mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 19:41:20 -05:00
569 lines
20 KiB
TypeScript
569 lines
20 KiB
TypeScript
import { collectEntries } from "../../tests/fixtures/artifactEntries.js";
|
|
import {
|
|
artifactPreparationRecoveryCases,
|
|
artifactSourcePreparationBoundaryCases,
|
|
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";
|
|
|
|
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),
|
|
]);
|
|
};
|
|
|
|
artifactSourcePreparationBoundaryCases({
|
|
label: "UnityFs",
|
|
image: () => buildUnityFs([{ path: "a", data: "x" }]),
|
|
createReader: (path, admitted) => new UnityFsArtifactReader(path, admitted),
|
|
});
|
|
|
|
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.each([
|
|
{
|
|
decoder: "LZ4",
|
|
encoding: { encodeBlock: repeatedBlock },
|
|
cancelMessage: "cancel during block decode",
|
|
},
|
|
{
|
|
decoder: "LZMA",
|
|
encoding: { blockCompression: 1 as const },
|
|
cancelMessage: "cancel during lzma block decode",
|
|
},
|
|
])(
|
|
"preserves cancellation occurring inside the $decoder decoder",
|
|
async ({ encoding, cancelMessage }) => {
|
|
const data = Buffer.alloc(8 * 1024 * 1024, 0x61);
|
|
const path = await fixture(
|
|
buildUnityFs([{ path: "x", data }], {
|
|
blockSize: data.length,
|
|
...encoding,
|
|
}),
|
|
);
|
|
const admitted = await openRegularFile(path, { symlinks: "reject" });
|
|
const reader = new UnityFsArtifactReader(path, admitted);
|
|
const controller = new AbortController();
|
|
const reason = new Error(cancelMessage);
|
|
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),
|
|
);
|