diff --git a/CHANGELOG.md b/CHANGELOG.md index f505bf09..c2190fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -347,6 +347,38 @@ GitHub release body, so a missing section means an empty release note. file, so the L2 telemetry layer is GPL-3.0 compatible. Checked against the pinned 0.9.6 package, not just the repository. +### Added +- **The Agent now seeds the rules file the guard reads** (`20_OPEN_QUESTIONS` + §S20, seed half). `rules/detection-rules.json` ships in the Agent's output and + is installed to the product location on startup. Before this, nothing in the + repository ever wrote that file, so on any machine that had not hand-installed + one the guard answered `RulesUnreadable` for every title — which is what the + first real injection hit. Measured end to end: remove the file and the guard + says `RulesUnreadable`; run the Agent and the guard reads its rules and reaches + check 1. + - **Provenance, not `rulesVersion`.** The first design replaced the installed + file when the packaged seed was strictly newer. Measured against this + repository's own history, every commit that changed the `anticheat` block + left `rulesVersion` untouched and the one commit that bumped it changed the + block not at all — the rule would have delivered **none** of the changes it + existed for. The seeder records a hash of what it installed instead. + - **`FlGuardCheckRules`** — a new observation-only ABI export, because + `DetectionRulesFile` never reads the `anticheat` block (§S15). Validating with + the managed reader would have checked everything except the half the hard gate + consumes, and could have installed a document the guard then refuses for every + title while reporting success. + - **A usable file we did not write is left alone**, which is safe only because + the floor is now generated from the shipped blocklist: a rules file can add + and cannot remove. An unusable one is replaced whoever wrote it — there is + nothing to clobber, and nothing else in the product repairs it. + - `ReplaceFileW` with a backup, a random temp name in the destination directory + opened `FileShare.None`, flush-to-disk before the swap, and a reparse-point + check on the directory chain. + - **§S20 does not close.** The HTTPS feed does not exist, so FR-7.3's + independent anti-cheat schedule is unmet; the guard still reads no version, so + binary and data have no handshake; and this is what makes the Vulkan layer's + §S2 self-scan reachable for the first time. All four recorded in the entry. + ### Fixed - **The compiled-in blocklist floor shipped too narrow, and it is now generated from the rules file** (§S21). As first written the floor carried exactly the diff --git a/FrameLedger.Rules.targets b/FrameLedger.Rules.targets new file mode 100644 index 00000000..85625319 --- /dev/null +++ b/FrameLedger.Rules.targets @@ -0,0 +1,48 @@ + + + + + $(MSBuildThisFileDirectory)rules\detection-rules.json + + + + + rules\detection-rules.json + PreserveNewest + + + + + + + + + diff --git a/docs/13_CI_CD.md b/docs/13_CI_CD.md index bcba7793..9359ac59 100644 --- a/docs/13_CI_CD.md +++ b/docs/13_CI_CD.md @@ -24,7 +24,21 @@ FrameLedger uses the **`poli0981/.github` ops repo** where its templates fit, an - `permissions: contents: write`. ### `rules-publish.yml` — on change to `rules/detection-rules.json` in `main` -- Runs `tools/rules-validate` → bumps `rulesVersion` check → the raw file on `main` **is** the distribution endpoint (05_DETECTION), so this workflow only gates correctness. +- Runs `tools/rules-validate` and fails on anti-cheat removals. The raw file on `main` **is** the distribution endpoint (05_DETECTION), so this workflow only gates correctness. + + > **There is no `rulesVersion` bump check, and this line used to claim one.** + > `rules-validate.ps1` checks the field's *format* and nothing compares it + > against the merge base, so a blocklist edit ships with the version untouched — + > measured on this repository's own history, that is what every commit that + > changed the `anticheat` block actually did, while the one commit that bumped + > `rulesVersion` changed the block not at all. + > + > Recorded rather than built, because nothing depends on the ordering: §S20's + > seeder deliberately uses **provenance** (a hash of what it installed) rather + > than version comparison, precisely because that history falsifies the + > comparison. A monotonicity gate is still worth having before anything else + > starts trusting the field — an unbuilt gate described as existing is the + > defect this note replaces. > **The validator does not evaluate rules**, and this line used to say it ran > "against fixtures". It checks the schema, the imperative constraints, the diff --git a/docs/20_OPEN_QUESTIONS.md b/docs/20_OPEN_QUESTIONS.md index daf3b3ca..601a5268 100644 --- a/docs/20_OPEN_QUESTIONS.md +++ b/docs/20_OPEN_QUESTIONS.md @@ -823,26 +823,79 @@ is worth extending; the claim that the doc is wrong is not. > complained about — a doc citation (`19_SAFETY:264`) pointing at text that is not > there. Line 264 is a blocklist table row. -### S20 · Nothing in the repo installs the rules file the guard reads +### S20 ◐ · Delivering the rules file — **seed half done, feed half open** -`RulesFilePath`/`ReadRulesFile` read only -`%LOCALAPPDATA%\FrameLedger\rules\detection-rules.json`, and -`DetectionRulesFile.cs` reads the same path. **No code in this repository seeds, -copies or downloads that file**, and no rules-update client exists. The -repository's `rules/detection-rules.json` is therefore a file no shipped -component currently reads. +The guard reads its blocklist from one place under Local AppData, and until +2026-08-04 nothing in this repository ever wrote a file there. On any machine that +had not hand-installed one the guard answered `RulesUnreadable` for every title — +correct fail-closed behaviour, and also the whole story: the first real +injection's opening refusal was exactly this. -Two consequences worth stating before someone edits the seed expecting an effect: +> **The entry's own opening sentence was not quite true**, and the exception +> matters for anyone reading it as a survey. `fl-probe-vklayer` DOES seed the +> file — install-only-if-absent, path resolved through `fl::guard::RulesFilePath` +> — and then deletes what it installed. So the repository had a writer; it had no +> *product* writer, and a ctest that removes its own work leaves the machine +> exactly as it found it. -- A rules edit changes nothing on any machine until a delivery path exists. This - is why the first real injection's opening refusal was `RulesUnreadable` — - correct behaviour, and also the whole story. -- **The guard never reads `rulesVersion` or `schemaVersion`.** `ParseRules` walks - only the `anticheat` subtree. So the binary half of any fix and the data half - have **no handshake**: a machine can hold a new `FrameLedger.Guard.dll` and a - year-old rules file forever with nothing detecting it. `13_CI_CD` says the raw - file on `main` *is* the distribution endpoint, so the two halves ship on - independent clocks. +**✅ The seed half is built.** `rules/detection-rules.json` now ships in the +Agent's output (`FrameLedger.Rules.targets`), and `RulesSeeder` installs it to the +product location. The Agent is the sole writer, per §S18's ratification, and it is +a real caller rather than a component nothing invokes: `Program.cs` runs it and +reports the outcome. + +Measured end to end on this machine — remove the file, the guard answers +`RulesUnreadable`; run the Agent; the guard reads its rules and reaches check 1. + +Four decisions worth keeping, each of which replaced something the design review +disproved: + +- **Provenance, not `rulesVersion`.** The first design replaced the installed file + when the packaged seed was strictly newer. Measured against this repository's + own history, every commit that changed the `anticheat` block left `rulesVersion` + untouched and the one commit that bumped it changed the block not at all — so + the rule would have delivered **none** of the changes it existed for. The seeder + records a hash of what it installed instead. +- **`ReplaceFileW`, not `MoveFileEx`.** See §S21: the prescribed primitive returns + `ERROR_ACCESS_DENIED` against a live reader. `ReplaceFileW`'s backup parameter + also makes `05_DETECTION`'s "the last valid copy is kept" a mechanism rather + than a sentence. +- **Validated by the guard's own parser.** `FlGuardCheckRules` is a new + observation-only export, because `DetectionRulesFile` never reads the + `anticheat` block (§S15) — validating with it would have checked everything + except the half the hard gate consumes, and could have installed a document the + guard then refuses for every title while reporting success. +- **A usable file we did not write is left alone.** Safe only because §S21's floor + is now generated from the shipped blocklist: a rules file can ADD and cannot + remove. Under the narrow floor the same rule would have handed permanent control + of the blocklist to whoever created the file first. + +#### What is still open, and it is not small + +- **The feed half.** `05_DETECTION` §Trust and staleness specifies an HTTPS fetch + with validate-then-replace; none of it exists. So **FR-7.3 is unmet**: anti-cheat + entries cannot reach a machine on their own schedule, only with a release. A + rules edit still changes nothing on any installed machine until the next build. +- **No binary/data handshake inside the guard.** `ParseRules` still walks only the + `anticheat` subtree and never reads `schemaVersion` or `rulesVersion`. Teaching + it to refuse an unknown version would be a second machine-wide refusal lever + pulled by data, and `rules-publish.yml` gates neither field — see `13_CI_CD`, + which used to claim a bump check that does not exist. +- **`trustedSigners` is the one allow-widening field a foreign file still + controls.** Deliberately not floored, because flooring an allowlist has the + wrong polarity. Inert today — `IsTrustedSigner` has no production call site + while §S19(b) is deferred — and **live the moment the signer half is wired**, + which makes gating it a prerequisite of §S19(b) rather than of this item. +- **This is what arms the Vulkan layer's self-scan for the first time.** `layer.cpp` + §S2's second half could only ever answer "inert" while the file never existed. + It is now reachable, on a machine where the file is present. The layer still + intercepts nothing (`vkQueuePresentKHR` is P1), so nothing observable changes + yet — recorded here so it is not discovered as a surprise when the present hook + lands. +- **A seed replacement is a rules update in FR-2.3's sense**, and the obligation + attached to that event — re-run the pre-scan, force-disable a game that has + started matching — is unimplemented. There is no `games` table yet, so there is + nothing to write; named here so whoever builds persistence has an anchor. ### S21 ✅ · The hard gate's data source was caller-nameable, and its completeness floor never read the values — **closed** diff --git a/src/FrameLedger.Agent/FrameLedger.Agent.csproj b/src/FrameLedger.Agent/FrameLedger.Agent.csproj index 831a7a10..e8f7de1a 100644 --- a/src/FrameLedger.Agent/FrameLedger.Agent.csproj +++ b/src/FrameLedger.Agent/FrameLedger.Agent.csproj @@ -36,4 +36,7 @@ --> + + + diff --git a/src/FrameLedger.Agent/Program.cs b/src/FrameLedger.Agent/Program.cs index c49d8fcd..9ddee7d3 100644 --- a/src/FrameLedger.Agent/Program.cs +++ b/src/FrameLedger.Agent/Program.cs @@ -1,6 +1,6 @@ // FrameLedger.Agent — capture orchestrator. // -// Scaffold only. The real entry point builds a Generic Host containing the +// Still a scaffold. The real entry point builds a Generic Host containing the // process watcher, the anti-cheat guard, the injector control, the shm drain, // the telemetry poller and the session recorder (docs/04_CAPTURE.md). // @@ -12,14 +12,50 @@ // CLI flags this must eventually accept (docs/12_BUILD.md §Debugging): // --serve --console --diag --install-task --uninstall-task // --register-vklayer --unregister-vklayer +// +// It has ONE real behaviour today: seeding the rules file (§S20). The Agent is +// the sole owner of %LOCALAPPDATA%\FrameLedger (§S18 blocker 3, ratified) and +// therefore the only thing that may write there. + +using FrameLedger.Application.Rules; +using FrameLedger.Infrastructure.Rules; namespace FrameLedger.Agent; internal static class Program { - private static int Main(string[] args) + private static async Task Main(string[] args) { ArgumentNullException.ThrowIfNull(args); - return 0; + + // Before anything else. The guard reads this file on every evaluation and + // refuses every title when it is absent, so a capture started before the + // seed lands would fail for a reason that has nothing to do with the game. + RulesSeedOutcome seeded = await new RulesSeeder(new FileSystemRulesStore()) + .EnsureSeededAsync() + .ConfigureAwait(false); + + // Console, not a logger, because there is no host to configure one in yet. + // The alternative is a branch whose result goes nowhere, and an outcome + // nobody can observe is the shape §S20 exists to complain about. + Console.WriteLine($"rules: {Describe(seeded)}"); + + return seeded is RulesSeedOutcome.WriteFailed or RulesSeedOutcome.PackagedSeedUnusable ? 1 : 0; } + + private static string Describe(RulesSeedOutcome outcome) => outcome switch + { + RulesSeedOutcome.Installed => "installed the packaged blocklist", + RulesSeedOutcome.Updated => "updated the blocklist this build ships", + RulesSeedOutcome.AlreadyCurrent => "already current", + RulesSeedOutcome.ForeignLeftAlone => + "a usable rules file is installed that we did not write — left alone (it can only ADD to the blocklist)", + RulesSeedOutcome.ReplacedUnusable => + "the installed rules file was not usable by the guard and has been replaced", + RulesSeedOutcome.RaceLost => "another process installed it first", + RulesSeedOutcome.PackagedSeedUnusable => + "FAILED — the seed shipped in this build is not usable by the guard; nothing was installed", + RulesSeedOutcome.WriteFailed => "FAILED — could not write the rules file", + _ => outcome.ToString(), + }; } diff --git a/src/FrameLedger.Application/Rules/IRulesStore.cs b/src/FrameLedger.Application/Rules/IRulesStore.cs new file mode 100644 index 00000000..a4c5c465 --- /dev/null +++ b/src/FrameLedger.Application/Rules/IRulesStore.cs @@ -0,0 +1,59 @@ +namespace FrameLedger.Application.Rules; + +/// +/// Everything needs to know about the rules file, and +/// nothing else. +/// +/// +/// +/// No method takes a path. The rules source is not selectable — +/// §S3 removed the pipe's ability to name it and §S21 removed the environment's — +/// and a port with a path parameter is how it would become selectable again. The +/// adapter knows the one location; the policy above it does not. +/// +/// +/// Validation is not this layer's job either. +/// asks the native guard's own parser, because +/// the managed detection reader structurally cannot see the anticheat +/// block (§S15 — there is no second matcher, and there never will be). A seeder +/// that validated with the managed reader would check everything except the half +/// the hard gate consumes. +/// +/// +public interface IRulesStore +{ + /// The rules file the guard reads, if one is there. + /// null when absent. Throws only on genuinely unexpected IO. + ValueTask ReadInstalledAsync(CancellationToken ct = default); + + /// The seed shipped in this build. + ValueTask ReadPackagedSeedAsync(CancellationToken ct = default); + + /// + /// The content hash this store last recorded as its own work, or null + /// if it has never installed anything here. + /// + /// + /// Provenance rather than version. §S20's first design compared + /// rulesVersion — measured against this repository's own history, every + /// commit that changed the blocklist left that field untouched and the one + /// commit that bumped it changed the blocklist not at all, so the comparison + /// would have delivered none of the changes that mattered. + /// + ValueTask ReadInstalledMarkerAsync(CancellationToken ct = default); + + /// Would the native guard accept this document? + bool IsUsableByTheGuard(byte[] candidate); + + /// + /// Write to the rules location, atomically, keeping + /// a backup of whatever was there, and record the hash as ours. + /// + /// The bytes to install. + /// + /// false refuses if a file appeared after we looked — losing that race + /// means somebody else installed one, which is not an error. + /// + /// Cancellation. + ValueTask WriteAsync(byte[] content, bool replaceExisting, CancellationToken ct = default); +} diff --git a/src/FrameLedger.Application/Rules/RulesSeedOutcome.cs b/src/FrameLedger.Application/Rules/RulesSeedOutcome.cs new file mode 100644 index 00000000..f288c6b0 --- /dev/null +++ b/src/FrameLedger.Application/Rules/RulesSeedOutcome.cs @@ -0,0 +1,65 @@ +namespace FrameLedger.Application.Rules; + +/// What did, and why. +/// +/// Every value is reportable. §S20's failure mode is silence: a seeder that wrote +/// nothing and said nothing leaves the guard answering RulesUnreadable for +/// every title with no trace of why. +/// +public enum RulesSeedOutcome +{ + /// Nothing was there; the packaged seed was installed. + Installed = 0, + + /// + /// The installed file was one we had installed, and this build ships a + /// different one. Replaced. + /// + Updated, + + /// The installed file is already exactly the packaged seed. + AlreadyCurrent, + + /// + /// A usable file is there that we did not install. Left alone. + /// + /// + /// It cannot weaken the gate: since the floor is generated from the shipped + /// blocklist, a rules file can only ADD (`19_SAFETY` §The floor data cannot + /// remove). So the safe act is to leave it and say so, rather than destroy + /// something a user or a support process put there. + /// + ForeignLeftAlone, + + /// + /// The installed file is not usable by the guard, so it was replaced. + /// + /// + /// There is nothing to clobber: the guard already refuses every title on that + /// file. Leaving it would make a corrupt or truncated file a permanent, + /// unrepairable machine-wide refusal, because nothing else in the product + /// repairs it. + /// + ReplacedUnusable, + + /// + /// Somebody else won the race to create the file between our look and our + /// write. Not an error. + /// + RaceLost, + + /// + /// The seed shipped in this build is not usable by the guard. Nothing was + /// installed. + /// + /// + /// Should be unreachable: rules-validate.ps1 and ctest + /// fl_rules_budget both gate the packaged seed, and the latter asserts + /// that exact file parses in the guard. Checked anyway, because "our own + /// artifact is fine" is the assumption this project keeps finding to be false. + /// + PackagedSeedUnusable, + + /// The rules location could not be written. Reported, not swallowed. + WriteFailed, +} diff --git a/src/FrameLedger.Application/Rules/RulesSeeder.cs b/src/FrameLedger.Application/Rules/RulesSeeder.cs new file mode 100644 index 00000000..e52944e2 --- /dev/null +++ b/src/FrameLedger.Application/Rules/RulesSeeder.cs @@ -0,0 +1,112 @@ +using System.Security.Cryptography; + +namespace FrameLedger.Application.Rules; + +/// +/// Puts a usable rules file where the guard reads one (20_OPEN_QUESTIONS §S20). +/// +/// +/// +/// Before this existed, nothing in the repository ever wrote that file, so on any +/// machine that had not hand-installed one the guard answered +/// RulesUnreadable for every title. That is correct fail-closed behaviour +/// and also the whole story: the first real injection's opening refusal was +/// exactly this. +/// +/// +/// What makes the decisions below safe is the floor, not this class. +/// Since the compiled-in blocklist is generated from the shipped seed, a rules +/// file can only ADD to what the guard blocks — it cannot remove a family, a +/// value or a name fragment (19_SAFETY §The floor data cannot remove). So +/// "leave a file we did not install alone" is not an override; at worst it is a +/// stale extension set. Under the narrow floor this class shipped against +/// originally, the same rule would have handed permanent control of the blocklist +/// to whoever created the file first. +/// +/// +/// Residual, stated rather than discovered: the one +/// allow-widening field a foreign file still controls is +/// anticheat.heuristic.trustedSigners, which is deliberately not floored +/// because flooring an allowlist has the wrong polarity. It is inert today — +/// IsTrustedSigner has no production call site while §S19(b) is deferred — +/// and it becomes live the moment the signer half is wired. That is a +/// prerequisite of §S19(b), recorded here because this is the class that made a +/// foreign file reachable. +/// +/// +/// This is the seed half only. There is no fetch client and no +/// network call; 05_DETECTION §Trust and staleness describes an HTTPS feed +/// that remains unbuilt, so FR-7.3's independent anti-cheat update schedule is +/// still unmet. +/// +/// +public sealed class RulesSeeder(IRulesStore store) +{ + private readonly IRulesStore _store = store ?? throw new ArgumentNullException(nameof(store)); + + /// Ensure a usable rules file exists, and keep our own copy current. + public async ValueTask EnsureSeededAsync(CancellationToken ct = default) + { + byte[] packaged = await _store.ReadPackagedSeedAsync(ct).ConfigureAwait(false); + + // Our own artifact is checked first, and the check is not ceremonial: it + // is the difference between "install nothing and say why" and "install a + // document the guard then refuses for every title on the machine". + if (!_store.IsUsableByTheGuard(packaged)) + { + return RulesSeedOutcome.PackagedSeedUnusable; + } + + byte[]? installed = await _store.ReadInstalledAsync(ct).ConfigureAwait(false); + + if (installed is null) + { + RulesWriteOutcome wrote = await _store.WriteAsync(packaged, replaceExisting: false, ct) + .ConfigureAwait(false); + return wrote switch + { + RulesWriteOutcome.Written => RulesSeedOutcome.Installed, + RulesWriteOutcome.AlreadyExists => RulesSeedOutcome.RaceLost, + _ => RulesSeedOutcome.WriteFailed, + }; + } + + string installedHash = Sha256(installed); + if (string.Equals(installedHash, Sha256(packaged), StringComparison.Ordinal)) + { + return RulesSeedOutcome.AlreadyCurrent; + } + + // Not usable ⇒ replace, whoever wrote it. There is no information to + // clobber: the guard already refuses every title on this file, and + // nothing else in the product repairs it, so leaving it would make a + // truncated or corrupt file a permanent machine-wide refusal. + if (!_store.IsUsableByTheGuard(installed)) + { + return await ReplaceAsync(packaged, RulesSeedOutcome.ReplacedUnusable, ct).ConfigureAwait(false); + } + + // Usable and ours ⇒ this build ships a different seed, so update it. This + // is the drift §S20 records — a new binary and a year-old blocklist + // coexisting forever — closed by provenance rather than by comparing + // `rulesVersion`, which this repository's own history shows nobody bumps + // when the blocklist changes. + string? marker = await _store.ReadInstalledMarkerAsync(ct).ConfigureAwait(false); + if (marker is not null && string.Equals(marker, installedHash, StringComparison.OrdinalIgnoreCase)) + { + return await ReplaceAsync(packaged, RulesSeedOutcome.Updated, ct).ConfigureAwait(false); + } + + // Usable and not ours. Left alone deliberately — see the remarks above. + return RulesSeedOutcome.ForeignLeftAlone; + } + + private async ValueTask ReplaceAsync(byte[] packaged, RulesSeedOutcome onSuccess, + CancellationToken ct) + { + RulesWriteOutcome wrote = await _store.WriteAsync(packaged, replaceExisting: true, ct).ConfigureAwait(false); + return wrote == RulesWriteOutcome.Written ? onSuccess : RulesSeedOutcome.WriteFailed; + } + + private static string Sha256(byte[] bytes) => Convert.ToHexString(SHA256.HashData(bytes)); +} diff --git a/src/FrameLedger.Application/Rules/RulesWriteOutcome.cs b/src/FrameLedger.Application/Rules/RulesWriteOutcome.cs new file mode 100644 index 00000000..2ba6dae3 --- /dev/null +++ b/src/FrameLedger.Application/Rules/RulesWriteOutcome.cs @@ -0,0 +1,17 @@ +namespace FrameLedger.Application.Rules; + +/// What the store's write attempt did. +public enum RulesWriteOutcome +{ + /// The file is now the content we asked for. + Written = 0, + + /// + /// A file appeared between the look and the write, and we were told not to + /// replace it. Not an error — somebody else seeded it. + /// + AlreadyExists, + + /// Could not write. The caller reports it rather than retrying blindly. + Failed, +} diff --git a/src/FrameLedger.Infrastructure/AntiCheat/NativeAntiCheatGuard.cs b/src/FrameLedger.Infrastructure/AntiCheat/NativeAntiCheatGuard.cs index 486493f7..18f53592 100644 --- a/src/FrameLedger.Infrastructure/AntiCheat/NativeAntiCheatGuard.cs +++ b/src/FrameLedger.Infrastructure/AntiCheat/NativeAntiCheatGuard.cs @@ -80,6 +80,10 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard [DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)] private static extern int FlGuardRulesFilePath([Out] char[] buffer, int cap); + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport(_guardDll, CallingConvention = CallingConvention.Cdecl)] + private static extern int FlGuardCheckRules(byte[] json, int length); + static NativeAntiCheatGuard() { NativeLibrary.SetDllImportResolver(typeof(NativeAntiCheatGuard).Assembly, Resolve); @@ -154,6 +158,28 @@ public sealed class NativeAntiCheatGuard : IAntiCheatGuard /// the shape §S21 was — a seeder that writes where the gate does not read /// reports success and leaves the guard refusing every title. /// + /// + /// Would the native guard accept this rules document? Returns + /// fl::guard::ParseResult; 0 is kOk. + /// + /// + /// §S20's seeder needs this because nothing managed can answer it: + /// DetectionRulesFile reads engines/platforms/capabilities and, by + /// explicit design, never the anticheat block (§S15 — no second + /// matcher). Validating a candidate with the managed reader would check + /// everything except the half the hard gate consumes. + /// + /// Observation only: buffer in, enum out, no path parameter, nothing + /// installed. It calls the same ParseRules the gate parses with, so + /// the thing that validates and the thing that parses are one. + /// + /// + public static int NativeCheckRules(byte[] json) + { + ArgumentNullException.ThrowIfNull(json); + return FlGuardCheckRules(json, json.Length); + } + public static string NativeRulesFilePath() { // 1024 mirrors fl::guard::kMaxRulesPathLen. A short buffer would come diff --git a/src/FrameLedger.Infrastructure/Rules/FileSystemRulesStore.cs b/src/FrameLedger.Infrastructure/Rules/FileSystemRulesStore.cs new file mode 100644 index 00000000..d1435e1c --- /dev/null +++ b/src/FrameLedger.Infrastructure/Rules/FileSystemRulesStore.cs @@ -0,0 +1,243 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using FrameLedger.Application.Rules; +using FrameLedger.Infrastructure.AntiCheat; + +namespace FrameLedger.Infrastructure.Rules; + +/// +/// The real filesystem behind (§S20). +/// +/// +/// Three mechanisms here were each chosen against an obvious wrong answer, and +/// the wrong answers are recorded because two of them were shipped first. +/// +public sealed class FileSystemRulesStore : IRulesStore +{ + private const string _markerName = ".seeded"; + + private readonly string _destination; + private readonly string _packaged; + + /// Uses the product's one rules location and the packaged seed beside this assembly. + public FileSystemRulesStore() + : this(NativeAntiCheatGuard.NativeRulesFilePath(), + Path.Combine(AppContext.BaseDirectory, "rules", "detection-rules.json")) + { + } + + /// Explicit paths. Tests only. + public FileSystemRulesStore(string destination, string packagedSeed) + { + // The destination comes from the GUARD, not from DetectionRulesFile. + // Writer and gate then cannot drift by construction rather than by + // assertion — RulesPathAgreementTests becomes a second net instead of the + // only one. A seeder that writes where the gate does not read reports + // success, and its own test would agree with it. + _destination = !string.IsNullOrEmpty(destination) + ? destination + : throw new ArgumentException("the guard could not resolve its rules path", nameof(destination)); + _packaged = packagedSeed ?? throw new ArgumentNullException(nameof(packagedSeed)); + } + + /// Where this store writes. Exposed so a test can assert it is the guard's own path. + public string Destination => _destination; + + /// + public async ValueTask ReadInstalledAsync(CancellationToken ct = default) + { + try + { + // Delete sharing, matching fl_ac_rules.cpp. Denying it here would make + // this reader the thing that blocks the guard's own replace. + var s = new FileStream(_destination, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.Asynchronous | FileOptions.SequentialScan); + await using (s.ConfigureAwait(false)) + { + using var ms = new MemoryStream(); + await s.CopyToAsync(ms, ct).ConfigureAwait(false); + return ms.ToArray(); + } + } + catch (FileNotFoundException) + { + return null; + } + catch (DirectoryNotFoundException) + { + return null; + } + } + + /// + public async ValueTask ReadPackagedSeedAsync(CancellationToken ct = default) => + await File.ReadAllBytesAsync(_packaged, ct).ConfigureAwait(false); + + /// + public async ValueTask ReadInstalledMarkerAsync(CancellationToken ct = default) + { + string path = MarkerPath(); + try + { + string text = await File.ReadAllTextAsync(path, ct).ConfigureAwait(false); + return text.Trim(); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // No marker means "we have never installed here", which is the same + // answer as an unreadable one for every decision above. + return null; + } + } + + /// + public bool IsUsableByTheGuard(byte[] candidate) + { + ArgumentNullException.ThrowIfNull(candidate); + return NativeAntiCheatGuard.NativeCheckRules(candidate) == 0; // fl::guard::ParseResult::kOk + } + + /// + public async ValueTask WriteAsync(byte[] content, bool replaceExisting, + CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(content); + string dir = Path.GetDirectoryName(_destination) + ?? throw new InvalidOperationException($"'{_destination}' has no directory"); + + try + { + Directory.CreateDirectory(dir); + + // A junction planted before first run redirects both this write and + // the guard's read, and RulesPathAgreementTests cannot see it because + // it compares path STRINGS. Check 4 already refuses reparse points for + // exactly this reason — "a junction can hide an EasyAntiCheat/ + // beneath it" — and the read path is what is being defended here. + if (AnyReparsePoint(dir)) + { + return RulesWriteOutcome.Failed; + } + + // Temp file in the DESTINATION directory: ReplaceFile and any rename + // need the same volume, and %TEMP% is both possibly elsewhere and the + // inherited-environment vector §S21 closed. Random name so it cannot + // be pre-created; FileShare.None so nothing can touch the bytes + // between validation and publication. + string tmp = Path.Combine(dir, $"detection-rules.json.{Guid.NewGuid():N}.tmp"); + RulesWriteOutcome published; + try + { + await WriteTempAsync(tmp, content, ct).ConfigureAwait(false); + published = Publish(tmp, replaceExisting); + } + finally + { + TryDelete(tmp); + } + if (published != RulesWriteOutcome.Written) + { + return published; + } + + await File.WriteAllTextAsync(MarkerPath(), Convert.ToHexString(SHA256.HashData(content)), ct) + .ConfigureAwait(false); + return RulesWriteOutcome.Written; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return RulesWriteOutcome.Failed; + } + } + + private static async ValueTask WriteTempAsync(string tmp, byte[] content, CancellationToken ct) + { + var s = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, + FileOptions.Asynchronous); + await using (s.ConfigureAwait(false)) + { + await s.WriteAsync(content, ct).ConfigureAwait(false); + + // Flush THROUGH TO DISK before the swap. FlushAsync only reaches the + // OS cache, so a crash between the write and the rename could publish + // a zero-length file at the hard gate's only input — which the guard + // reads as kRulesMalformed, i.e. refuse every title. There is no async + // flush-to-disk in .NET, so the synchronous call is the point rather + // than an oversight. +#pragma warning disable CA1849 // no async equivalent exists for flushToDisk + s.Flush(flushToDisk: true); +#pragma warning restore CA1849 + } + } + + private RulesWriteOutcome Publish(string tmp, bool replaceExisting) + { + if (replaceExisting) + { + return ReplaceFileW(_destination, tmp, BackupPath(), 0, IntPtr.Zero, IntPtr.Zero) + ? RulesWriteOutcome.Written + : RulesWriteOutcome.Failed; + } + + // Fails if the target appeared meanwhile, which is the whole point: + // losing that race means somebody else seeded it. + try + { + File.Move(tmp, _destination, overwrite: false); + return RulesWriteOutcome.Written; + } + catch (IOException) when (File.Exists(_destination)) + { + return RulesWriteOutcome.AlreadyExists; + } + } + + private string MarkerPath() => Path.Combine(Path.GetDirectoryName(_destination)!, _markerName); + + private string BackupPath() => _destination + ".bak"; + + private static void TryDelete(string path) + { + try + { + if (File.Exists(path)) + { + File.Delete(path); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A leftover temp file is litter, not a failure of the write. + } + } + + private static bool AnyReparsePoint(string directory) + { + for (DirectoryInfo? d = new(directory); d is not null; d = d.Parent) + { + if (!d.Exists) + { + continue; + } + if (d.Attributes.HasFlag(FileAttributes.ReparsePoint)) + { + return true; + } + } + return false; + } + + // MoveFileEx(MOVEFILE_REPLACE_EXISTING) is NOT usable here, and this comment + // exists because §S21 prescribed it. Measured against a handle opened exactly + // as the guard opens it (GENERIC_READ, FILE_SHARE_READ|WRITE|DELETE), it + // returns ERROR_ACCESS_DENIED; ReplaceFileW with a backup file named succeeds. + // Delete sharing is necessary and nowhere near sufficient. + // + // The backup is not incidental either: it is what makes 05_DETECTION's "the + // last valid copy is kept" a mechanism rather than a sentence. + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool ReplaceFileW(string replacedFileName, string replacementFileName, + string? backupFileName, uint replaceFlags, IntPtr exclude, IntPtr reserved); +} diff --git a/src/native/FrameLedger.Injector/include/fl_guard_abi.h b/src/native/FrameLedger.Injector/include/fl_guard_abi.h index 62ce2ecf..68167cf9 100644 --- a/src/native/FrameLedger.Injector/include/fl_guard_abi.h +++ b/src/native/FrameLedger.Injector/include/fl_guard_abi.h @@ -90,6 +90,31 @@ FL_GUARD_ABI std::int32_t FlGuardReasonCount(void); // different file. FL_GUARD_ABI std::int32_t FlGuardRulesFilePath(wchar_t* out, std::int32_t cap); +// Would the GUARD accept this rules document? Returns fl::guard::ParseResult. +// +// §S20 needs it because the managed side structurally cannot answer the +// question. `DetectionRulesFile` reads engines/platforms/capabilities and states +// at DetectionRulesDto that there is no `anticheat` member "and there never will +// be" (§S15 — no second matcher). So validating a candidate rules file with it +// checks everything except the half the hard gate consumes, and would let a +// seeder install a document the guard then refuses for every title while +// reporting success. +// +// Buffer in, enum out. NO PATH PARAMETER — the rules source is not selectable +// (§S3, §S21), and this must not become the way it becomes selectable. It parses +// a candidate the caller already holds; it does not read, choose or install +// anything. +// +// Not a second matcher: it calls fl::guard::ParseRules, the same function the +// gate parses with. That is the whole point — the thing that validates and the +// thing that parses are one. +// +// NOT re-entrant, like every other guard entry point: ParseRules uses a +// function-scope static token array. Callers are expected to be the Agent at +// startup, before any capture is running (docs/07_IPC §guardTicks describes the +// one-at-a-time contract). +FL_GUARD_ABI std::int32_t FlGuardCheckRules(const char* json, std::int32_t length); + } // extern "C" #endif // FL_GUARD_ABI_H diff --git a/src/native/FrameLedger.Injector/src/fl_guard_abi.cpp b/src/native/FrameLedger.Injector/src/fl_guard_abi.cpp index 650d95fd..733b8d9b 100644 --- a/src/native/FrameLedger.Injector/src/fl_guard_abi.cpp +++ b/src/native/FrameLedger.Injector/src/fl_guard_abi.cpp @@ -79,6 +79,18 @@ std::int32_t FlGuardRulesFilePath(wchar_t* out, std::int32_t cap) { return static_cast(wcslen(out)); } +std::int32_t FlGuardCheckRules(const char* json, std::int32_t length) { + if (json == nullptr || length <= 0) { + return static_cast(fl::guard::ParseResult::kMalformed); + } + // A whole Rules is ~200 KB; static because this is not re-entrant anyway and + // the guard allocates nothing. The parsed result is discarded — the caller + // asked whether the document is usable, not what is in it, and handing back + // the blocklist would be the second matcher §S15 forbids. + static fl::guard::Rules scratch; + return static_cast(fl::guard::ParseRules(json, static_cast(length), scratch)); +} + } // extern "C" // kAllow must stay 0: a default-constructed managed AntiCheatVerdict zeroes diff --git a/tests/FrameLedger.Application.Tests/RulesSeederTests.cs b/tests/FrameLedger.Application.Tests/RulesSeederTests.cs new file mode 100644 index 00000000..e9d294ba --- /dev/null +++ b/tests/FrameLedger.Application.Tests/RulesSeederTests.cs @@ -0,0 +1,165 @@ +using System.Security.Cryptography; +using FrameLedger.Application.Rules; + +namespace FrameLedger.Application.Tests; + +/// +/// §S20's decision table, one forced input per branch. +/// +/// +/// The store is faked so every branch is reachable; the real filesystem and the +/// real guard parser are exercised by FrameLedger.Infrastructure.Tests. +/// What matters here is that no branch can be deleted without a test going red. +/// +public sealed class RulesSeederTests +{ + private static byte[] Bytes(string s) => System.Text.Encoding.UTF8.GetBytes(s); + + private static string Hash(byte[] b) => Convert.ToHexString(SHA256.HashData(b)); + + private sealed class FakeStore : IRulesStore + { + public byte[] Packaged { get; set; } = Bytes("packaged"); + public byte[]? Installed { get; set; } + public string? Marker { get; set; } + public HashSet Unusable { get; } = []; + public RulesWriteOutcome WriteResult { get; set; } = RulesWriteOutcome.Written; + + public byte[]? Written { get; private set; } + public bool? WroteWithReplace { get; private set; } + public int Writes { get; private set; } + + public ValueTask ReadInstalledAsync(CancellationToken ct = default) => new(Installed); + + public ValueTask ReadPackagedSeedAsync(CancellationToken ct = default) => new(Packaged); + + public ValueTask ReadInstalledMarkerAsync(CancellationToken ct = default) => new(Marker); + + public bool IsUsableByTheGuard(byte[] candidate) => + !Unusable.Contains(System.Text.Encoding.UTF8.GetString(candidate), StringComparer.Ordinal); + + public ValueTask WriteAsync(byte[] content, bool replaceExisting, + CancellationToken ct = default) + { + Writes++; + Written = content; + WroteWithReplace = replaceExisting; + return new ValueTask(WriteResult); + } + } + + [Fact] + public async Task NothingInstalledMeansInstallThePackagedSeed() + { + var store = new FakeStore(); + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.Installed, outcome); + Assert.Equal(store.Packaged, store.Written); + // Non-clobber on the absent path: if a file appeared meanwhile it is not + // ours to overwrite. + Assert.False(store.WroteWithReplace); + } + + [Fact] + public async Task AlreadyThePackagedSeedMeansDoNothing() + { + var store = new FakeStore { Installed = Bytes("packaged") }; + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.AlreadyCurrent, outcome); + Assert.Equal(0, store.Writes); + } + + [Fact] + public async Task OurOwnStaleFileIsUpdated() + { + // Provenance, not version: the marker says we wrote what is there, and + // this build ships something else. + byte[] old = Bytes("what we installed last time"); + var store = new FakeStore { Installed = old, Marker = Hash(old) }; + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.Updated, outcome); + Assert.Equal(store.Packaged, store.Written); + Assert.True(store.WroteWithReplace); + } + + [Fact] + public async Task AFileWeDidNotWriteIsLeftAlone() + { + // The safe act, and only because the floor is generated from the shipped + // blocklist: a rules file can ADD to what the guard blocks and cannot + // remove anything, so leaving a foreign file cannot weaken the gate. + var store = new FakeStore { Installed = Bytes("somebody else's rules"), Marker = null }; + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.ForeignLeftAlone, outcome); + Assert.Equal(0, store.Writes); + } + + [Fact] + public async Task AStaleMarkerThatDoesNotMatchLeavesTheFileAlone() + { + // The marker names a different file from the one on disk, so we did not + // write what is there. Treated as foreign, not as ours. + var store = new FakeStore { Installed = Bytes("edited by hand"), Marker = Hash(Bytes("something else")) }; + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.ForeignLeftAlone, outcome); + Assert.Equal(0, store.Writes); + } + + [Fact] + public async Task AnUnusableInstalledFileIsReplacedWhoeverWroteIt() + { + // There is nothing to clobber — the guard already refuses every title on + // this file — and nothing else in the product repairs it, so leaving it + // would make a corrupt file a permanent machine-wide refusal. + var store = new FakeStore { Installed = Bytes("truncated{"), Marker = null }; + store.Unusable.Add("truncated{"); + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.ReplacedUnusable, outcome); + Assert.True(store.WroteWithReplace); + } + + [Fact] + public async Task AnUnusablePackagedSeedInstallsNothing() + { + // Our own artifact is checked before it is trusted. CI gates it twice, so + // this should be unreachable — which is exactly the sort of assumption + // this project keeps finding to be false. + var store = new FakeStore(); + store.Unusable.Add("packaged"); + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.PackagedSeedUnusable, outcome); + Assert.Equal(0, store.Writes); + } + + [Fact] + public async Task LosingTheRaceIsNotAFailure() + { + var store = new FakeStore { WriteResult = RulesWriteOutcome.AlreadyExists }; + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.RaceLost, outcome); + } + + [Fact] + public async Task AFailedWriteIsReportedRatherThanSwallowed() + { + var store = new FakeStore { WriteResult = RulesWriteOutcome.Failed }; + + RulesSeedOutcome outcome = await new RulesSeeder(store).EnsureSeededAsync(TestContext.Current.CancellationToken); + + Assert.Equal(RulesSeedOutcome.WriteFailed, outcome); + } +} diff --git a/tests/FrameLedger.Infrastructure.Tests/Detection/RuleFixtureCorpusTests.cs b/tests/FrameLedger.Infrastructure.Tests/Detection/RuleFixtureCorpusTests.cs index b4572efc..a0d9630b 100644 --- a/tests/FrameLedger.Infrastructure.Tests/Detection/RuleFixtureCorpusTests.cs +++ b/tests/FrameLedger.Infrastructure.Tests/Detection/RuleFixtureCorpusTests.cs @@ -37,10 +37,17 @@ public sealed class RuleFixtureCorpusTests private sealed record Expected(string? Engine, string? Platform, IReadOnlyList Capabilities); /// Walks up from the test binary to the repository root. + /// + /// Keyed on the solution file, not on a directory called rules. §S20 + /// made the seed a build artifact, so the test's OWN output directory now + /// contains rules\detection-rules.json — the walk stopped immediately + /// and every fixture went missing. A marker that exists in exactly one place + /// cannot be shadowed that way. + /// private static string RepoRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); - while (dir is not null && !Directory.Exists(Path.Combine(dir.FullName, "rules"))) + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "FrameLedger.slnx"))) { dir = dir.Parent; } diff --git a/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj b/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj index 785d68d0..0ceabce9 100644 --- a/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj +++ b/tests/FrameLedger.Infrastructure.Tests/FrameLedger.Infrastructure.Tests.csproj @@ -29,4 +29,11 @@ --> + + + diff --git a/tests/FrameLedger.Infrastructure.Tests/Rules/RulesSeedingEndToEndTests.cs b/tests/FrameLedger.Infrastructure.Tests/Rules/RulesSeedingEndToEndTests.cs new file mode 100644 index 00000000..4b5ef67f --- /dev/null +++ b/tests/FrameLedger.Infrastructure.Tests/Rules/RulesSeedingEndToEndTests.cs @@ -0,0 +1,123 @@ +using System.Security.Cryptography; +using FrameLedger.Application.Rules; +using FrameLedger.Infrastructure.AntiCheat; +using FrameLedger.Infrastructure.Rules; + +namespace FrameLedger.Infrastructure.Tests.Rules; + +/// +/// §S20 against the real filesystem and the real guard parser. +/// +public sealed class RulesSeedingEndToEndTests +{ + private static string PackagedSeed() => Path.Combine(AppContext.BaseDirectory, "rules", "detection-rules.json"); + + [Fact] + public void ThePackagedSeedShipsAndIsTheFileCiValidated() + { + // Without this, the seeder and its own tests could agree with each other + // while the artifact carried nothing — PreserveNewest compares timestamps, + // so a stale copy is a real outcome rather than a hypothetical one. + Assert.True(File.Exists(PackagedSeed()), $"no packaged seed at {PackagedSeed()}"); + + string repoRoot = RepoRoot(); + string inRepo = Path.Combine(repoRoot, "rules", "detection-rules.json"); + Assert.True(File.Exists(inRepo), $"no repository seed at {inRepo}"); + + Assert.Equal( + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(inRepo))), + Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(PackagedSeed())))); + } + + [Fact] + public void TheGuardsOwnParserAcceptsThePackagedSeedAndRejectsRubbish() + { + // Both directions, because a validator that accepts everything would pass + // the first assertion on its own. + Assert.Equal(0, NativeAntiCheatGuard.NativeCheckRules(File.ReadAllBytes(PackagedSeed()))); + Assert.NotEqual(0, NativeAntiCheatGuard.NativeCheckRules("{ not json"u8.ToArray())); + Assert.NotEqual(0, NativeAntiCheatGuard.NativeCheckRules("""{"anticheat":{"modules":[]}}"""u8.ToArray())); + } + + [Fact] + public async Task SeedingIntoAnEmptyDirectoryProducesAFileTheGuardAccepts() + { + // A scratch destination, NOT the machine's real rules location: a test + // that mutates the product's one file leaves the guard refusing every + // title if it dies between delete and restore. + string dir = Path.Combine(Path.GetTempPath(), "fl-seed-" + Guid.NewGuid().ToString("N")[..8]); + string dest = Path.Combine(dir, "rules", "detection-rules.json"); + try + { + var store = new FileSystemRulesStore(dest, PackagedSeed()); + var seeder = new RulesSeeder(store); + + Assert.Equal(RulesSeedOutcome.Installed, await seeder.EnsureSeededAsync(TestContext.Current.CancellationToken)); + Assert.True(File.Exists(dest)); + Assert.Equal(0, NativeAntiCheatGuard.NativeCheckRules(await File.ReadAllBytesAsync(dest, TestContext.Current.CancellationToken))); + + // Idempotent: a second run must not rewrite a current file. + Assert.Equal(RulesSeedOutcome.AlreadyCurrent, await seeder.EnsureSeededAsync(TestContext.Current.CancellationToken)); + + // Our own stale file is updated, and the backup ReplaceFileW keeps is + // what makes 05_DETECTION's "the last valid copy is kept" a mechanism. + await File.WriteAllTextAsync(dest, "{ deliberately unusable", TestContext.Current.CancellationToken); + Assert.Equal(RulesSeedOutcome.ReplacedUnusable, await seeder.EnsureSeededAsync(TestContext.Current.CancellationToken)); + Assert.Equal(0, NativeAntiCheatGuard.NativeCheckRules(await File.ReadAllBytesAsync(dest, TestContext.Current.CancellationToken))); + Assert.True(File.Exists(dest + ".bak"), "the replaced file should have been kept"); + } + finally + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, recursive: true); + } + } + } + + [Fact] + public async Task AUsableFileWeDidNotWriteIsLeftAlone() + { + string dir = Path.Combine(Path.GetTempPath(), "fl-seed-" + Guid.NewGuid().ToString("N")[..8]); + string dest = Path.Combine(dir, "rules", "detection-rules.json"); + try + { + Directory.CreateDirectory(Path.GetDirectoryName(dest)!); + // A real, usable rules document that we did not install: the shipped + // seed with one extra byte of whitespace, so its hash differs. + byte[] foreign = [.. await File.ReadAllBytesAsync(PackagedSeed(), TestContext.Current.CancellationToken), (byte)'\n']; + await File.WriteAllBytesAsync(dest, foreign, TestContext.Current.CancellationToken); + + var seeder = new RulesSeeder(new FileSystemRulesStore(dest, PackagedSeed())); + Assert.Equal(RulesSeedOutcome.ForeignLeftAlone, await seeder.EnsureSeededAsync(TestContext.Current.CancellationToken)); + Assert.Equal(foreign, await File.ReadAllBytesAsync(dest, TestContext.Current.CancellationToken)); + } + finally + { + if (Directory.Exists(dir)) + { + Directory.Delete(dir, recursive: true); + } + } + } + + [Fact] + public void TheStoreWritesWhereTheGUARDReads() + { + // The parameterless store resolves its destination from the guard's own + // exported path, so a seeder that writes where the gate does not read is + // impossible by construction rather than by assertion. + Assert.Equal(NativeAntiCheatGuard.NativeRulesFilePath(), new FileSystemRulesStore().Destination); + } + + private static string RepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "FrameLedger.slnx"))) + { + dir = dir.Parent; + } + Assert.NotNull(dir); + return dir!.FullName; + } +}