Files
Beqaandmorluto a6cca9dc62 feat(artifacts): decode UnityFS LZMA blocks (#14699)
* feat(artifacts): decode UnityFS LZMA blocks

Unity's default AssetBundle compression (type 1) left members as
hash_status unavailable. Decode 5-byte Unity LZMA streams with the
existing lzma-purejs dependency so inventory can hash and extract them.

* fix(compression): read Unity LZMA dictionary via BinaryReader

Architecture guards forbid raw Buffer numeric reads outside
binaryContainer; match the UEFI LZMA path.

* style(compression): format UnityFS LZMA helper

* fix(compression): make UnityFS LZMA cancelable and end-marker safe

Accept optional LZMA end markers without trailing junk, decode off-thread so
timer aborts land, return one expected-sized buffer, and mark xinzexi unverified.

* fix(compression): await Unity LZMA worker exit and transfer alone buffer

Await worker.terminate() before settling abort/reply paths, and allocate the
synthesized alone header with allocUnsafeSlow so the worker receives it without
a second encoded-stream copy.

* chore: retrigger CI after Greptile worker-exit follow-up

* test(compression): clarify Unity LZMA cancellation case title

Retriggers Actions after the worker-exit follow-up push did not receive a
GitHub Actions check suite.

* fix(unityfs): keep the directory for over-budget LZMA blocks and decode spec-valid streams

UnityFS writers emit one LZMA block for a whole data stream, so the per-block
decode budget refused the whole inventory of any LZMA bundle above 64 MiB,
where before this change the directory was retained. An over-budget block now
keeps the directory and only members inside it report an unavailable read
naming the budget, for LZ4 and LZMA alike.

The LZMA decoder window is bounded by the declared output instead of the
declared dictionary, so a large dictionary on a small block decodes and no
longer allocates a dictionary-sized window. Properties follow the LZMA
specification (lc 0-8, lp 0-4, pb 0-4) rather than the LZMA2 lc + lp limit.
Worker error events and exits without a reply stay runtime failures instead of
being reported as a malformed block.

Tests decode a liblzma-produced stream as a known answer, settle only after
the worker exits on completion and cancellation, and share one encoder.

* fix(artifacts): report Unity LZMA size mismatch as malformed

Overflow past the bundle's declared length is a format error, not a
decoder budget exhaustion. Declarations above maximumBytes still fail
closed as a resource limit before decode starts.

* fix(unityfs): name the encoded or decoded bound that refused a block

A block refused by its encoded size reported its decoded size against the decoded budget. The block now records which bound refused it, and the member read names that bound, its declared size and the budget.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-27 12:44:20 -05:00

259 lines
8.9 KiB
TypeScript

import { createHash } from "node:crypto";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { artifactInspectionResultSchema } from "../../../src/domain/artifactInspection.js";
import { artifactExtractionResultSchema } from "../../../src/domain/artifactGraph.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { buildUnityFs } from "../../fixtures/unityfs.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.for([
"fixed header",
"header padding",
"directory",
"payload",
] as const)(
"rejects a UnityFS declaration excluding its %s",
async (boundary, { cli }) => {
const root = await createTestTempDirectory("rea-unity-extent-");
const path = join(root, "bundle");
const bytes = buildUnityFs([{ path: "payload.txt", data: "ORIGINAL" }], {
blockCompression: 0,
blocksInfoCompression: 0,
});
// The fixture's fixed tail starts at 32; its format-8 header is padded to 64.
const declaredSize = {
"fixed header": 16,
"header padding": 63,
directory: 64 + bytes.readUInt32BE(40) - 1,
payload: bytes.length - 1,
}[boundary]!;
bytes.writeBigUInt64BE(BigInt(declaredSize), 32);
await writeFile(path, bytes);
const result = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(1);
expect(result.json).toMatchObject({
code: "unsupported_target",
details: { path, failure_kind: "malformed", format: "unityfs" },
});
},
);
cliTest.for([false, true])(
"keeps the declared UnityFS inventory and payload with an appended replacement directory (footer: %s)",
async (blocksInfoAtEnd, { cli }) => {
const root = await createTestTempDirectory("rea-unity-trailer-");
const path = join(root, "bundle");
const payload = Buffer.from("ORIGINAL");
const options = {
blocksInfoAtEnd,
blockCompression: 0,
blocksInfoCompression: 0,
};
const original = buildUnityFs(
[{ path: "payload.txt", data: payload }],
options,
);
const replacement = buildUnityFs([{ path: "outside.txt", data: payload }], {
...options,
blocksInfoAtEnd: true,
});
const directory = replacement.subarray(
replacement.length - replacement.readUInt32BE(40),
);
await writeFile(path, Buffer.concat([original, directory]));
const inspected = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(inspected.exitCode, inspected.stderr).toBe(0);
const inventory = artifactInspectionResultSchema.parse(
parseEvidence(inspected.json).normalized_result,
).substeps[0]!.evidence.normalized_result;
expect(inventory.occurrences.map((entry) => entry.logical_path)).toEqual([
".",
"payload.txt",
]);
expect(inventory.occurrences[0]!.format_metadata).toMatchObject({
declared_size: original.length,
});
const outputRoot = join(root, "extracted");
const extracted = await cli.run({
arguments: [
"extract-artifact",
path,
"--output-root",
outputRoot,
"--json",
],
});
expect(extracted.exitCode, extracted.stderr).toBe(0);
expect(
(await readFile(join(outputRoot, "payload.txt"))).equals(payload),
).toBe(true);
},
);
cliTest(
"inspects and extracts UnityFS with virtual coordinates and retained unavailable members",
async ({ cli, onTestFinished }) => {
const root = await createTestTempDirectory("rea-unity-cli-");
const path = join(root, "bundle");
const payload = Buffer.from("serialized bytes");
await writeFile(
path,
buildUnityFs([{ path: "data..bin", data: payload, flags: 4 }]),
);
const inspected = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(inspected.exitCode, inspected.stderr).toBe(0);
const inspection = artifactInspectionResultSchema.parse(
parseEvidence(inspected.json).normalized_result,
);
const inventory = inspection.substeps[0]!.evidence.normalized_result;
expect(inventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: "data..bin",
source_location: null,
hash_status: "verified",
format_metadata: {
kind: "unityfs-entry",
index: 0,
source_path: "data..bin",
declared_offset: 0,
flags: 4,
},
}),
);
expect(inventory.nodes).toContainEqual(
expect.objectContaining({
sha256: createHash("sha256").update(payload).digest("hex"),
}),
);
const extracted = await cli.run({
arguments: ["extract-artifact", path, "--json"],
});
expect(extracted.exitCode, extracted.stderr).toBe(0);
const output = artifactExtractionResultSchema.parse(
parseEvidence(extracted.json).normalized_result,
);
onTestFinished(() =>
rm(output.output_root, { recursive: true, force: true }),
);
expect(
(await readFile(join(output.output_root, "data..bin"))).equals(payload),
).toBe(true);
await writeFile(
path,
buildUnityFs([{ path: "CAB-lzma", data: payload }], {
blockCompression: 1,
}),
);
const lzma = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(lzma.exitCode, lzma.stderr).toBe(0);
const lzmaInventory = artifactInspectionResultSchema.parse(
parseEvidence(lzma.json).normalized_result,
).substeps[0]!.evidence.normalized_result;
expect(lzmaInventory.coverage).toMatchObject({ status: "complete" });
expect(lzmaInventory.occurrences).toContainEqual(
expect.objectContaining({
logical_path: "CAB-lzma",
hash_status: "verified",
}),
);
expect(lzmaInventory.nodes).toContainEqual(
expect.objectContaining({
sha256: createHash("sha256").update(payload).digest("hex"),
}),
);
},
);
cliTest(
"keeps an unsafe declared uint64 size unknown in desktop header facts",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-unity-desktop-");
await mkdir(join(root, "assets"));
const bytes = buildUnityFs([{ path: "CAB", data: "bytes" }]);
bytes.writeBigUInt64BE(2n ** 53n + 1n, 32);
await writeFile(join(root, "assets", "content.bundle"), bytes);
const result = await cli.run({
arguments: ["inspect-desktop-application", root, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
expect(parseEvidence(result.json).normalized_result).toMatchObject({
files: expect.arrayContaining([
expect.objectContaining({
path: "assets/content.bundle",
ranges: [{ offset: 0, bytes: 64, sha256: expect.any(String) }],
facts: expect.arrayContaining([
expect.objectContaining({
kind: "unityfs-header",
value: expect.objectContaining({ declared_size: null }),
}),
]),
}),
]),
});
},
);
cliTest(
"retains the same UnityFS header facts when the version strings extend past the desktop prefix",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-unity-desktop-header-");
const assets = join(root, "assets");
await mkdir(assets);
const engineVersion = "2022.3.1f1";
const bytes = buildUnityFs([{ path: "CAB", data: Buffer.alloc(3_000) }], {
playerVersion: "game-player-build-" + "x".repeat(72),
engineVersion,
blockCompression: 0,
});
const path = join(assets, "content.bundle");
await writeFile(path, bytes);
const inventory = await cli.run({
arguments: ["inspect-artifact", path, "--json"],
});
expect(inventory.exitCode, inventory.stderr).toBe(0);
const artifact = artifactInspectionResultSchema.parse(
parseEvidence(inventory.json).normalized_result,
).substeps[0]!.evidence.normalized_result;
const facts = {
format_version: 8,
engine_version: engineVersion,
declared_size: bytes.length,
};
expect(artifact.occurrences[0]!.format_metadata).toMatchObject(facts);
const scan = await cli.run({
arguments: ["inspect-desktop-application", root, "--json"],
});
expect(scan.exitCode, scan.stderr).toBe(0);
expect(parseEvidence(scan.json).normalized_result).toMatchObject({
files: expect.arrayContaining([
expect.objectContaining({
path: "assets/content.bundle",
facts: expect.arrayContaining([
expect.objectContaining({
kind: "unityfs-header",
value: expect.objectContaining(facts),
}),
]),
ranges: expect.arrayContaining([
expect.objectContaining({ offset: 0, bytes: 64 }),
expect.objectContaining({ offset: 64, bytes: 2_016 }),
]),
}),
]),
});
},
);