mirror of
https://github.com/morluto/rea.git
synced 2026-12-01 16:48:52 +00:00
* 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>
652 lines
23 KiB
TypeScript
652 lines
23 KiB
TypeScript
import { collectEntries } from "../../tests/fixtures/artifactEntries.js";
|
|
import {
|
|
artifactPreparationRecoveryCases,
|
|
boundedArchiveStreamCases,
|
|
} from "../../tests/fixtures/artifactReaderLifecycle.js";
|
|
import { truncate, writeFile } from "node:fs/promises";
|
|
import { buffer, text } from "node:stream/consumers";
|
|
import { setImmediate } from "node:timers/promises";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
import { createTestTempFile } from "../../tests/fixtures/temporaryDirectory.js";
|
|
import { createDeferred } from "../../tests/fixtures/binarySession.js";
|
|
import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js";
|
|
import { buildUnityFs } from "../../tests/fixtures/unityfs.js";
|
|
import { openRegularFile } from "../filesystem/RegularFile.js";
|
|
import { UnityFsArtifactReader } from "./UnityFsArtifactReader.js";
|
|
import { ArtifactFileSource } from "../resources/index.js";
|
|
|
|
const fixture = (bytes: Buffer): Promise<string> =>
|
|
createTestTempFile("rea-unity-boundary-", "bundle", bytes);
|
|
|
|
// A valid two-sequence LZ4 block: one literal, a distance-one match, five final
|
|
// literals. The decoder yields after the large match, before the last sequence.
|
|
const repeatedBlock = (data: Buffer): Buffer => {
|
|
const extra = data.length - 6 - 19;
|
|
const extension = [
|
|
...Array<number>(Math.floor(extra / 255)).fill(255),
|
|
extra % 255,
|
|
];
|
|
return Buffer.from([
|
|
0x1f,
|
|
data[0]!,
|
|
1,
|
|
0,
|
|
...extension,
|
|
0x50,
|
|
...data.subarray(-5),
|
|
]);
|
|
};
|
|
|
|
it("retries UnityFs preparation cancelled during file reading", async () => {
|
|
const path = await fixture(buildUnityFs([{ path: "a", data: "x" }]));
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const controller = new AbortController();
|
|
const reason = { stage: "header read" };
|
|
const nativeRead = admitted.handle.read.bind(admitted.handle);
|
|
const read = vi.spyOn(admitted.handle, "read").mockImplementation((async (
|
|
...args: unknown[]
|
|
) => {
|
|
const result = await Reflect.apply(nativeRead, admitted.handle, args);
|
|
controller.abort(reason);
|
|
return result;
|
|
}) as typeof admitted.handle.read);
|
|
try {
|
|
await expect(
|
|
(async () => {
|
|
for await (const _ of reader.entries(controller.signal)) {
|
|
}
|
|
})(),
|
|
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
|
|
read.mockRestore();
|
|
expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([
|
|
"a",
|
|
]);
|
|
} finally {
|
|
read.mockRestore();
|
|
await reader.close();
|
|
await admitted.handle.close();
|
|
}
|
|
});
|
|
|
|
it("does not publish UnityFs entries when final source verification fails", async () => {
|
|
const path = await fixture(buildUnityFs([{ path: "a", data: "x" }]));
|
|
const control = new UnityFsArtifactReader(path);
|
|
const reader = new UnityFsArtifactReader(path);
|
|
const expected = (await collectEntries(control))[0]!;
|
|
const nativeRead = ArtifactFileSource.prototype.read;
|
|
const physical = Object.assign(
|
|
new Error("final source verification failed"),
|
|
{ code: "EIO" },
|
|
);
|
|
let calls = 0;
|
|
const read = vi
|
|
.spyOn(ArtifactFileSource.prototype, "read")
|
|
.mockImplementation(function (this: ArtifactFileSource, ...args) {
|
|
calls += 1;
|
|
if (calls === 2) return Promise.reject(physical);
|
|
return nativeRead.apply(this, args);
|
|
});
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toBe(physical);
|
|
await expect(reader.open(expected)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
});
|
|
read.mockRestore();
|
|
expect((await collectEntries(reader)).map((entry) => entry.path)).toEqual([
|
|
"a",
|
|
]);
|
|
} finally {
|
|
read.mockRestore();
|
|
await reader.close();
|
|
await control.close();
|
|
}
|
|
});
|
|
|
|
describe("UnityFS declared container bounds", () => {
|
|
it.each([
|
|
["encrypted", { flags: 0x1400 | 0xc3 }],
|
|
["unsupported compression", { blocksInfoCompression: 4 }],
|
|
["unknown layout", { engineVersion: "2021.x.32f1c1", flags: 0x2c3 }],
|
|
] as const)(
|
|
"rejects an impossible footer extent even with %s",
|
|
async (_, options) => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "x" }], {
|
|
...options,
|
|
blocksInfoAtEnd: true,
|
|
});
|
|
bytes.writeUInt32BE(bytes.length + 1, 40);
|
|
const reader = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "malformed",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("does not increase the bundle's plaintext-work budget for appended carrier bytes", async () => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "x" }], {
|
|
blocksInfoCompression: 0,
|
|
blockCompression: 0,
|
|
});
|
|
// A one-byte unsupported block declares more than the 256 MiB work floor.
|
|
// Its bytes need not be decoded to reject the declared virtual extent.
|
|
bytes.writeUInt32BE(256 * 1024 * 1024 + 1, 64 + 20);
|
|
bytes.writeUInt16BE(4, 64 + 28);
|
|
const reader = new UnityFsArtifactReader(
|
|
await fixture(Buffer.concat([bytes, Buffer.alloc(1024 * 1024)])),
|
|
);
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "limit",
|
|
message: expect.stringContaining("declared virtual stream"),
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("UnityFS per-block decode budget", () => {
|
|
it.each([
|
|
{ blocksInfoAtEnd: false, blockCompression: 2 },
|
|
{ blocksInfoAtEnd: true, blockCompression: 2 },
|
|
{ blocksInfoAtEnd: false, blockCompression: 1 },
|
|
{ blocksInfoAtEnd: true, blockCompression: 1 },
|
|
])(
|
|
"keeps the directory and refuses only members of an over-budget block, then validates its encoded range ($blockCompression, footer: $blocksInfoAtEnd)",
|
|
async ({ blocksInfoAtEnd, blockCompression }) => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "abc" }], {
|
|
blocksInfoAtEnd,
|
|
blocksInfoCompression: 0,
|
|
blockCompression,
|
|
});
|
|
const tableOffset = blocksInfoAtEnd
|
|
? bytes.length - bytes.readUInt32BE(40)
|
|
: 64;
|
|
// Keep the produced encoded bytes, then declare a decoded size that
|
|
// exceeds the decoder allowance. Writers emit one LZMA block for a whole
|
|
// bundle, so this budget must not erase the directory.
|
|
bytes.writeUInt32BE(64 * 1024 * 1024 + 1, tableOffset + 20);
|
|
const control = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
const [entry, ...rest] = await collectEntries(control);
|
|
expect(rest).toEqual([]);
|
|
if (entry === undefined)
|
|
throw new Error("expected the directory entry");
|
|
expect(entry.path).toBe("data");
|
|
await expect(control.open(entry)).rejects.toMatchObject({
|
|
reason: "unavailable",
|
|
message: expect.stringContaining("per-block decoded budget"),
|
|
limitation: expect.stringContaining("this release has no override"),
|
|
});
|
|
} finally {
|
|
await control.close();
|
|
}
|
|
|
|
// The encoded declaration now exceeds the whole carrier, so it cannot
|
|
// describe a block even though the same decoded limit still applies.
|
|
bytes.writeUInt32BE(bytes.length, tableOffset + 24);
|
|
const invalid = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(invalid)).rejects.toMatchObject({
|
|
reason: "malformed",
|
|
message: expect.stringContaining(
|
|
"declared data area exceeds the bundle extent",
|
|
),
|
|
});
|
|
} finally {
|
|
await invalid.close();
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("UnityFS per-block encoded budget", () => {
|
|
it("names the encoded bound when only the encoded size exceeds it", async () => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "abc" }], {
|
|
blocksInfoCompression: 0,
|
|
blockCompression: 2,
|
|
});
|
|
// One byte above the encoded allowance (64 MiB + 64 MiB / 255 + 16),
|
|
// with the decoded size untouched; a sparse carrier keeps it in range.
|
|
const encoded =
|
|
64 * 1024 * 1024 + Math.floor((64 * 1024 * 1024) / 255) + 17;
|
|
bytes.writeUInt32BE(encoded, 64 + 24);
|
|
const path = await fixture(bytes);
|
|
const length = bytes.length + encoded;
|
|
const file = Buffer.from(bytes);
|
|
file.writeBigUInt64BE(BigInt(length), 32);
|
|
await writeFile(path, file);
|
|
await truncate(path, length);
|
|
const reader = new UnityFsArtifactReader(path);
|
|
try {
|
|
const [entry] = await collectEntries(reader);
|
|
if (entry === undefined) throw new Error("expected the directory entry");
|
|
await expect(reader.open(entry)).rejects.toMatchObject({
|
|
reason: "unavailable",
|
|
message: expect.stringContaining(
|
|
`${String(encoded)} encoded bytes, above the ${String(encoded - 1)}-byte per-block encoded budget`,
|
|
),
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("UnityFS allocation and malformed-input boundaries", () => {
|
|
it("rejects an oversized directory extending past the physical file", async () => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "x" }]);
|
|
bytes.writeUInt32BE(17 * 1024 * 1024, 40);
|
|
const reader = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "malformed",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it.each(["encoded", "decoded"] as const)(
|
|
"admits the %s directory budget before reading or decoding it",
|
|
async (kind) => {
|
|
const bytes = buildUnityFs([{ path: "data", data: "x" }]);
|
|
bytes.writeUInt32BE(17 * 1024 * 1024, kind === "encoded" ? 40 : 44);
|
|
if (kind === "encoded")
|
|
bytes.writeBigUInt64BE(BigInt(17 * 1024 * 1024 + 64), 32);
|
|
const path = await fixture(bytes);
|
|
if (kind === "encoded") await truncate(path, 17 * 1024 * 1024 + 64);
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const reads = vi.spyOn(admitted.handle, "read");
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "limit",
|
|
boundary: "memory",
|
|
});
|
|
expect(reads).toHaveBeenCalledTimes(1); // bounded header only
|
|
} finally {
|
|
try {
|
|
await reader.close();
|
|
} finally {
|
|
reads.mockRestore();
|
|
await admitted.handle.close();
|
|
}
|
|
}
|
|
},
|
|
);
|
|
|
|
it("reserves block-row storage before constructing a large row array", async () => {
|
|
const bytes = buildUnityFs([], {
|
|
blocksInfoCompression: 0,
|
|
blockCompression: 0,
|
|
});
|
|
const tableSize = 20 + 300_000 * 10 + 4;
|
|
bytes.writeUInt32BE(tableSize, 40);
|
|
bytes.writeUInt32BE(tableSize, 44);
|
|
// Keep the padded data area start inside the carrier so only the row
|
|
// representation budget can reject this table.
|
|
const file = Buffer.alloc(64 + Math.ceil(tableSize / 16) * 16);
|
|
bytes.subarray(0, 64).copy(file);
|
|
file.writeBigUInt64BE(BigInt(file.length), 32);
|
|
file.writeUInt32BE(300_000, 64 + 16);
|
|
const reader = new UnityFsArtifactReader(await fixture(file));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "limit",
|
|
boundary: "memory",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("charges overlapping readable members, not only their unique block", async () => {
|
|
const size = 1024 * 1024;
|
|
const members = Array.from({ length: 257 }, (_, index) => ({
|
|
path: `alias-${String(index)}`,
|
|
offset: 0,
|
|
size,
|
|
data: index === 0 ? Buffer.alloc(size, 0x61) : Buffer.alloc(0),
|
|
}));
|
|
const control = new UnityFsArtifactReader(
|
|
await fixture(
|
|
buildUnityFs(members.slice(0, 256), {
|
|
blockSize: size,
|
|
encodeBlock: repeatedBlock,
|
|
}),
|
|
),
|
|
);
|
|
try {
|
|
expect(await collectEntries(control)).toHaveLength(256);
|
|
} finally {
|
|
await control.close();
|
|
}
|
|
const reader = new UnityFsArtifactReader(
|
|
await fixture(
|
|
buildUnityFs(members, {
|
|
blockSize: size,
|
|
encodeBlock: repeatedBlock,
|
|
}),
|
|
),
|
|
);
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "limit",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("types a short later node after an unterminated first node consumes its bytes", async () => {
|
|
const bytes = buildUnityFs(
|
|
[
|
|
{ path: "a".repeat(40), data: "" },
|
|
{ path: "b", data: "" },
|
|
],
|
|
{
|
|
blocksInfoCompression: 0,
|
|
blockCompression: 0,
|
|
},
|
|
);
|
|
// First path consumes most of the second row. The minimum total table-size
|
|
// check alone cannot establish each subsequent fixed row's bounds.
|
|
bytes.fill(0x61, 64 + 34 + 20, 64 + 34 + 20 + 41 + 18);
|
|
const reader = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "truncated",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("translates malformed directory LZ4 into the artifact error algebra", async () => {
|
|
const bytes = buildUnityFs([{ path: "x", data: "x" }]);
|
|
bytes[65] = 0xff;
|
|
const reader = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "malformed",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("refuses data blocks overlapping an end-positioned directory", async () => {
|
|
const bytes = buildUnityFs([{ path: "x", data: "abc" }], {
|
|
blocksInfoAtEnd: true,
|
|
blocksInfoCompression: 0,
|
|
blockCompression: 0,
|
|
});
|
|
const tableOffset = bytes.length - bytes.readUInt32BE(40);
|
|
bytes.writeUInt32BE(5, tableOffset + 20);
|
|
bytes.writeUInt32BE(5, tableOffset + 24);
|
|
const reader = new UnityFsArtifactReader(await fixture(bytes));
|
|
try {
|
|
await expect(collectEntries(reader)).rejects.toMatchObject({
|
|
reason: "malformed",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
it.each([1, 2])(
|
|
"does no I/O for an empty block with codec %s and preserves source counts",
|
|
async (codec) => {
|
|
const original = buildUnityFs([{ path: "x", data: "ab" }], {
|
|
blockSize: 1,
|
|
blockCompression: 0,
|
|
blocksInfoCompression: 0,
|
|
flags: 0x40,
|
|
});
|
|
const tableSize = original.readUInt32BE(40);
|
|
// Insert an empty block between two one-byte plain blocks, preserving
|
|
// the member's two-byte virtual extent and the directory's exact bounds.
|
|
const emptyBlock = Buffer.alloc(10);
|
|
emptyBlock.writeUInt32BE(1, 4);
|
|
emptyBlock.writeUInt16BE(codec, 8);
|
|
const bytes = Buffer.concat([
|
|
original.subarray(0, 64 + 30),
|
|
emptyBlock,
|
|
original.subarray(64 + 30, 64 + tableSize),
|
|
Buffer.from([0x61, 0, 0x62]),
|
|
]);
|
|
bytes.writeBigUInt64BE(BigInt(bytes.length), 32);
|
|
bytes.writeUInt32BE(tableSize + 10, 40);
|
|
bytes.writeUInt32BE(tableSize + 10, 44);
|
|
bytes.writeUInt32BE(3, 64 + 16);
|
|
const path = await fixture(bytes);
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
try {
|
|
const [entry] = await collectEntries(reader);
|
|
expect(reader.formatMetadata()?.block_count).toBe(3);
|
|
const reads = vi.spyOn(admitted.handle, "read");
|
|
try {
|
|
expect(await text(await reader.open(entry!))).toBe("ab");
|
|
expect(reads).toHaveBeenCalledTimes(2);
|
|
} finally {
|
|
reads.mockRestore();
|
|
}
|
|
} finally {
|
|
await reader.close();
|
|
await admitted.handle.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
describe("UnityFS stream ownership and immutable cache", () => {
|
|
it("joins an outstanding positional read before close completes", async () => {
|
|
const path = await fixture(buildUnityFs([{ path: "x", data: "bytes" }]));
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const reached = createDeferred<void>(),
|
|
release = createDeferred<void>();
|
|
const nativeRead = admitted.handle.read.bind(admitted.handle);
|
|
const [entry] = await collectEntries(reader);
|
|
const reads = vi.spyOn(admitted.handle, "read").mockImplementation((async (
|
|
...args: unknown[]
|
|
) => {
|
|
reached.resolve();
|
|
await release.promise;
|
|
return Reflect.apply(nativeRead, admitted.handle, args);
|
|
}) as typeof admitted.handle.read);
|
|
let consumed: Promise<Buffer> | undefined;
|
|
try {
|
|
const stream = await reader.open(entry!);
|
|
consumed = buffer(stream);
|
|
void consumed.catch(() => undefined);
|
|
await awaitAcknowledgement(reached.promise, consumed, "member read");
|
|
let closed = false;
|
|
const closing = reader.close().then(() => {
|
|
closed = true;
|
|
});
|
|
await setImmediate();
|
|
expect(closed).toBe(false);
|
|
release.resolve();
|
|
await closing;
|
|
expect(stream.closed).toBe(true);
|
|
} finally {
|
|
release.resolve();
|
|
try {
|
|
await reader.close();
|
|
} finally {
|
|
await consumed?.catch(() => undefined);
|
|
reads.mockRestore();
|
|
await admitted.handle.close();
|
|
}
|
|
}
|
|
});
|
|
|
|
it("preserves cancellation occurring inside the LZ4 decoder", async () => {
|
|
const data = Buffer.alloc(8 * 1024 * 1024, 0x61);
|
|
const path = await fixture(
|
|
buildUnityFs([{ path: "x", data }], {
|
|
blockSize: data.length,
|
|
encodeBlock: repeatedBlock,
|
|
}),
|
|
);
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const controller = new AbortController();
|
|
const reason = new Error("cancel during block decode");
|
|
const nativeRead = admitted.handle.read.bind(admitted.handle);
|
|
const [entry] = await collectEntries(reader);
|
|
const reads = vi.spyOn(admitted.handle, "read").mockImplementation((async (
|
|
...args: unknown[]
|
|
) => {
|
|
const result = await Reflect.apply(nativeRead, admitted.handle, args);
|
|
globalThis.setImmediate(() => {
|
|
controller.abort(reason);
|
|
});
|
|
return result;
|
|
}) as typeof admitted.handle.read);
|
|
try {
|
|
await expect(
|
|
buffer(await reader.open(entry!, controller.signal)),
|
|
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
|
|
} finally {
|
|
try {
|
|
await reader.close();
|
|
} finally {
|
|
reads.mockRestore();
|
|
await admitted.handle.close();
|
|
}
|
|
}
|
|
});
|
|
|
|
it("preserves cancellation occurring inside the LZMA decoder", async () => {
|
|
const data = Buffer.alloc(8 * 1024 * 1024, 0x61);
|
|
const path = await fixture(
|
|
buildUnityFs([{ path: "x", data }], {
|
|
blockSize: data.length,
|
|
blockCompression: 1,
|
|
}),
|
|
);
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const controller = new AbortController();
|
|
const reason = new Error("cancel during lzma block decode");
|
|
const nativeRead = admitted.handle.read.bind(admitted.handle);
|
|
const [entry] = await collectEntries(reader);
|
|
const reads = vi.spyOn(admitted.handle, "read").mockImplementation((async (
|
|
...args: unknown[]
|
|
) => {
|
|
const result = await Reflect.apply(nativeRead, admitted.handle, args);
|
|
globalThis.setImmediate(() => {
|
|
controller.abort(reason);
|
|
});
|
|
return result;
|
|
}) as typeof admitted.handle.read);
|
|
try {
|
|
await expect(
|
|
buffer(await reader.open(entry!, controller.signal)),
|
|
).rejects.toMatchObject({ reason: "cancelled", cause: reason });
|
|
} finally {
|
|
try {
|
|
await reader.close();
|
|
} finally {
|
|
reads.mockRestore();
|
|
await admitted.handle.close();
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("UnityFS stream capacity and cache ownership", () => {
|
|
it("bounds tiny-block I/O independently of decoded byte counts", async () => {
|
|
const size = 32;
|
|
const members = Array.from({ length: 129 }, (_, index) => ({
|
|
path: `alias-${String(index)}`,
|
|
offset: 0,
|
|
size,
|
|
data: index === 0 ? Buffer.alloc(size, 0x61) : Buffer.alloc(0),
|
|
}));
|
|
const reader = new UnityFsArtifactReader(
|
|
await fixture(buildUnityFs(members, { blockSize: 1 })),
|
|
);
|
|
try {
|
|
let completed = 0;
|
|
await expect(
|
|
(async () => {
|
|
for (const entry of await collectEntries(reader)) {
|
|
await buffer(await reader.open(entry));
|
|
completed += 1;
|
|
}
|
|
})(),
|
|
).rejects.toMatchObject({
|
|
reason: "limit",
|
|
boundary: "capacity",
|
|
});
|
|
expect(completed).toBe(128);
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("does not let modified output chunks corrupt cached or concurrent member reads", async () => {
|
|
const data = Buffer.alloc(1024 * 1024, 0x61);
|
|
const reader = new UnityFsArtifactReader(
|
|
await fixture(
|
|
buildUnityFs([{ path: "x", data }], { blockSize: data.length }),
|
|
),
|
|
);
|
|
try {
|
|
const [entry] = await collectEntries(reader);
|
|
const stream = await reader.open(entry!);
|
|
const iterator = stream[Symbol.asyncIterator]();
|
|
const first = await iterator.next();
|
|
if (first.done || !Buffer.isBuffer(first.value))
|
|
throw new Error("expected a chunk");
|
|
first.value.fill(0);
|
|
stream.destroy();
|
|
expect((await buffer(await reader.open(entry!))).equals(data)).toBe(true);
|
|
const controller = new AbortController();
|
|
const cancelled = await reader.open(entry!, controller.signal);
|
|
await cancelled[Symbol.asyncIterator]().next();
|
|
const peer = buffer(await reader.open(entry!));
|
|
controller.abort();
|
|
expect((await peer).equals(data)).toBe(true);
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
|
|
it("validates freshness before reusing a decoded block", async () => {
|
|
const bytes = buildUnityFs([{ path: "x", data: "before" }]);
|
|
const path = await fixture(bytes);
|
|
const reader = new UnityFsArtifactReader(path);
|
|
try {
|
|
const [entry] = await collectEntries(reader);
|
|
expect(await text(await reader.open(entry!))).toBe("before");
|
|
await writeFile(path, Buffer.concat([bytes, Buffer.from([0])]));
|
|
await expect(reader.open(entry!)).rejects.toMatchObject({
|
|
reason: "integrity",
|
|
});
|
|
} finally {
|
|
await reader.close();
|
|
}
|
|
});
|
|
});
|
|
|
|
artifactPreparationRecoveryCases({
|
|
image: () => buildUnityFs([{ path: "a", data: "x" }]),
|
|
createReader: (path, admitted) => new UnityFsArtifactReader(path, admitted),
|
|
});
|
|
|
|
boundedArchiveStreamCases(
|
|
buildUnityFs,
|
|
(path, admitted) => new UnityFsArtifactReader(path, admitted),
|
|
);
|