Files
Triforce-Source/launcher/LogicTests/Tests.Hardening.cs
ruckus7382sfgsgdf b527e29adb Triforce v0.8.5
A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
2026-11-28 10:54:41 -06:00

140 lines
8.9 KiB
C#

using System.Buffers.Binary;
using System.Diagnostics;
using System.Text;
using Triforce.Core.GameFiles;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
/// <summary>((Triforce, 11-26) The launcher's security and edge-case audit: what a crafted or damaged input, a server that sends
/// more than it says, or a name the launcher did not expect now does (refused with a reason, never a crash or a lost file).</summary>
static partial class Tests
{
// ---------------- names and numbers from folders and output ----------------
static void HardeningNames()
{
// (a mods folder whose number is in another script's digits: a name, not a crash that empties the Mods page)
var (_, num, name) = Mods.Parse("01-Skins");
Equal(null, num, "full-width digits are no number");
Equal("01-Skins", name, "the name whole");
Equal(1, Mods.Parse("-01-Skins").Number, "ASCII digits still are");
// (the build's step times: a number too large for an int is no time, not an exception in the output reader)
var steps = BuildProtocol.ParseSteps("x 99999999999:00, read 1:32");
Check(!steps.ContainsKey("x") && steps["read"] == 92, "an overlong number left out, the rest read");
// (the benchmark's verdict is HTML on the page: a place's name from the results file is encoded)
Check(Benchmark.SkippedNote(new[] { "<img src=x>" }).Contains("&lt;img src=x&gt;"), "a place's name encoded");
// (release notes: a long line of [ no longer takes quadratic time)
var sw = Stopwatch.StartNew();
ReleaseNotes.Plain(new string('[', 60000));
Check(sw.Elapsed < TimeSpan.FromSeconds(2), "a long line of [ read in " + sw.ElapsedMilliseconds + " ms");
// (names only the launcher makes beside a save folder: a player's own "<save>.old" is never taken for its)
Check(Partial.Suffix == ".triforce-partial" && Partial.Aside == ".triforce-old", "the launcher's own names");
Check(Uninstaller.OwnFolders.Contains(Randomizer.WorkFolder), "the randomizer's folder goes with an uninstall");
var root = NewRoot("hardening-names");
Check(new Ootrr(Ctx(root)).Folder.StartsWith(Path.Combine(Ctx(root).Home, Randomizer.WorkFolder), StringComparison.OrdinalIgnoreCase),
"OOTRR lives in the randomizer's folder, not in tools (which a tools update replaces whole)");
}
// ---------------- downloads ----------------
static async Task HardeningDownloads()
{
using var s = new FakeServer();
var root = NewRoot("hardening-downloads");
var ctx = Ctx(root);
using var http = Downloader.CreateHttp();
var d = new Downloader(ctx);
// (an address that is not https is not fetched; a test's own 127.0.0.1 server only in a test run)
var plain = Path.Combine(root, "plain.bin");
await ThrowsAsync<IOException>(() => d.ToFileAsync(http, "http://example.invalid/x.zip", plain, 0, null, CancellationToken.None), "plain http refused");
Equal(0, s.Requests, "nothing asked of any server");
// (no size listed: the most it may be; a server that offers more is refused, nothing kept)
s.Add("/big", new byte[100_000]);
var big = Path.Combine(root, "big.bin");
var e = await ThrowsAsync<IOException>(() => d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 50_000), "more than the most");
Check(e.Message.Contains("more than"), "said: " + e.Message);
Check(!File.Exists(big) && !File.Exists(big + ".part"), "nothing of it kept");
await d.ToFileAsync(http, s.Url + "/big", big, 0, null, CancellationToken.None, most: 200_000);
Equal(100_000L, new FileInfo(big).Length, "within the most: downloaded");
// (a JSON answer read whole, but no more than its limit once unpacked)
await ThrowsAsync<IOException>(() => Downloader.TextAsync(new ByteArrayContent(new byte[5000]), 4000, CancellationToken.None), "an answer over its limit");
Equal("{\"a\":1}", await Downloader.TextAsync(new StringContent("{\"a\":1}"), 4000, CancellationToken.None), "an answer within it");
}
// ---------------- files the launcher changes ----------------
static void HardeningFiles()
{
var root = NewRoot("hardening-files");
// (the benchmark's settings: every line of a key set, the file's bytes and line ends kept)
var ini = Path.Combine(root, "triforce_options.ini");
File.WriteAllBytes(ini, Encoding.Latin1.GetBytes("a=1\r\nb=2\r\na=3\r\nname=café\r\n"));
BenchIni.Set(ini, new Dictionary<string, int> { ["a"] = 9, ["c"] = 4 });
Equal("a=9\r\nb=2\r\na=9\r\nname=café\r\nc=4\r\n", Encoding.Latin1.GetString(File.ReadAllBytes(ini)), "both a lines, CRLF and the byte 0xE9 kept, c added");
var back = Path.Combine(root, "backup.ini");
File.WriteAllText(back, "x=1\n");
BenchIni.Restore(back, ini);
Check(File.ReadAllText(ini) == "x=1\n" && !File.Exists(ini + ".new"), "put back in one step");
// (the texture pack's Remove: its own pictures and list go; what else a player keeps there stays)
var game = Path.Combine(root, "game");
var pack = TexturePack.Folder(game);
Directory.CreateDirectory(Path.Combine(pack, "mine"));
File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p");
File.WriteAllText(Path.Combine(pack, "0123456789abcdef_m1.png.new"), "p");
File.WriteAllText(Path.Combine(pack, TexturePack.StateName), "{}");
File.WriteAllText(Path.Combine(pack, "notes.txt"), "mine");
File.WriteAllText(Path.Combine(pack, "mine", "x.png"), "mine");
new TexturePack(Ctx(root)).Remove(game);
Check(!File.Exists(Path.Combine(pack, "0123456789abcdef.png")) && !File.Exists(Path.Combine(pack, TexturePack.StateName)) &&
!File.Exists(Path.Combine(pack, "0123456789abcdef_m1.png.new")), "the pack's files gone");
Check(File.Exists(Path.Combine(pack, "notes.txt")) && File.Exists(Path.Combine(pack, "mine", "x.png")), "the player's files kept");
Directory.Delete(Path.Combine(pack, "mine"), true);
File.Delete(Path.Combine(pack, "notes.txt"));
File.WriteAllText(Path.Combine(pack, "0123456789abcdef.png"), "p");
new TexturePack(Ctx(root)).Remove(game);
Check(!Directory.Exists(pack), "nothing else in it: the folder goes");
}
// ---------------- game files that are damaged or made to harm ----------------
static void HardeningParsers()
{
// (a texture archive that names 131072 textures in a few bytes: refused at once, not 17 GB of names)
var bntx = new byte[0x40];
"BNTX"u8.CopyTo(bntx);
BinaryPrimitives.WriteUInt32LittleEndian(bntx.AsSpan(0x24), 131072);
BinaryPrimitives.WriteUInt64LittleEndian(bntx.AsSpan(0x28), 0x30);
var sw = Stopwatch.StartNew();
Throws<InvalidDataException>(() => new Bntx(bntx), "a texture table larger than the file");
// (two entries that point at one texture: refused)
var twice = new byte[0x200];
"BNTX"u8.CopyTo(twice);
BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 2);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x28), 0x30);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x30), 0x80);
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x38), 0x80);
"BRTI"u8.CopyTo(twice.AsSpan(0x80));
BinaryPrimitives.WriteUInt64LittleEndian(twice.AsSpan(0x80 + 0x60), 0x180);
Throws<InvalidDataException>(() => new Bntx(twice), "one texture named twice");
// (a texture name longer than a name is)
BinaryPrimitives.WriteUInt32LittleEndian(twice.AsSpan(0x24), 1);
BinaryPrimitives.WriteUInt16LittleEndian(twice.AsSpan(0x180), 0xFFFF);
Throws<InvalidDataException>(() => new Bntx(twice), "a 64K-character name");
Check(sw.Elapsed < TimeSpan.FromSeconds(2), "refused at once: " + sw.ElapsedMilliseconds + " ms");
// (a zstd frame that unpacks to more than it may: refused, whether it says its size or not)
var frame = new ZstdSharp.Compressor().Wrap(new byte[100_000]).ToArray();
Throws<InvalidDataException>(() => Zs.Decompress(frame, null, 10_000), "a frame that says it is larger than the most");
Equal(100_000, Zs.Decompress(frame, null).Length, "within the most: unpacked");
// (a texture's sizes from its header, checked before anything is allocated)
Throws<InvalidDataException>(() => ImageLimits.Check(0, 16), "no width");
Throws<InvalidDataException>(() => ImageLimits.Check(70000, 16), "wider than any texture");
Throws<InvalidDataException>(() => BlockCompression.Decode(new byte[64], 40000, 40000, BlockCompression.Kind.BC1), "a BC1 texture of 40000 x 40000");
Throws<InvalidDataException>(() => BlockLinear.Deswizzle(new byte[64], 16384, 32767, 4, 0), "a 2 GB deswizzle from a 64-byte texture");
}
}