feat(safety): the Agent seeds the rules file the guard reads (#27)
Nothing in this repository ever wrote the file the hard gate reads, so 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. 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. Four Agent branches exercised against the machine's real rules location, with its own file backed up and restored by hash — already-current, installed-from-nothing, idempotent second run, corrupt-file-replaced. ## Four decisions, each replacing 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, `31825cf` and `ba5355e` both changed the `anticheat` block without touching `rulesVersion`, and `a4a2c63` — the only commit that bumped it — changed the block not at all. The rule would have delivered NONE of the two changes it existed for. The seeder records a hash of what it installed instead. - **`ReplaceFileW`, not `MoveFileEx`.** Measured: `MoveFileEx(REPLACE_EXISTING)` returns `ERROR_ACCESS_DENIED` against a reader holding the guard's exact share mode. Its 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` — buffer in, `ParseResult` out, no path parameter, so §S3/§S21's "the rules source is not selectable" is untouched. `DetectionRulesFile` never reads the `anticheat` block (§S15), so 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 the seeder logged success. - **A usable file we did not write is left alone.** Safe only because the floor is 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. An UNUSABLE file is replaced whoever wrote it — there is nothing to clobber and nothing else repairs it. ## Mechanics Random temp name in the DESTINATION directory (same volume, and `%TEMP%` is the inherited-environment vector §S21 closed), opened `FileShare.None`, flushed through to disk before the swap, and a reparse-point check on the directory chain. ## The caller is real `FrameLedger.Agent/Program.cs` was `return 0`. It now runs the seeder and reports the outcome, and a no-op seeder fails 8 Application tests and 2 Infrastructure tests — proven by making it one. ## One regression caught by an existing test `RuleFixtureCorpusTests` walks up from the test binary looking for a directory called `rules`, and this puts one in the test's own output. The walk stopped immediately and every fixture went missing. Re-keyed on `FrameLedger.slnx`. ## §S20 does not close Rewritten to the residual rather than deleted: the HTTPS feed does not exist so FR-7.3 is unmet; the guard still reads no version so binary and data have no handshake, and `13_CI_CD`'s claim that rules-publish checks the bump was false and is corrected; `trustedSigners` is the one allow-widening field a foreign file still controls, inert until §S19(b) wires the signer half; and this is what makes the Vulkan layer's §S2 self-scan reachable for the first time. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9e0bcec905
commit
1ed07c08c6
18 files changed
+1069
-22
No files matched your search
@@ -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
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<Project>
|
||||
|
||||
<!--
|
||||
Ships rules/detection-rules.json beside the importing project's output, as
|
||||
`rules\detection-rules.json`.
|
||||
|
||||
§S20: the guard reads its blocklist from Local AppData and nothing in this
|
||||
repository ever put a file there, so on any machine that has not hand-installed
|
||||
one the guard answers RulesUnreadable for every title. The first half of fixing
|
||||
that is having the seed in a build output at all — before this file, it was in
|
||||
no csproj, no props and no targets.
|
||||
|
||||
Imported by exactly two projects:
|
||||
- FrameLedger.Agent — the sole host (§S18 blocker 3, ratified),
|
||||
and the only thing that seeds.
|
||||
- FrameLedger.Infrastructure.Tests — asserts the shipped copy is the file CI
|
||||
validated, and drives the seeder end to end.
|
||||
|
||||
NOT imported by FrameLedger.App, for the same reason it does not carry the
|
||||
guard DLL.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<FlSeedRules>$(MSBuildThisFileDirectory)rules\detection-rules.json</FlSeedRules>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Include="$(FlSeedRules)">
|
||||
<Link>rules\detection-rules.json</Link>
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<!--
|
||||
An ERROR, not a warning, and no Exists() condition on the item above.
|
||||
|
||||
FrameLedger.Guard.targets warns, because the native build may legitimately not
|
||||
have run yet on a fresh clone. This file is different: rules/detection-rules.json
|
||||
is checked in, so its absence is not a state anyone builds through — it means
|
||||
the repository is wrong. Copying the Guard.targets warn-half here would be the
|
||||
gate-that-cannot-fail shape: the seeder would ship, find nothing to seed, and
|
||||
report success.
|
||||
-->
|
||||
<Target Name="FlErrorOnMissingSeedRules" BeforeTargets="Build"
|
||||
Condition="!Exists('$(FlSeedRules)')">
|
||||
<Error Text="rules/detection-rules.json is missing at $(FlSeedRules). It is checked in; a build without it would produce an Agent that seeds nothing and says it succeeded." />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
+15
-1
@@ -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
|
||||
|
||||
+70
-17
@@ -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**
|
||||
|
||||
|
||||
@@ -36,4 +36,7 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
|
||||
|
||||
<!-- The seed the Agent installs to the product location on first run (§S20). -->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
|
||||
|
||||
</Project>
|
||||
@@ -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<int> 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(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
namespace FrameLedger.Application.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// Everything <see cref="RulesSeeder"/> needs to know about the rules file, and
|
||||
/// nothing else.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <strong>No method takes a path.</strong> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <strong>Validation is not this layer's job either.</strong>
|
||||
/// <see cref="IsUsableByTheGuard"/> asks the native guard's own parser, because
|
||||
/// the managed detection reader structurally cannot see the <c>anticheat</c>
|
||||
/// 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.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public interface IRulesStore
|
||||
{
|
||||
/// <summary>The rules file the guard reads, if one is there.</summary>
|
||||
/// <returns><c>null</c> when absent. Throws only on genuinely unexpected IO.</returns>
|
||||
ValueTask<byte[]?> ReadInstalledAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>The seed shipped in this build.</summary>
|
||||
ValueTask<byte[]> ReadPackagedSeedAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// The content hash this store last recorded as its own work, or <c>null</c>
|
||||
/// if it has never installed anything here.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Provenance rather than version. §S20's first design compared
|
||||
/// <c>rulesVersion</c> — 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.
|
||||
/// </remarks>
|
||||
ValueTask<string?> ReadInstalledMarkerAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>Would the native guard accept this document?</summary>
|
||||
bool IsUsableByTheGuard(byte[] candidate);
|
||||
|
||||
/// <summary>
|
||||
/// Write <paramref name="content"/> to the rules location, atomically, keeping
|
||||
/// a backup of whatever was there, and record the hash as ours.
|
||||
/// </summary>
|
||||
/// <param name="content">The bytes to install.</param>
|
||||
/// <param name="replaceExisting">
|
||||
/// <c>false</c> refuses if a file appeared after we looked — losing that race
|
||||
/// means somebody else installed one, which is not an error.
|
||||
/// </param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
ValueTask<RulesWriteOutcome> WriteAsync(byte[] content, bool replaceExisting, CancellationToken ct = default);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
namespace FrameLedger.Application.Rules;
|
||||
|
||||
/// <summary>What <see cref="RulesSeeder"/> did, and why.</summary>
|
||||
/// <remarks>
|
||||
/// Every value is reportable. §S20's failure mode is silence: a seeder that wrote
|
||||
/// nothing and said nothing leaves the guard answering <c>RulesUnreadable</c> for
|
||||
/// every title with no trace of why.
|
||||
/// </remarks>
|
||||
public enum RulesSeedOutcome
|
||||
{
|
||||
/// <summary>Nothing was there; the packaged seed was installed.</summary>
|
||||
Installed = 0,
|
||||
|
||||
/// <summary>
|
||||
/// The installed file was one we had installed, and this build ships a
|
||||
/// different one. Replaced.
|
||||
/// </summary>
|
||||
Updated,
|
||||
|
||||
/// <summary>The installed file is already exactly the packaged seed.</summary>
|
||||
AlreadyCurrent,
|
||||
|
||||
/// <summary>
|
||||
/// A usable file is there that we did not install. Left alone.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
ForeignLeftAlone,
|
||||
|
||||
/// <summary>
|
||||
/// The installed file is not usable by the guard, so it was replaced.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
ReplacedUnusable,
|
||||
|
||||
/// <summary>
|
||||
/// Somebody else won the race to create the file between our look and our
|
||||
/// write. Not an error.
|
||||
/// </summary>
|
||||
RaceLost,
|
||||
|
||||
/// <summary>
|
||||
/// The seed shipped in this build is not usable by the guard. Nothing was
|
||||
/// installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Should be unreachable: <c>rules-validate.ps1</c> and ctest
|
||||
/// <c>fl_rules_budget</c> 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.
|
||||
/// </remarks>
|
||||
PackagedSeedUnusable,
|
||||
|
||||
/// <summary>The rules location could not be written. Reported, not swallowed.</summary>
|
||||
WriteFailed,
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace FrameLedger.Application.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// Puts a usable rules file where the guard reads one (<c>20_OPEN_QUESTIONS</c> §S20).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Before this existed, nothing in the repository ever wrote that file, so on any
|
||||
/// machine that had not hand-installed one the guard answered
|
||||
/// <c>RulesUnreadable</c> for every title. That is correct fail-closed behaviour
|
||||
/// and also the whole story: the first real injection's opening refusal was
|
||||
/// exactly this.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <strong>What makes the decisions below safe is the floor, not this class.</strong>
|
||||
/// 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 (<c>19_SAFETY</c> §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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <strong>Residual, stated rather than discovered:</strong> the one
|
||||
/// allow-widening field a foreign file still controls is
|
||||
/// <c>anticheat.heuristic.trustedSigners</c>, which is deliberately not floored
|
||||
/// because flooring an allowlist has the wrong polarity. It is inert today —
|
||||
/// <c>IsTrustedSigner</c> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <strong>This is the seed half only.</strong> There is no fetch client and no
|
||||
/// network call; <c>05_DETECTION</c> §Trust and staleness describes an HTTPS feed
|
||||
/// that remains unbuilt, so FR-7.3's independent anti-cheat update schedule is
|
||||
/// still unmet.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class RulesSeeder(IRulesStore store)
|
||||
{
|
||||
private readonly IRulesStore _store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
|
||||
/// <summary>Ensure a usable rules file exists, and keep our own copy current.</summary>
|
||||
public async ValueTask<RulesSeedOutcome> 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<RulesSeedOutcome> 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));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace FrameLedger.Application.Rules;
|
||||
|
||||
/// <summary>What the store's write attempt did.</summary>
|
||||
public enum RulesWriteOutcome
|
||||
{
|
||||
/// <summary>The file is now the content we asked for.</summary>
|
||||
Written = 0,
|
||||
|
||||
/// <summary>
|
||||
/// A file appeared between the look and the write, and we were told not to
|
||||
/// replace it. Not an error — somebody else seeded it.
|
||||
/// </summary>
|
||||
AlreadyExists,
|
||||
|
||||
/// <summary>Could not write. The caller reports it rather than retrying blindly.</summary>
|
||||
Failed,
|
||||
}
|
||||
@@ -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.
|
||||
/// </remarks>
|
||||
/// <summary>
|
||||
/// Would the native guard accept this rules document? Returns
|
||||
/// <c>fl::guard::ParseResult</c>; <c>0</c> is <c>kOk</c>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// §S20's seeder needs this because nothing managed can answer it:
|
||||
/// <c>DetectionRulesFile</c> reads engines/platforms/capabilities and, by
|
||||
/// explicit design, never the <c>anticheat</c> block (§S15 — no second
|
||||
/// matcher). Validating a candidate with the managed reader would check
|
||||
/// everything except the half the hard gate consumes.
|
||||
/// <para>
|
||||
/// Observation only: buffer in, enum out, no path parameter, nothing
|
||||
/// installed. It calls the same <c>ParseRules</c> the gate parses with, so
|
||||
/// the thing that validates and the thing that parses are one.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
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
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using FrameLedger.Application.Rules;
|
||||
using FrameLedger.Infrastructure.AntiCheat;
|
||||
|
||||
namespace FrameLedger.Infrastructure.Rules;
|
||||
|
||||
/// <summary>
|
||||
/// The real filesystem behind <see cref="IRulesStore"/> (§S20).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Three mechanisms here were each chosen against an obvious wrong answer, and
|
||||
/// the wrong answers are recorded because two of them were shipped first.
|
||||
/// </remarks>
|
||||
public sealed class FileSystemRulesStore : IRulesStore
|
||||
{
|
||||
private const string _markerName = ".seeded";
|
||||
|
||||
private readonly string _destination;
|
||||
private readonly string _packaged;
|
||||
|
||||
/// <summary>Uses the product's one rules location and the packaged seed beside this assembly.</summary>
|
||||
public FileSystemRulesStore()
|
||||
: this(NativeAntiCheatGuard.NativeRulesFilePath(),
|
||||
Path.Combine(AppContext.BaseDirectory, "rules", "detection-rules.json"))
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Explicit paths. Tests only.</summary>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>Where this store writes. Exposed so a test can assert it is the guard's own path.</summary>
|
||||
public string Destination => _destination;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<byte[]?> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<byte[]> ReadPackagedSeedAsync(CancellationToken ct = default) =>
|
||||
await File.ReadAllBytesAsync(_packaged, ct).ConfigureAwait(false);
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<string?> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsUsableByTheGuard(byte[] candidate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(candidate);
|
||||
return NativeAntiCheatGuard.NativeCheckRules(candidate) == 0; // fl::guard::ParseResult::kOk
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async ValueTask<RulesWriteOutcome> 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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -79,6 +79,18 @@ std::int32_t FlGuardRulesFilePath(wchar_t* out, std::int32_t cap) {
|
||||
return static_cast<std::int32_t>(wcslen(out));
|
||||
}
|
||||
|
||||
std::int32_t FlGuardCheckRules(const char* json, std::int32_t length) {
|
||||
if (json == nullptr || length <= 0) {
|
||||
return static_cast<std::int32_t>(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<std::int32_t>(fl::guard::ParseRules(json, static_cast<std::size_t>(length), scratch));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
// kAllow must stay 0: a default-constructed managed AntiCheatVerdict zeroes
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
using System.Security.Cryptography;
|
||||
using FrameLedger.Application.Rules;
|
||||
|
||||
namespace FrameLedger.Application.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// §S20's decision table, one forced input per branch.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The store is faked so every branch is reachable; the real filesystem and the
|
||||
/// real guard parser are exercised by <c>FrameLedger.Infrastructure.Tests</c>.
|
||||
/// What matters here is that no branch can be deleted without a test going red.
|
||||
/// </remarks>
|
||||
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<string> 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<byte[]?> ReadInstalledAsync(CancellationToken ct = default) => new(Installed);
|
||||
|
||||
public ValueTask<byte[]> ReadPackagedSeedAsync(CancellationToken ct = default) => new(Packaged);
|
||||
|
||||
public ValueTask<string?> ReadInstalledMarkerAsync(CancellationToken ct = default) => new(Marker);
|
||||
|
||||
public bool IsUsableByTheGuard(byte[] candidate) =>
|
||||
!Unusable.Contains(System.Text.Encoding.UTF8.GetString(candidate), StringComparer.Ordinal);
|
||||
|
||||
public ValueTask<RulesWriteOutcome> WriteAsync(byte[] content, bool replaceExisting,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
Writes++;
|
||||
Written = content;
|
||||
WroteWithReplace = replaceExisting;
|
||||
return new ValueTask<RulesWriteOutcome>(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);
|
||||
}
|
||||
}
|
||||
@@ -37,10 +37,17 @@ public sealed class RuleFixtureCorpusTests
|
||||
private sealed record Expected(string? Engine, string? Platform, IReadOnlyList<string> Capabilities);
|
||||
|
||||
/// <summary>Walks up from the test binary to the repository root.</summary>
|
||||
/// <remarks>
|
||||
/// Keyed on the solution file, not on a directory called <c>rules</c>. §S20
|
||||
/// made the seed a build artifact, so the test's OWN output directory now
|
||||
/// contains <c>rules\detection-rules.json</c> — the walk stopped immediately
|
||||
/// and every fixture went missing. A marker that exists in exactly one place
|
||||
/// cannot be shadowed that way.
|
||||
/// </remarks>
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -29,4 +29,11 @@
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Guard.targets" />
|
||||
|
||||
<!--
|
||||
The packaged seed, so the seeder tests run against the artifact that ships
|
||||
rather than against the repository path. One of them asserts the two are the
|
||||
same file.
|
||||
-->
|
||||
<Import Project="$(MSBuildThisFileDirectory)..\..\FrameLedger.Rules.targets" />
|
||||
|
||||
</Project>
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// §S20 against the real filesystem and the real guard parser.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user