merge: Campaign LA LA3 - Launcher.Core review-closed

This commit is contained in:
Erik 2026-08-14 17:11:25 +02:00
commit 7749545dc4
33 changed files with 4477 additions and 0 deletions

View file

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<LangVersion>latest</LangVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\AcDream.Launcher.Core\AcDream.Launcher.Core.csproj" />
<ProjectReference Include="..\..\src\AcDream.Platform\AcDream.Platform.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,98 @@
using System.Security.Cryptography;
using System.Text;
using AcDream.Launcher.Core.Integrity;
namespace AcDream.Launcher.Core.Tests.Integrity;
public sealed class FileIntegrityTests : IDisposable
{
private readonly string _root;
public FileIntegrityTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-integrity-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void ComputeSha256HexMatchesTheFrameworkHasher()
{
string path = Path.Combine(_root, "file.bin");
byte[] content = Encoding.UTF8.GetBytes("acdream launcher integrity fixture");
File.WriteAllBytes(path, content);
string expected = Convert.ToHexStringLower(SHA256.HashData(content));
string actual = FileIntegrity.ComputeSha256Hex(path);
Assert.Equal(expected, actual);
}
[Fact]
public async Task ComputeSha256HexAsyncMatchesTheSyncResult()
{
string path = Path.Combine(_root, "file.bin");
File.WriteAllBytes(path, Encoding.UTF8.GetBytes("async path fixture"));
string sync = FileIntegrity.ComputeSha256Hex(path);
string asyncResult = await FileIntegrity.ComputeSha256HexAsync(path);
Assert.Equal(sync, asyncResult);
}
[Fact]
public void VerifySucceedsForAMatchingDigestRegardlessOfCase()
{
string path = Path.Combine(_root, "file.bin");
File.WriteAllBytes(path, Encoding.UTF8.GetBytes("case-insensitive fixture"));
string lower = FileIntegrity.ComputeSha256Hex(path);
Assert.True(FileIntegrity.Verify(path, lower));
Assert.True(FileIntegrity.Verify(path, lower.ToUpperInvariant()));
}
[Fact]
public void VerifyFailsForAMismatchedDigest()
{
string path = Path.Combine(_root, "file.bin");
File.WriteAllBytes(path, Encoding.UTF8.GetBytes("original content"));
Assert.False(FileIntegrity.Verify(path, new string('0', 64)));
}
[Fact]
public void DifferentContentProducesDifferentDigests()
{
string pathA = Path.Combine(_root, "a.bin");
string pathB = Path.Combine(_root, "b.bin");
File.WriteAllBytes(pathA, Encoding.UTF8.GetBytes("content A"));
File.WriteAllBytes(pathB, Encoding.UTF8.GetBytes("content B"));
Assert.NotEqual(
FileIntegrity.ComputeSha256Hex(pathA),
FileIntegrity.ComputeSha256Hex(pathB));
}
[Fact]
public void EmptyFileHashesToTheWellKnownSha256OfEmptyInput()
{
string path = Path.Combine(_root, "empty.bin");
File.WriteAllBytes(path, []);
string actual = FileIntegrity.ComputeSha256Hex(path);
Assert.Equal(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
actual);
}
}

View file

@ -0,0 +1,79 @@
using System.Runtime.CompilerServices;
using System.Xml.Linq;
namespace AcDream.Launcher.Core.Tests;
// Campaign LA plan §LA3 review finding F5: AcDream.Launcher.Core's entire
// premise (spec §LA3, SessionConfigDocument.cs's "PINNED CONTRACT" remarks)
// is being the BCL-plus-Platform-only assembly the external Avalonia
// launcher (LA4) can reference without pulling in any game-solution
// dependency. That contract is what this guard enforces — the csproj must
// declare exactly one ProjectReference (AcDream.Platform) and zero
// PackageReference entries, forever, in the same spirit as Platform's,
// Runtime's, and Headless's dependency-boundary guards.
public sealed class LauncherCoreDependencyBoundaryTests
{
[Fact]
public void LauncherCoreProjectReferencesOnlyPlatformAndDeclaresNoPackages()
{
string repositoryRoot = FindRepositoryRoot();
string projectPath = Path.Combine(
repositoryRoot,
"src",
"AcDream.Launcher.Core",
"AcDream.Launcher.Core.csproj");
var project = XDocument.Load(projectPath);
var projectReferences = project.Descendants("ProjectReference")
.Select(element => element.Attribute("Include")?.Value)
// The csproj is authored with Windows-style "..\Foo\Foo.csproj"
// separators; Path.GetFileName only recognizes the platform's
// own separator, so on Linux it would return the whole
// relative path unchanged instead of just the filename.
// Normalizing to '/' first keeps this assertion
// platform-agnostic (this project's tests run under both
// native Windows and WSL — see Campaign LA plan §LA3 review
// finding F5's acceptance).
.Select(include => include is null
? null
: Path.GetFileName(include.Replace('\\', '/')))
.ToList();
Assert.Equal(["AcDream.Platform.csproj"], projectReferences);
Assert.Empty(project.Descendants("PackageReference"));
}
private static string FindRepositoryRoot(
[CallerFilePath] string sourcePath = "")
{
string[] starts =
{
Path.GetDirectoryName(sourcePath) ?? string.Empty,
Directory.GetCurrentDirectory(),
AppContext.BaseDirectory,
};
foreach (string start in starts)
{
if (string.IsNullOrEmpty(start))
{
continue;
}
var directory = new DirectoryInfo(start);
while (directory is not null)
{
if (File.Exists(Path.Combine(
directory.FullName,
"AcDream.slnx")))
{
return directory.FullName;
}
directory = directory.Parent;
}
}
throw new DirectoryNotFoundException(
"Could not find AcDream.slnx above the source, working, or output directory.");
}
}

View file

@ -0,0 +1,525 @@
using System.Collections.Concurrent;
using System.Threading;
using AcDream.Launcher.Core.Launching;
namespace AcDream.Launcher.Core.Tests.Launching;
public sealed class LauncherProcessSupervisorTests
{
[Fact]
public void StartWritesPasswordThenClosesStdinAndTransitionsToRunning()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
var states = new List<LauncherSessionState>();
supervisor.StateChanged += (_, s) => states.Add(s);
supervisor.Start(Spec(), "S3cretPassw0rd!");
FakeChildProcess fake = factory.LastCreated!;
Assert.True(fake.Started);
Assert.Equal("S3cretPassw0rd!\n", fake.StandardInputText);
Assert.True(fake.StandardInputClosed);
Assert.Equal(LauncherSessionState.Running, supervisor.State);
Assert.Equal(
[LauncherSessionState.Starting, LauncherSessionState.Running],
states);
}
[Fact]
public void StartWithNullPasswordClosesStdinWithoutWriting()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), password: null);
FakeChildProcess fake = factory.LastCreated!;
Assert.Equal(string.Empty, fake.StandardInputText);
Assert.True(fake.StandardInputClosed);
}
[Fact]
public void StartTwiceOnTheSameSupervisorThrows()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), "pw");
Assert.Throws<InvalidOperationException>(() => supervisor.Start(Spec(), "pw"));
}
[Fact]
public void StopCallsCloseMainWindowAndSucceedsWithoutKillWhenTheProcessExitsInTime()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), "pw");
supervisor.Stop(TimeSpan.FromMilliseconds(50));
FakeChildProcess fake = factory.LastCreated!;
Assert.True(fake.CloseMainWindowCalled);
Assert.Equal(0, fake.KillCallCount);
Assert.Equal(LauncherSessionState.Exited, supervisor.State);
Assert.Equal(0, supervisor.ExitCode);
}
[Fact]
public void StopFallsBackToKillWhenTheProcessDoesNotExitWithinTheTimeout()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: false);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), "pw");
supervisor.Stop(TimeSpan.FromMilliseconds(50));
FakeChildProcess fake = factory.LastCreated!;
Assert.True(fake.CloseMainWindowCalled);
Assert.Equal(1, fake.KillCallCount);
Assert.Equal(LauncherSessionState.Exited, supervisor.State);
}
[Fact]
public void StopIsANoOpBeforeStart()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Stop(TimeSpan.FromMilliseconds(50));
Assert.Null(factory.LastCreated);
Assert.Equal(LauncherSessionState.Starting, supervisor.State);
}
[Fact]
public void StopIsANoOpAfterTheProcessHasAlreadyExited()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), "pw");
supervisor.Stop(TimeSpan.FromMilliseconds(50));
FakeChildProcess fake = factory.LastCreated!;
Assert.Equal(0, fake.KillCallCount);
supervisor.Stop(TimeSpan.FromMilliseconds(50));
// CloseMainWindow was called exactly once (the first Stop) —
// Stop after exit does not re-invoke the graceful/kill dance.
Assert.Equal(1, fake.CloseMainWindowCallCount);
Assert.Equal(0, fake.KillCallCount);
}
[Fact]
public void StopAttemptsTheGracefulStopSignalBeforeCloseMainWindow()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
supervisor.Start(Spec(), "pw");
supervisor.Stop(TimeSpan.FromMilliseconds(50));
FakeChildProcess fake = factory.LastCreated!;
Assert.Equal(1, fake.TryRequestGracefulStopCallCount);
Assert.Equal(["gracefulStop", "closeMainWindow"], fake.CallOrder);
}
[Fact]
public void GracefulStopSignalSendsSigintToARealChildOnLinux()
{
// Review finding F3, proven end to end against the real
// SystemChildProcess: Stop() sends SIGINT before falling back to
// CloseMainWindow/Kill, and the trapped child exits gracefully
// with code 0 well within the timeout. A hard SIGKILL fallback
// (or a signal arriving before the shell's trap is even armed,
// which falls back to the shell's default SIGINT disposition —
// terminate with exit 128+2=130) would not produce this clean
// exit code, so ExitCode == 0 is a hermetic proof the graceful
// path is what actually stopped the child.
if (!OperatingSystem.IsLinux())
return;
string readyMarker = Path.Combine(
Path.GetTempPath(), "acdream-la3-sigint-" + Guid.NewGuid().ToString("N"));
try
{
using var supervisor = new LauncherProcessSupervisor();
var exited = new ManualResetEventSlim(false);
supervisor.StateChanged += (_, s) =>
{
if (s == LauncherSessionState.Exited)
exited.Set();
};
supervisor.Start(
new LauncherProcessSpec(
"/bin/bash",
[
"-c",
"trap 'kill $child 2>/dev/null; exit 0' INT; "
+ "sleep 30 & child=$!; "
+ $"touch '{readyMarker}'; "
+ "wait $child",
]),
password: null);
// Wait for the child to prove its SIGINT trap is armed AND
// its background `sleep` is tracked (touch runs after both,
// in program order) before sending the signal — otherwise
// this test would race the shell's own startup and
// intermittently observe the shell's default SIGINT
// disposition instead of the trap, or leave an untracked
// orphaned `sleep`.
DateTime readyDeadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
while (!File.Exists(readyMarker) && DateTime.UtcNow < readyDeadline)
{
Thread.Sleep(10);
}
Assert.True(
File.Exists(readyMarker),
"child did not signal trap-armed readiness in time");
supervisor.Stop(TimeSpan.FromSeconds(10));
Assert.True(exited.Wait(TimeSpan.FromSeconds(5)));
Assert.Equal(0, supervisor.ExitCode);
}
finally
{
try
{
File.Delete(readyMarker);
}
catch (IOException)
{
}
}
}
[Fact]
public void StartKillsAndDisposesTheChildWhenFeedingStdinThrowsAfterTheProcessHasStarted()
{
var factory = new FakeChildProcessFactory(
exitsWithinStopTimeout: true,
throwOnStandardInputWrite: true);
using var supervisor = new LauncherProcessSupervisor(factory);
Assert.ThrowsAny<Exception>(() => supervisor.Start(Spec(), "pw"));
FakeChildProcess fake = factory.LastCreated!;
Assert.True(fake.Started);
Assert.Equal(1, fake.KillCallCount);
Assert.True(fake.Disposed);
}
[Fact]
public void SetStateIsMonotonicAndIgnoresATransitionAfterExited()
{
// Simulates the child exiting synchronously from inside
// process.Start() itself (a child that dies immediately) — the
// trailing SetState(Running) at the end of Start() must not
// resurrect State from the terminal Exited it already reached,
// nor fire a spurious StateChanged(Running).
var factory = new FakeChildProcessFactory(
exitsWithinStopTimeout: true,
exitDuringStart: true);
using var supervisor = new LauncherProcessSupervisor(factory);
var states = new List<LauncherSessionState>();
supervisor.StateChanged += (_, s) => states.Add(s);
supervisor.Start(Spec(), "pw");
Assert.Equal(LauncherSessionState.Exited, supervisor.State);
Assert.Equal(
[LauncherSessionState.Starting, LauncherSessionState.Exited],
states);
}
[Fact]
public async Task ConcurrentRunningAndExitedPublicationsRemainMonotonicAndInOrder()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
using var runningPublicationEntered = new ManualResetEventSlim(false);
using var releaseRunningPublication = new ManualResetEventSlim(false);
var states = new ConcurrentQueue<LauncherSessionState>();
supervisor.StateChanged += (_, state) =>
{
if (state == LauncherSessionState.Running)
{
runningPublicationEntered.Set();
Assert.True(
releaseRunningPublication.Wait(TimeSpan.FromSeconds(5)),
"test did not release the Running publication barrier");
}
states.Enqueue(state);
};
Task startTask = Task.Run(() => supervisor.Start(Spec(), "pw"));
try
{
Assert.True(
runningPublicationEntered.Wait(TimeSpan.FromSeconds(5)),
"Running publication did not reach the test barrier");
// Commit Exited while Running's observer is deliberately
// paused. Storage reaches the terminal state immediately, but
// publication must queue behind the earlier Running event.
factory.LastCreated!.ExitForTest(17);
Assert.Equal(LauncherSessionState.Exited, supervisor.State);
}
finally
{
releaseRunningPublication.Set();
}
await startTask.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(
[
LauncherSessionState.Starting,
LauncherSessionState.Running,
LauncherSessionState.Exited,
],
states);
Assert.Equal(17, supervisor.ExitCode);
}
[Fact]
public void StateChangedPublicationAllowsCrossThreadReadsAndReentrantExit()
{
var factory = new FakeChildProcessFactory(exitsWithinStopTimeout: true);
using var supervisor = new LauncherProcessSupervisor(factory);
var states = new List<LauncherSessionState>();
supervisor.StateChanged += (_, state) =>
{
states.Add(state);
if (state != LauncherSessionState.Running)
{
return;
}
// A publisher that invokes callbacks while holding the state
// gate deadlocks this cross-thread read. The callback also
// raises Exited re-entrantly; it must queue after Running rather
// than recurse out of order or deadlock.
Task<LauncherSessionState> readTask = Task.Run(() => supervisor.State);
Assert.True(readTask.Wait(TimeSpan.FromSeconds(5)));
Assert.Equal(LauncherSessionState.Running, readTask.Result);
factory.LastCreated!.ExitForTest(23);
};
supervisor.Start(Spec(), "pw");
Assert.Equal(
[
LauncherSessionState.Starting,
LauncherSessionState.Running,
LauncherSessionState.Exited,
],
states);
Assert.Equal(LauncherSessionState.Exited, supervisor.State);
Assert.Equal(23, supervisor.ExitCode);
}
[Fact]
public void LauncherProcessSpecCarriesNoCredentialLikeMember()
{
// Defense in depth: the password must never be able to reach
// process arguments or environment (Campaign LA plan §LA3). This
// guards against a future field addition accidentally widening
// that surface.
System.Reflection.PropertyInfo[] properties =
typeof(LauncherProcessSpec).GetProperties();
Assert.DoesNotContain(
properties,
p => p.Name.Contains("password", StringComparison.OrdinalIgnoreCase)
|| p.Name.Contains("credential", StringComparison.OrdinalIgnoreCase));
}
[Fact]
public void RealProcessSpawnFeedsStdinAndCapturesExitCode()
{
// The "trivial cross-platform fake child" (plan §LA3 acceptance):
// `dotnet --version` is guaranteed present (we're running under
// `dotnet test`) on both Windows and Linux/WSL, ignores stdin
// entirely, and reliably exits 0 — proving the REAL
// SystemChildProcessFactory spawn/stdin-feed/exit-code-capture
// path end to end without any OS-specific script branching.
string dotnet = FindDotnetExecutable();
using var supervisor = new LauncherProcessSupervisor();
var exited = new ManualResetEventSlim(false);
supervisor.StateChanged += (_, s) =>
{
if (s == LauncherSessionState.Exited)
exited.Set();
};
supervisor.Start(
new LauncherProcessSpec(dotnet, ["--version"]),
"unused-password-ignored-by-dotnet");
bool completed = exited.Wait(TimeSpan.FromSeconds(30));
Assert.True(completed, "the real dotnet --version child did not exit within 30s");
Assert.Equal(0, supervisor.ExitCode);
}
private static LauncherProcessSpec Spec() =>
new("fake-host", ["--session-config", "session.json"]);
private static string FindDotnetExecutable() =>
// PATH-based resolution: .NET Core's Process.Start searches PATH
// for a bare filename when UseShellExecute is false, on both
// Windows and Unix, and `dotnet` is guaranteed on PATH here
// because this test is itself running under `dotnet test`.
OperatingSystem.IsWindows() ? "dotnet.exe" : "dotnet";
private sealed class FakeChildProcessFactory(
bool exitsWithinStopTimeout,
bool exitDuringStart = false,
bool throwOnStandardInputWrite = false)
: ILauncherChildProcessFactory
{
public FakeChildProcess? LastCreated { get; private set; }
public ILauncherChildProcess Create(LauncherProcessSpec spec)
{
LastCreated = new FakeChildProcess(
spec,
exitsWithinStopTimeout,
exitDuringStart,
throwOnStandardInputWrite);
return LastCreated;
}
}
private sealed class FakeChildProcess(
LauncherProcessSpec spec,
bool exitsWithinStopTimeout,
bool exitDuringStart = false,
bool throwOnStandardInputWrite = false)
: ILauncherChildProcess
{
private readonly RecordingTextWriter _standardInput = new();
private readonly ThrowingTextWriter _throwingStandardInput = new();
public LauncherProcessSpec Spec { get; } = spec;
public bool Started { get; private set; }
public string StandardInputText => _standardInput.ToString();
public bool StandardInputClosed => _standardInput.IsClosed;
public bool CloseMainWindowCalled => CloseMainWindowCallCount > 0;
public int CloseMainWindowCallCount { get; private set; }
public int TryRequestGracefulStopCallCount { get; private set; }
public int KillCallCount { get; private set; }
public bool Disposed { get; private set; }
/// <summary>Records the order <see cref="TryRequestGracefulStop"/>,
/// <see cref="CloseMainWindow"/>, and <see cref="Kill"/> were
/// actually invoked in — review finding F3's ordering guarantee.
/// </summary>
public List<string> CallOrder { get; } = [];
public bool HasExited { get; private set; }
public int ExitCode { get; private set; }
public TextWriter StandardInput =>
throwOnStandardInputWrite ? _throwingStandardInput : _standardInput;
public event EventHandler? Exited;
public void Start()
{
Started = true;
if (exitDuringStart)
{
// Simulates a child that dies synchronously from inside
// Process.Start() itself (review finding F9's race).
ExitForTest(0);
}
}
public void ExitForTest(int exitCode)
{
if (HasExited)
{
return;
}
HasExited = true;
ExitCode = exitCode;
Exited?.Invoke(this, EventArgs.Empty);
}
public bool TryRequestGracefulStop()
{
TryRequestGracefulStopCallCount++;
CallOrder.Add("gracefulStop");
return false;
}
public bool CloseMainWindow()
{
CloseMainWindowCallCount++;
CallOrder.Add("closeMainWindow");
return true;
}
public void Kill()
{
KillCallCount++;
CallOrder.Add("kill");
ExitForTest(-1);
}
public bool WaitForExit(TimeSpan timeout)
{
if (!exitsWithinStopTimeout)
return false;
ExitForTest(0);
return true;
}
public void Dispose()
{
Disposed = true;
}
}
private sealed class RecordingTextWriter : StringWriter
{
public bool IsClosed { get; private set; }
protected override void Dispose(bool disposing)
{
IsClosed = true;
base.Dispose(disposing);
}
}
/// <summary>Simulates a broken stdin pipe (review finding F8): the
/// child process started successfully, but feeding it the password
/// fails.</summary>
private sealed class ThrowingTextWriter : StringWriter
{
public override void Write(string? value) =>
throw new IOException("simulated broken stdin pipe");
public override void Write(char value) =>
throw new IOException("simulated broken stdin pipe");
}
}

View file

@ -0,0 +1,398 @@
using System.Text.Json.Nodes;
using AcDream.Launcher.Core.Launching;
using AcDream.Launcher.Core.Profiles;
using AcDream.Platform;
namespace AcDream.Launcher.Core.Tests.Launching;
/// <summary>
/// Golden-shape tests for <see cref="SessionConfigComposer"/> against the
/// Campaign LA plan §LA3 pinned contract: exactly the listed keys, exact
/// camelCase names, character/policy presence rules per launch mode, and
/// (critically) no password anywhere in the document.
/// </summary>
public sealed class SessionConfigComposerTests
{
private static readonly ApplicationPathSet Paths = new(
ConfigDirectory: "/cfg/acdream",
DataDirectory: "/data/acdream",
CacheDirectory: "/cache/acdream",
LegacyConfigDirectory: null);
private static readonly LauncherInstallRecord Install = new(
DatDirectory: "/dats",
PreparedAssetPath: "/data/acdream/pak/acdream.pak");
private static ServerProfile Server() =>
new() { Name = "Local ACE", Host = "127.0.0.1", Port = 9000 };
private static AccountProfile Account() =>
new() { Account = "testaccount", Password = "S3cretPassw0rd!" };
private static CharacterProfile Character(LaunchMode mode, string? id = "0x5000000A") =>
new()
{
Name = "+Acdream",
Id = id,
LaunchMode = mode,
Plugins = ["ExamplePlugin"],
LoginCommands = ["/tell someone, hi"],
};
[Fact]
public void GuiModeIncludesCharacterSelectorAndOmitsPolicy()
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Gui),
Install,
Paths,
sessionId: "session-gui");
JsonObject session = SingleSession(composed);
AssertKeys(
session,
"id", "endpoint", "account", "character", "credential",
"plugins", "loginCommands", "statusFile");
Assert.Equal("session-gui", (string?)session["id"]);
Assert.Equal("testaccount", (string?)session["account"]);
Assert.Equal(0x5000000Au, (uint?)session["character"]!["id"]);
Assert.Null(session["character"]!["name"]);
Assert.Null(session["character"]!["index"]);
Assert.Equal("standardInput", (string?)session["credential"]!["provider"]);
Assert.Equal("session", (string?)session["credential"]!["reference"]);
Assert.Equal(
new[] { "ExamplePlugin" },
session["plugins"]!.AsArray().Select(n => (string?)n));
Assert.Equal(
new[] { "/tell someone, hi" },
session["loginCommands"]!.AsArray().Select(n => (string?)n));
Assert.Equal(
Path.Combine(Paths.CacheDirectory, "launcher", "sessions", "session-gui", "status.jsonl"),
(string?)session["statusFile"]);
}
[Fact]
public void GuiSelectModeOmitsCharacterFieldEntirely()
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.GuiSelect),
Install,
Paths,
sessionId: "session-guiselect");
JsonObject session = SingleSession(composed);
AssertKeys(
session,
"id", "endpoint", "account", "credential",
"plugins", "loginCommands", "statusFile");
Assert.False(session.ContainsKey("character"));
Assert.False(session.ContainsKey("policy"));
}
[Fact]
public void HeadlessModeIncludesCharacterAndIdlePolicy()
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Headless),
Install,
Paths,
sessionId: "session-headless",
loginCommandDelayMs: 750);
JsonObject session = SingleSession(composed);
AssertKeys(
session,
"id", "endpoint", "account", "character", "policy", "credential",
"plugins", "loginCommands", "loginCommandDelayMs", "statusFile");
Assert.Equal(0x5000000Au, (uint?)session["character"]!["id"]);
Assert.Equal("idle", (string?)session["policy"]!["id"]);
Assert.Equal(750, (int?)session["loginCommandDelayMs"]);
}
[Fact]
public void GuiModeFallsBackToNameSelectorWhenIdIsMissing()
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Gui, id: null),
Install,
Paths,
sessionId: "session-gui-name");
JsonObject session = SingleSession(composed);
Assert.Null(session["character"]!["id"]);
Assert.Equal("+Acdream", (string?)session["character"]!["name"]);
}
[Fact]
public void GuiModeFallsBackToNameSelectorWhenIdIsAHandTypedDecimalWithoutThe0xPrefix()
{
// Review finding F10: an 8-digit all-decimal-digit string is ALSO
// a syntactically valid hex number. Without requiring the "0x"
// prefix, this used to silently reinterpret a hand-typed decimal
// id as hex and select the wrong character; it must now fall
// through to the name selector instead of guessing.
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Gui, id: "12345678"),
Install,
Paths,
sessionId: "session-gui-decimal-id");
JsonObject session = SingleSession(composed);
Assert.Null(session["character"]!["id"]);
Assert.Equal("+Acdream", (string?)session["character"]!["name"]);
}
[Fact]
public void GuiModeFallsBackToNameSelectorWhenTheParsedIdIsZero()
{
// Review finding F10: both host loaders reject `id: 0` outright,
// so a parsed-but-zero id is not a usable selector either.
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Gui, id: "0x00000000"),
Install,
Paths,
sessionId: "session-gui-zero-id");
JsonObject session = SingleSession(composed);
Assert.Null(session["character"]!["id"]);
Assert.Equal("+Acdream", (string?)session["character"]!["name"]);
}
[Fact]
public void PluginsAndLoginCommandsAreOmittedWhenEmptyRatherThanEmptyArrays()
{
CharacterProfile character = Character(LaunchMode.Gui);
character.Plugins = [];
character.LoginCommands = [];
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
character,
Install,
Paths,
sessionId: "session-empty-lists");
JsonObject session = SingleSession(composed);
Assert.False(session.ContainsKey("plugins"));
Assert.False(session.ContainsKey("loginCommands"));
}
[Fact]
public void ProcessContentCarriesInstallRecordAndPathsIsOmittedByDefault()
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(LaunchMode.Gui),
Install,
Paths,
sessionId: "session-content");
JsonObject root = ParseRoot(composed);
Assert.Equal(1, (int?)root["version"]);
JsonObject process = root["process"]!.AsObject();
// PINNED CONTRACT (review finding F1): process.paths is OMITTED
// entirely — not an empty object — unless a caller explicitly
// supplies overrides. The App-side loader parses with strict
// UnmappedMemberHandling.Disallow and has no `paths` member of
// its own, so an emitted "paths":{} would reject the whole
// document at config load for every gui/guiSelect launch.
AssertKeys(process, "content");
Assert.False(process.ContainsKey("paths"));
JsonObject content = process["content"]!.AsObject();
AssertKeys(content, "datDirectory", "preparedAssetPath");
Assert.Equal(Install.DatDirectory, (string?)content["datDirectory"]);
Assert.Equal(Install.PreparedAssetPath, (string?)content["preparedAssetPath"]);
}
[Fact]
public void NormalPlaySessionsOmitTheModeFieldEntirely()
{
foreach (LaunchMode mode in new[] { LaunchMode.Gui, LaunchMode.GuiSelect, LaunchMode.Headless })
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
Account(),
Character(mode),
Install,
Paths,
sessionId: $"session-mode-omit-{mode}");
JsonObject session = SingleSession(composed);
Assert.False(session.ContainsKey("mode"));
}
}
[Fact]
public void ProbeModeSetsModeAndOmitsCharacterPolicyPluginsAndLoginCommands()
{
ComposedSessionConfig composed = SessionConfigComposer.ComposeProbe(
Server(),
Account(),
Install,
Paths,
sessionId: "session-probe");
JsonObject session = SingleSession(composed);
AssertKeys(
session,
"id", "mode", "endpoint", "account", "credential", "statusFile");
Assert.Equal("session-probe", (string?)session["id"]);
Assert.Equal("probe", (string?)session["mode"]);
Assert.Equal("127.0.0.1", (string?)session["endpoint"]!["host"]);
Assert.Equal(9000, (int?)session["endpoint"]!["port"]);
Assert.Equal("testaccount", (string?)session["account"]);
Assert.Equal("standardInput", (string?)session["credential"]!["provider"]);
Assert.False(session.ContainsKey("character"));
Assert.False(session.ContainsKey("policy"));
Assert.False(session.ContainsKey("plugins"));
Assert.False(session.ContainsKey("loginCommands"));
Assert.False(session.ContainsKey("loginCommandDelayMs"));
Assert.Equal(
Path.Combine(
Paths.CacheDirectory, "launcher", "sessions", "session-probe", "status.jsonl"),
(string?)session["statusFile"]);
}
[Fact]
public void ProbeModeDocumentNeverContainsThePassword()
{
AccountProfile account = Account();
ComposedSessionConfig composed = SessionConfigComposer.ComposeProbe(
Server(),
account,
Install,
Paths,
sessionId: "session-probe-pw");
string json = SessionConfigComposer.Serialize(composed.Document);
Assert.DoesNotContain(account.Password, json, StringComparison.Ordinal);
}
[Fact]
public void ProbeModeProcessSettingsMatchNormalComposition()
{
ComposedSessionConfig composed = SessionConfigComposer.ComposeProbe(
Server(),
Account(),
Install,
Paths,
sessionId: "session-probe-content");
JsonObject root = ParseRoot(composed);
JsonObject process = root["process"]!.AsObject();
AssertKeys(process, "content");
JsonObject content = process["content"]!.AsObject();
Assert.Equal(Install.DatDirectory, (string?)content["datDirectory"]);
Assert.Equal(Install.PreparedAssetPath, (string?)content["preparedAssetPath"]);
}
[Fact]
public void ComposedDocumentNeverContainsThePassword()
{
AccountProfile account = Account();
foreach (LaunchMode mode in new[] { LaunchMode.Gui, LaunchMode.GuiSelect, LaunchMode.Headless })
{
ComposedSessionConfig composed = SessionConfigComposer.Compose(
Server(),
account,
Character(mode),
Install,
Paths,
sessionId: $"session-{mode}");
string json = SessionConfigComposer.Serialize(composed.Document);
Assert.DoesNotContain(account.Password, json, StringComparison.Ordinal);
}
}
[Fact]
public void ComposeAndWriteWritesSessionJsonUnderTheExpectedPath()
{
string root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-composer-tests",
Guid.NewGuid().ToString("N"));
try
{
var paths = new ApplicationPathSet(
Path.Combine(root, "cfg"),
Path.Combine(root, "data"),
Path.Combine(root, "cache"),
null);
ComposedSessionConfig composed = SessionConfigComposer.ComposeAndWrite(
Server(),
Account(),
Character(LaunchMode.Gui),
Install,
paths,
sessionId: "session-write");
string expectedPath = Path.Combine(
paths.CacheDirectory, "launcher", "sessions", "session-write", "session.json");
Assert.Equal(expectedPath, composed.ConfigFilePath);
Assert.True(File.Exists(expectedPath));
string text = File.ReadAllText(expectedPath);
Assert.DoesNotContain(Account().Password, text, StringComparison.Ordinal);
}
finally
{
if (Directory.Exists(root))
{
Directory.Delete(root, recursive: true);
}
}
}
private static JsonObject ParseRoot(ComposedSessionConfig composed)
{
string json = SessionConfigComposer.Serialize(composed.Document);
return JsonNode.Parse(json)!.AsObject();
}
private static JsonObject SingleSession(ComposedSessionConfig composed)
{
JsonObject root = ParseRoot(composed);
JsonArray sessions = root["sessions"]!.AsArray();
return Assert.Single(sessions)!.AsObject();
}
/// <summary>
/// Asserts the object's property set is EXACTLY the given keys — no
/// more, no fewer — without depending on reflection-based member
/// enumeration order (only the presence/absence of each pinned-
/// contract key is a guarantee this slice makes).
/// </summary>
private static void AssertKeys(JsonObject obj, params string[] expectedKeys)
{
var actual = new HashSet<string>(obj.Select(kv => kv.Key), StringComparer.Ordinal);
var expected = new HashSet<string>(expectedKeys, StringComparer.Ordinal);
Assert.Equal(expected, actual);
}
}

View file

@ -0,0 +1,50 @@
using AcDream.Launcher.Core.Profiles;
namespace AcDream.Launcher.Core.Tests.Profiles;
public sealed class CharacterIdFormatTests
{
[Fact]
public void ToHexStringFormatsEightDigitUppercaseWithPrefix()
{
Assert.Equal("0x5000000A", CharacterIdFormat.ToHexString(0x5000000Au));
Assert.Equal("0x00000001", CharacterIdFormat.ToHexString(1u));
}
[Theory]
[InlineData("0x5000000A", 0x5000000Au)]
[InlineData("0x5000000a", 0x5000000Au)]
[InlineData("0X5000000A", 0x5000000Au)]
public void TryParseAcceptsThe0xPrefixCaseInsensitively(string text, uint expected)
{
Assert.True(CharacterIdFormat.TryParse(text, out uint id));
Assert.Equal(expected, id);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("not-hex")]
[InlineData("5000000A")]
[InlineData("12345678")]
public void TryParseRejectsNullEmptyNonHexOrAnUnprefixedString(string? text)
{
// "5000000A"/"12345678" are all-hex-digit strings that would
// parse fine as hex WITHOUT the "0x" prefix — review finding F10
// requires the prefix precisely so a hand-typed decimal id (which
// is ALSO syntactically valid hex) is never silently
// misinterpreted as one.
Assert.False(CharacterIdFormat.TryParse(text, out uint id));
Assert.Equal(0u, id);
}
[Fact]
public void RoundTripsThroughToHexStringAndTryParse()
{
const uint original = 0x5000000Au;
string text = CharacterIdFormat.ToHexString(original);
Assert.True(CharacterIdFormat.TryParse(text, out uint parsed));
Assert.Equal(original, parsed);
}
}

View file

@ -0,0 +1,362 @@
using AcDream.Launcher.Core.Profiles;
namespace AcDream.Launcher.Core.Tests.Profiles;
public sealed class LauncherProfileStoreTests : IDisposable
{
private readonly string _root;
private readonly string _filePath;
public LauncherProfileStoreTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-profile-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_filePath = Path.Combine(_root, "launcher-profiles.json");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void LoadOnMissingFileYieldsEmptyDocumentWithoutTouchingDisk()
{
var store = new LauncherProfileStore(_filePath);
bool loaded = store.Load();
Assert.False(loaded);
Assert.False(File.Exists(_filePath));
Assert.Equal(1, store.Document.Version);
Assert.Empty(store.Document.Servers);
}
[Fact]
public void AddServerThenSaveThenReloadRoundTrips()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.Save();
Assert.True(File.Exists(_filePath));
var reloaded = new LauncherProfileStore(_filePath);
reloaded.Load();
ServerProfile server = Assert.Single(reloaded.Document.Servers);
Assert.Equal("Local ACE", server.Name);
Assert.Equal("127.0.0.1", server.Host);
Assert.Equal(9000, server.Port);
Assert.Empty(server.Accounts);
}
[Fact]
public void AddServerRejectsDuplicateName()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
var ex = Assert.Throws<LauncherProfileException>(
() => store.AddServer("Local ACE", "127.0.0.1", 9001));
Assert.Contains("Local ACE", ex.Message);
}
[Theory]
[InlineData(0)]
[InlineData(65536)]
[InlineData(-1)]
public void AddServerRejectsOutOfRangePort(int port)
{
var store = new LauncherProfileStore(_filePath);
store.Load();
Assert.Throws<LauncherProfileException>(
() => store.AddServer("Local ACE", "127.0.0.1", port));
}
[Fact]
public void EditServerRenamesAndUpdatesHostAndPort()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.EditServer("Local ACE", newName: "Home ACE", newHost: "10.0.0.5", newPort: 9001);
ServerProfile server = Assert.Single(store.Document.Servers);
Assert.Equal("Home ACE", server.Name);
Assert.Equal("10.0.0.5", server.Host);
Assert.Equal(9001, server.Port);
}
[Fact]
public void EditServerOnUnknownNameThrows()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
Assert.Throws<LauncherProfileException>(
() => store.EditServer("Nope", newHost: "1.2.3.4"));
}
[Fact]
public void RemoveServerRemovesIt()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.RemoveServer("Local ACE");
Assert.Empty(store.Document.Servers);
}
[Fact]
public void AddEditRemoveAccountRoundTrip()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "testpassword");
AccountProfile account = Assert.Single(
store.Document.Servers.Single().Accounts);
Assert.Equal("testaccount", account.Account);
Assert.Equal("testpassword", account.Password);
store.EditAccount(
"Local ACE",
"testaccount",
newAccount: "renamed",
newPassword: "newpass");
account = Assert.Single(store.Document.Servers.Single().Accounts);
Assert.Equal("renamed", account.Account);
Assert.Equal("newpass", account.Password);
store.RemoveAccount("Local ACE", "renamed");
Assert.Empty(store.Document.Servers.Single().Accounts);
}
[Fact]
public void AddAccountRejectsDuplicateAccountOnSameServer()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "pw");
Assert.Throws<LauncherProfileException>(
() => store.AddAccount("Local ACE", "testaccount", "pw2"));
}
[Fact]
public void EditCharacterUpdatesLaunchModePluginsAndLoginCommandsOnly()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "pw");
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
store.EditCharacter(
"Local ACE",
"testaccount",
"+Acdream",
launchMode: LaunchMode.Headless,
plugins: ["ExamplePlugin"],
loginCommands: ["/tell someone, hi"]);
CharacterProfile character = Assert.Single(
store.Document.Servers.Single().Accounts.Single().Characters);
Assert.Equal(LaunchMode.Headless, character.LaunchMode);
Assert.Equal(["ExamplePlugin"], character.Plugins);
Assert.Equal(["/tell someone, hi"], character.LoginCommands);
Assert.Equal("0x5000000A", character.Id);
}
[Fact]
public void FullProfileWithServersAccountsAndCharactersRoundTripsThroughDisk()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "testpassword");
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
store.EditCharacter(
"Local ACE",
"testaccount",
"+Acdream",
launchMode: LaunchMode.Gui,
plugins: ["ExamplePlugin"],
loginCommands: ["/vt start"]);
store.Save();
// Direct proof of the on-disk enum casing — a round-trip alone
// could mask a PascalCase regression if the reader ever became
// case-insensitive on enum values.
string text = File.ReadAllText(_filePath);
Assert.Contains("\"launchMode\":\"gui\"", text.Replace(" ", string.Empty));
var reloaded = new LauncherProfileStore(_filePath);
reloaded.Load();
ServerProfile server = Assert.Single(reloaded.Document.Servers);
AccountProfile account = Assert.Single(server.Accounts);
CharacterProfile character = Assert.Single(account.Characters);
Assert.Equal("+Acdream", character.Name);
Assert.Equal("0x5000000A", character.Id);
Assert.Equal(LaunchMode.Gui, character.LaunchMode);
Assert.Equal(["ExamplePlugin"], character.Plugins);
Assert.Equal(["/vt start"], character.LoginCommands);
}
[Fact]
public void LoadRejectsUnsupportedVersion()
{
File.WriteAllText(_filePath, """{"version":2,"servers":[]}""");
var store = new LauncherProfileStore(_filePath);
Assert.Throws<LauncherProfileException>(() => store.Load());
}
[Fact]
public void LoadRejectsUnmappedMembersStrictly()
{
File.WriteAllText(
_filePath,
"""{"version":1,"servers":[],"unexpectedField":true}""");
var store = new LauncherProfileStore(_filePath);
Assert.Throws<LauncherProfileException>(() => store.Load());
}
[Fact]
public void SaveWritesCamelCaseJson()
{
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.Save();
string text = File.ReadAllText(_filePath);
Assert.Contains("\"version\"", text);
Assert.Contains("\"servers\"", text);
Assert.Contains("\"host\"", text);
Assert.DoesNotContain("\"Version\"", text);
Assert.DoesNotContain("\"Servers\"", text);
}
[Fact]
public void SaveSetsOwnerOnlyPermissionsOnLinux()
{
// Linux-conditional: 0600 is a Linux-only hygiene step (spec §5,
// decisions log item "Windows profile-file permissions"). A no-op
// pass on Windows/macOS, matching the repo's established
// OperatingSystem.IsLinux() early-return pattern (e.g.
// HeadlessCredentialResolverTests.LinuxRejectsGroupOrOtherCredentialPermissions).
if (!OperatingSystem.IsLinux())
return;
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "testpassword");
store.Save();
UnixFileMode mode = File.GetUnixFileMode(_filePath);
Assert.Equal(
UnixFileMode.UserRead | UnixFileMode.UserWrite,
mode);
}
[Fact]
public void TempCredentialCreationOptionsRequestAtomicPlatformCorrectCreation()
{
FileStreamOptions options =
LauncherProfileStore.CreateCredentialTempFileOptions();
Assert.Equal(FileMode.CreateNew, options.Mode);
Assert.Equal(FileAccess.Write, options.Access);
Assert.Equal(FileShare.None, options.Share);
if (OperatingSystem.IsLinux())
{
Assert.Equal(
LauncherProfileStore.OwnerOnlyFileMode,
options.UnixCreateMode);
}
else
{
Assert.Null(options.UnixCreateMode);
}
}
[Fact]
public void TempCredentialFileIsOwnerOnlyFromItsFirstObservableLinuxState()
{
// Deterministic proof of the exact production create path: inspect
// the file while the CreateNew handle is still open, before any
// serialization or post-create chmod can occur. This replaces the
// old timing-only poller, which could miss the vulnerable window.
if (!OperatingSystem.IsLinux())
return;
string tempPath = _filePath + ".tmp";
using FileStream stream = LauncherProfileStore.CreateCredentialTempFile(tempPath);
Assert.Equal(
LauncherProfileStore.OwnerOnlyFileMode,
File.GetUnixFileMode(tempPath));
}
[Fact]
public void SaveDeletesTheStaleTempFileWhenTheFinalRenameFails()
{
// Review finding F4: force the rename step to fail (the
// destination path names an existing DIRECTORY, which
// File.Move(..., overwrite: true) refuses to replace — Windows
// reports this as UnauthorizedAccessException, Linux as
// IOException, so the assertion below accepts either) and assert
// the temp file — which still carries the just-serialized
// plaintext credentials — doesn't linger on disk afterward.
Directory.CreateDirectory(_filePath);
var store = new LauncherProfileStore(_filePath);
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "testpassword");
Assert.ThrowsAny<Exception>(() => store.Save());
Assert.False(File.Exists(_filePath + ".tmp"));
}
[Fact]
public void LoadDeletesAStaleTempFileLeftBehindByACrashedSave()
{
// Review finding F4: a Save() that crashed between creating the
// temp file and the atomic rename leaves a ".tmp" carrying the
// same plaintext credentials as the real store. Load() cleans it
// up opportunistically the next time the store is opened.
File.WriteAllText(_filePath + ".tmp", """{"version":1,"servers":[]}""");
var store = new LauncherProfileStore(_filePath);
store.Load();
Assert.False(File.Exists(_filePath + ".tmp"));
}
}

View file

@ -0,0 +1,172 @@
using AcDream.Launcher.Core.Profiles;
namespace AcDream.Launcher.Core.Tests.Profiles;
/// <summary>
/// The roster-merge matrix (Campaign LA plan §LA3 acceptance): a new
/// character, an existing character keeping its user settings, and a
/// character absent from a later roster snapshot being retained
/// (possibly pending-delete).
/// </summary>
public sealed class RosterMergeTests
{
private static LauncherProfileStore NewStoreWithServerAndAccount()
{
var store = new LauncherProfileStore(
Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".json"));
store.Load();
store.AddServer("Local ACE", "127.0.0.1", 9000);
store.AddAccount("Local ACE", "testaccount", "testpassword");
return store;
}
[Fact]
public void FirstMergeAddsNewCharactersWithDefaultLaunchModeGuiSelect()
{
LauncherProfileStore store = NewStoreWithServerAndAccount();
store.MergeRoster(
"Local ACE",
"testaccount",
[
new CharacterRosterEntry(0x5000000A, "+Acdream", 0),
new CharacterRosterEntry(0x5000000B, "+Second", 0),
]);
List<CharacterProfile> characters =
store.Document.Servers.Single().Accounts.Single().Characters;
Assert.Equal(2, characters.Count);
CharacterProfile first = characters.Single(c => c.Name == "+Acdream");
Assert.Equal("0x5000000A", first.Id);
Assert.Equal(LaunchMode.GuiSelect, first.LaunchMode);
Assert.Empty(first.Plugins);
Assert.Empty(first.LoginCommands);
CharacterProfile second = characters.Single(c => c.Name == "+Second");
Assert.Equal("0x5000000B", second.Id);
Assert.Equal(LaunchMode.GuiSelect, second.LaunchMode);
}
[Fact]
public void SecondMergePreservesUserSettingsOnAnExistingCharacter()
{
LauncherProfileStore store = NewStoreWithServerAndAccount();
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
store.EditCharacter(
"Local ACE",
"testaccount",
"+Acdream",
launchMode: LaunchMode.Headless,
plugins: ["ExamplePlugin"],
loginCommands: ["/vt start"]);
// A later probe reports the same character again (same id), with
// a renamed display — settings must survive untouched.
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
CharacterProfile character = Assert.Single(
store.Document.Servers.Single().Accounts.Single().Characters);
Assert.Equal(LaunchMode.Headless, character.LaunchMode);
Assert.Equal(["ExamplePlugin"], character.Plugins);
Assert.Equal(["/vt start"], character.LoginCommands);
}
[Fact]
public void MergeUpdatesNameWhenIdMatchesButDisplayNameChanged()
{
LauncherProfileStore store = NewStoreWithServerAndAccount();
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+OldName", 0)]);
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+NewName", 0)]);
CharacterProfile character = Assert.Single(
store.Document.Servers.Single().Accounts.Single().Characters);
Assert.Equal("+NewName", character.Name);
Assert.Equal("0x5000000A", character.Id);
}
[Fact]
public void CharacterAbsentFromALaterRosterSnapshotIsRetained()
{
LauncherProfileStore store = NewStoreWithServerAndAccount();
store.MergeRoster(
"Local ACE",
"testaccount",
[
new CharacterRosterEntry(0x5000000A, "+Acdream", 0),
new CharacterRosterEntry(0x5000000B, "+PendingDelete", 1),
]);
// A later probe's roster only reports one of the two — e.g. the
// other was deleted and is now in ACE's grace window / a
// partial snapshot. The store never removes rows on the
// caller's behalf.
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
List<CharacterProfile> characters =
store.Document.Servers.Single().Accounts.Single().Characters;
Assert.Equal(2, characters.Count);
Assert.Contains(characters, c => c.Name == "+Acdream");
Assert.Contains(characters, c => c.Name == "+PendingDelete");
}
[Fact]
public void MergeNormalizesAnUnprefixedHexIdInsteadOfCreatingADuplicateRow()
{
// Review finding F10: a hand-edited row can carry an id without
// the "0x" prefix (e.g. copy-pasted from somewhere that dropped
// it). CharacterIdFormat.TryParse now REJECTS that string
// outright (it no longer guesses hex-without-a-prefix), so the
// old raw string-equality comparison against the roster's
// canonical "0x..." form would never match and would add a
// second row forever. The name-fallback match must still
// recognize this as the SAME character and self-heal its id.
LauncherProfileStore store = NewStoreWithServerAndAccount();
store.Document.Servers.Single().Accounts.Single().Characters.Add(
new CharacterProfile { Id = "5000000A", Name = "+Acdream" });
store.MergeRoster(
"Local ACE",
"testaccount",
[new CharacterRosterEntry(0x5000000A, "+Acdream", 0)]);
CharacterProfile character = Assert.Single(
store.Document.Servers.Single().Accounts.Single().Characters);
Assert.Equal("0x5000000A", character.Id);
Assert.Equal("+Acdream", character.Name);
}
[Fact]
public void MergeThrowsForUnknownServerOrAccount()
{
LauncherProfileStore store = NewStoreWithServerAndAccount();
Assert.Throws<LauncherProfileException>(
() => store.MergeRoster(
"Nope",
"testaccount",
[new CharacterRosterEntry(1, "x", 0)]));
Assert.Throws<LauncherProfileException>(
() => store.MergeRoster(
"Local ACE",
"nope",
[new CharacterRosterEntry(1, "x", 0)]));
}
}

View file

@ -0,0 +1,210 @@
using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusEventParserTests
{
[Fact]
public void ParsesStarted()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"started","t":"2026-08-14T12:00:00Z","sessionId":"s1"}""");
var started = Assert.IsType<StartedStatusEvent>(e);
Assert.Equal(1, started.V);
Assert.Equal("started", started.E);
Assert.Equal("s1", started.SessionId);
Assert.Equal(
DateTimeOffset.Parse("2026-08-14T12:00:00Z"),
started.T);
}
[Fact]
public void ParsesConnected()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"connected","t":"2026-08-14T12:00:01Z","sessionId":"s1"}""");
Assert.IsType<ConnectedStatusEvent>(e);
}
[Fact]
public void ParsesCharacterListWithMultipleCharacters()
{
var e = StatusEventParser.Parse(
"""
{"v":1,"e":"characterList","t":"2026-08-14T12:00:02Z","sessionId":"s1",
"accountName":"testaccount","slotCount":6,
"characters":[
{"id":1342177290,"name":"+Acdream","secondsGreyedOut":0},
{"id":1342177291,"name":"+Second","secondsGreyedOut":1}
]}
""");
var list = Assert.IsType<CharacterListStatusEvent>(e);
Assert.Equal("testaccount", list.AccountName);
Assert.Equal(6, list.SlotCount);
Assert.Equal(2, list.Characters.Count);
Assert.Equal(1342177290u, list.Characters[0].Id);
Assert.Equal("+Acdream", list.Characters[0].Name);
Assert.Equal(0u, list.Characters[0].SecondsGreyedOut);
Assert.Equal(1342177291u, list.Characters[1].Id);
Assert.Equal(1u, list.Characters[1].SecondsGreyedOut);
}
[Fact]
public void ParsesEnteredWorld()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"enteredWorld","t":"2026-08-14T12:00:03Z","sessionId":"s1","characterId":1342177290,"characterName":"+Acdream"}""");
var entered = Assert.IsType<EnteredWorldStatusEvent>(e);
Assert.Equal(1342177290u, entered.CharacterId);
Assert.Equal("+Acdream", entered.CharacterName);
}
[Fact]
public void ParsesPluginLoadedAndPluginFailed()
{
var loaded = Assert.IsType<PluginLoadedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"pluginLoaded","t":"2026-08-14T12:00:04Z","sessionId":"s1","plugin":"ExamplePlugin"}"""));
Assert.Equal("ExamplePlugin", loaded.Plugin);
var failed = Assert.IsType<PluginFailedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"pluginFailed","t":"2026-08-14T12:00:05Z","sessionId":"s1","plugin":"BadPlugin","error":"boom"}"""));
Assert.Equal("BadPlugin", failed.Plugin);
Assert.Equal("boom", failed.Error);
}
[Fact]
public void ParsesDisconnectedAndExited()
{
var disconnected = Assert.IsType<DisconnectedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"disconnected","t":"2026-08-14T12:00:06Z","sessionId":"s1","reason":"serverClosed"}"""));
Assert.Equal("serverClosed", disconnected.Reason);
var exited = Assert.IsType<ExitedStatusEvent>(
StatusEventParser.Parse(
"""{"v":1,"e":"exited","t":"2026-08-14T12:00:07Z","sessionId":"s1","code":0,"reason":"graceful"}"""));
Assert.Equal(0, exited.Code);
Assert.Equal("graceful", exited.Reason);
}
[Fact]
public void UnknownEValueSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse(
"""{"v":1,"e":"someFutureEvent","t":"2026-08-14T12:00:08Z","sessionId":"s1","extra":true}""");
var unknown = Assert.IsType<UnknownStatusEvent>(e);
Assert.Equal("someFutureEvent", unknown.E);
Assert.Equal("s1", unknown.SessionId);
Assert.Contains("someFutureEvent", unknown.RawJson);
}
[Fact]
public void MalformedJsonSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse("{not json");
Assert.IsType<UnknownStatusEvent>(e);
}
[Theory]
[InlineData("[]")]
[InlineData("null")]
[InlineData("42")]
[InlineData("\"text\"")]
public void CompleteJsonWithANonObjectRootSurfacesAsMalformedEvent(string line)
{
var e = StatusEventParser.Parse(line);
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.Contains("root", malformed.Error, StringComparison.OrdinalIgnoreCase);
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData("\t")]
public void WhitespaceOrEmptyLineSurfacesAsUnknownEventRatherThanThrowing(string line)
{
// Review finding F7: ArgumentException.ThrowIfNullOrWhiteSpace
// used to guard this method BEFORE the try/catch, so a
// whitespace-only line (e.g. a stray blank line the tailer
// happens to hand over) escaped as an uncaught exception instead
// of degrading like every other malformed-input case.
var e = StatusEventParser.Parse(line);
Assert.IsType<UnknownStatusEvent>(e);
}
[Fact]
public void NullLineSurfacesAsUnknownEventRatherThanThrowing()
{
var e = StatusEventParser.Parse(null!);
Assert.IsType<UnknownStatusEvent>(e);
}
[Theory]
[InlineData("{\"e\":\"started\",\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":\"1\",\"e\":\"connected\",\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":2,\"e\":\"started\",\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":\"connected\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":\"started\",\"t\":42,\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":\"connected\",\"t\":\"not-a-time\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":\"started\",\"t\":\"2026-08-14T12:00:00+02:00\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":\"connected\",\"t\":\"2026-08-14T12:00:00Z\"}")]
[InlineData("{\"v\":1,\"e\":\"started\",\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":42}")]
[InlineData("{\"v\":1,\"e\":\"connected\",\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"\"}")]
public void PayloadFreeKnownEventsRequireTheFullPinnedV1Envelope(string line)
{
var e = StatusEventParser.Parse(line);
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.False(string.IsNullOrWhiteSpace(malformed.Error));
}
[Theory]
[InlineData("{\"v\":1,\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"s1\"}")]
[InlineData("{\"v\":1,\"e\":42,\"t\":\"2026-08-14T12:00:00Z\",\"sessionId\":\"s1\"}")]
public void MissingOrWrongKindEventNameSurfacesAsMalformedEvent(string line)
{
Assert.IsType<MalformedStatusEvent>(StatusEventParser.Parse(line));
}
[Fact]
public void KnownEValueWithMissingRequiredFieldSurfacesAsMalformedEventRatherThanThrowing()
{
// characterList without "characters" — a shape mismatch on a
// KNOWN event name. Review finding F12: this must be
// distinguishable from an unrecognized e value, so it now
// surfaces as MalformedStatusEvent rather than UnknownStatusEvent.
var e = StatusEventParser.Parse(
"""{"v":1,"e":"characterList","t":"2026-08-14T12:00:09Z","sessionId":"s1","accountName":"a","slotCount":6}""");
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.Equal("characterList", malformed.E);
Assert.Equal("s1", malformed.SessionId);
Assert.False(string.IsNullOrWhiteSpace(malformed.Error));
}
[Fact]
public void KnownEValueWithAFieldOfTheWrongJsonKindSurfacesAsMalformedEvent()
{
// "characters" present but not an array — this throws
// InvalidOperationException out of JsonElement.EnumerateArray()
// rather than the FormatException a missing/wrong-kind scalar
// field throws, so it exercises the parser's other malformed-
// payload catch path.
var e = StatusEventParser.Parse(
"""{"v":1,"e":"characterList","t":"2026-08-14T12:00:10Z","sessionId":"s1","accountName":"a","slotCount":6,"characters":"not-an-array"}""");
var malformed = Assert.IsType<MalformedStatusEvent>(e);
Assert.Equal("characterList", malformed.E);
Assert.False(string.IsNullOrWhiteSpace(malformed.Error));
}
}

View file

@ -0,0 +1,214 @@
using System.Text;
using AcDream.Launcher.Core.Status;
namespace AcDream.Launcher.Core.Tests.Status;
public sealed class StatusFileTailerTests : IDisposable
{
private readonly string _root;
private readonly string _path;
public StatusFileTailerTests()
{
_root = Path.Combine(
Path.GetTempPath(),
"acdream-launcher-tailer-tests",
Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
_path = Path.Combine(_root, "status.jsonl");
}
public void Dispose()
{
if (Directory.Exists(_root))
{
Directory.Delete(_root, recursive: true);
}
}
[Fact]
public void ReturnsNoEventsWhenTheFileDoesNotExistYet()
{
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReturnsNoEventsWhenNothingHasBeenAppendedSinceTheLastPoll()
{
AppendShared(Line("started", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Single(tailer.ReadNewEvents());
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void ReadsMultipleCompleteLinesInOnePoll()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
Assert.IsType<StartedStatusEvent>(events[0]);
Assert.IsType<ConnectedStatusEvent>(events[1]);
}
[Fact]
public void ContinuesPastCompleteNonObjectJsonValuesToTheFollowingValidLine()
{
AppendShared(
"[]\nnull\n42\n\"text\"\n"
+ Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(5, events.Count);
Assert.All(events.Take(4), e => Assert.IsType<MalformedStatusEvent>(e));
Assert.IsType<ConnectedStatusEvent>(events[4]);
}
[Fact]
public void TolerateAPartialLastLineAndCompletesItOnALaterPoll()
{
string full = Line("started", "s1");
int splitAt = full.Length - 10; // cut mid-object, before the closing brace/newline
AppendShared(full[..splitAt]);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Empty(firstPoll);
AppendShared(full[splitAt..]);
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(secondPoll);
Assert.IsType<StartedStatusEvent>(onlyEvent);
}
[Fact]
public void APartialLineFollowedByAFullLineOnlyEmitsTheCompleteOne()
{
AppendShared(Line("started", "s1"));
string partial = """{"v":1,"e":"connected","t":"2026-08-14T12:00:00Z","sessionId":"s1"""; // no closing
AppendShared(partial);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.IsType<StartedStatusEvent>(onlyEvent);
// Completing the second line on a later poll produces exactly
// one more event, proving the partial bytes were retained (not
// dropped and not double-counted).
AppendShared("\"}\n");
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
StatusEvent completed = Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(completed);
}
[Fact]
public void SkipsBlankLines()
{
AppendShared("\n" + Line("started", "s1") + "\n" + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Equal(2, events.Count);
}
[Fact]
public void ReadsWithAWriterHoldingTheFileOpenForAppend()
{
// Share-tolerant reads: the writer's handle stays open the whole
// time (FileShare.ReadWrite on both sides), matching a live host
// process appending status.jsonl while the launcher tails it.
using var writer = new FileStream(
_path,
FileMode.Create,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
var tailer = new StatusFileTailer(_path);
byte[] first = Encoding.UTF8.GetBytes(Line("started", "s1"));
writer.Write(first, 0, first.Length);
writer.Flush();
IReadOnlyList<StatusEvent> firstPoll = tailer.ReadNewEvents();
Assert.Single(firstPoll);
byte[] second = Encoding.UTF8.GetBytes(Line("connected", "s1"));
writer.Write(second, 0, second.Length);
writer.Flush();
IReadOnlyList<StatusEvent> secondPoll = tailer.ReadNewEvents();
Assert.Single(secondPoll);
Assert.IsType<ConnectedStatusEvent>(secondPoll[0]);
}
[Fact]
public void ReadNewEventsReturnsEmptyRatherThanThrowingOnASharingViolation()
{
// A deterministic proxy for the File.Exists -> new FileStream
// TOCTOU window (review finding F7): Windows enforces FileShare
// at the OS level, so holding an exclusive (FileShare.None)
// handle open while the tailer tries to open the same path
// reliably reproduces the IOException the tailer must now
// swallow instead of throwing out of a method documented never
// to throw. (.NET's FileStream doesn't apply mandatory locking
// on Linux by default, so this specific scenario isn't
// reproducible there — the fix itself is platform-agnostic, only
// this particular deterministic trigger is Windows-only.)
if (!OperatingSystem.IsWindows())
return;
AppendShared(Line("started", "s1"));
using var exclusiveHandle = new FileStream(
_path, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
var tailer = new StatusFileTailer(_path);
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
Assert.Empty(events);
}
[Fact]
public void RestartsFromTheTopWhenTheFileIsTruncatedOrReplaced()
{
AppendShared(Line("started", "s1") + Line("connected", "s1"));
var tailer = new StatusFileTailer(_path);
Assert.Equal(2, tailer.ReadNewEvents().Count);
File.Delete(_path);
AppendShared(Line("started", "s2"));
IReadOnlyList<StatusEvent> events = tailer.ReadNewEvents();
StatusEvent onlyEvent = Assert.Single(events);
Assert.Equal("s2", onlyEvent.SessionId);
}
private static string Line(string e, string sessionId) =>
$$"""{"v":1,"e":"{{e}}","t":"2026-08-14T12:00:00Z","sessionId":"{{sessionId}}"}""" + "\n";
private void AppendShared(string text)
{
using var stream = new FileStream(
_path,
FileMode.Append,
FileAccess.Write,
FileShare.ReadWrite | FileShare.Delete);
byte[] bytes = Encoding.UTF8.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
}
}