fix(artifacts): bound expanded ASAR listing before allocation (#2724)

Squash merge of https://github.com/morluto/rea/pull/2724.

Co-authored-by: chAngE <172472630+chAng-L19@users.noreply.github.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
This commit is contained in:
chAngE
2026-10-13 23:47:18 +08:00
committed by GitHub
co-authored by chAngE morluto
parent 9240a4e9ac
commit f825c869d6
6 changed files with 348 additions and 78 deletions
@@ -0,0 +1,130 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { buffer } from "node:stream/consumers";
import { setImmediate } from "node:timers/promises";
import { expect, it } from "vitest";
import { AsarArtifactReader } from "../../../src/artifacts/AsarArtifactReader.js";
import { readAsarListing } from "../../../src/artifacts/AsarListing.js";
import {
asarHeaderBytes,
nestedAsarHeader,
} from "../../fixtures/asarHeader.js";
import { inventoryArtifact } from "../../fixtures/artifactInventory.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const archiveWith = async (bytes: Buffer) => {
const root = await createTestTempDirectory("rea-asar-listing-");
const path = join(root, "app.asar");
await writeFile(path, bytes);
return path;
};
it("interrupts expanded listing admission between traversal batches", async () => {
const controller = new AbortController();
const header = {
files: Object.fromEntries(
Array.from({ length: 4000 }, (_, index) => [
`f${index}`,
{ size: 0, offset: "0" },
]),
),
};
const listing = readAsarListing(header, controller.signal);
await setImmediate();
controller.abort();
await expect(listing).rejects.toMatchObject({ reason: "cancelled" });
});
it("rejects path expansion before publishing any inventory, preserving the input", async () => {
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
expect(bytes.length).toBeLessThan(150_000);
const path = await archiveWith(bytes);
await expect(inventoryArtifact(path)).rejects.toMatchObject({
reason: "limit",
message: "ASAR expanded listing exceeds its 64 MiB representation budget",
});
expect(await readFile(path)).toEqual(bytes);
});
it("reads deeply nested packed metadata without recursive listing or member lookup", async () => {
const path = await archiveWith(nestedAsarHeader(3500, "d", 1));
const reader = new AsarArtifactReader(path);
try {
let count = 0;
for await (const entry of reader.entries()) {
count++;
if (entry.kind === "file") {
expect(entry.path).toBe(`${"d/".repeat(3500)}f0`);
expect(await buffer(await reader.open(entry))).toEqual(Buffer.alloc(0));
}
}
expect(count).toBe(3501);
} finally {
await reader.close();
}
});
it.each(["..", ".", "", "a/../b", "a/b", "a\0b"])(
"rejects raw ASAR component %j before host normalization can alias another entry",
async (component) => {
const json = JSON.stringify({
files: { [component]: { size: 0, offset: "0" } },
});
await expect(
inventoryArtifact(await archiveWith(asarHeaderBytes(json))),
).rejects.toMatchObject({ reason: "path" });
},
);
it("orders raw names portably and retains prototype-named entries and links", async () => {
const path = await archiveWith(
asarHeaderBytes(
'{"files":{"a0":{"size":0,"offset":"0"},"__proto__":{"size":0,"offset":"0"},"a":{"files":{"b":{"link":"a0"}}},"😀":{"size":0,"offset":"0"},"\uE000":{"size":0,"offset":"0"}}}',
),
);
const reader = new AsarArtifactReader(path);
try {
const entries = [];
for await (const entry of reader.entries())
entries.push([entry.path, entry.kind]);
expect(entries).toEqual([
["__proto__", "file"],
["a", "directory"],
["a/b", "symlink"],
["a0", "file"],
["\uE000", "file"],
["😀", "file"],
]);
} finally {
await reader.close();
}
});
it("preserves POSIX literal backslashes and rejects Windows component separators", async () => {
const path = await archiveWith(
asarHeaderBytes(
JSON.stringify({ files: { "a\\b": { size: 0, offset: "0" } } }),
),
);
const reader = new AsarArtifactReader(path);
try {
const list = async () => {
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
return entries;
};
if (process.platform === "win32") {
await expect(list()).rejects.toMatchObject({ reason: "path" });
} else {
const entries = await list();
expect(entries).toHaveLength(1);
expect(entries[0]?.path).toBe("a\\b");
expect(await buffer(await reader.open(entries[0]!))).toEqual(
Buffer.alloc(0),
);
}
} finally {
await reader.close();
}
});
@@ -0,0 +1,60 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it } from "vitest";
import { ArtifactProvider } from "../../../src/artifacts/ArtifactProvider.js";
import { createServer } from "../../../src/server/createServer.js";
import { nestedAsarHeader } from "../../fixtures/asarHeader.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
it("reports expanded ASAR admission failure through MCP and permits a valid retry", async () => {
const root = await createTestTempDirectory("rea-asar-listing-mcp-");
const path = join(root, "app.asar");
const bytes = nestedAsarHeader(64, "d".repeat(256), 4000);
await writeFile(path, bytes);
const session = createTestBinarySession(new ArtifactProvider(process.env));
const server = createServer({ kind: "session", session });
const client = new Client({ name: "asar-listing-test", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
expect(
(await client.callTool({ name: "open_binary", arguments: { path } }))
.isError,
).not.toBe(true);
const result = await client.callTool({
name: "inspect_artifact",
arguments: {},
});
expect(result.isError).toBe(true);
expect(parseMcpToolError(result)).toMatchObject({
error: {
code: "truncated",
category: "truncated",
},
});
expect(result.structuredContent).toBeUndefined();
expect(await readFile(path)).toEqual(bytes);
const valid = join(root, "valid.asar");
await writeFile(valid, nestedAsarHeader(1, "lib", 1));
expect(
(
await client.callTool({
name: "open_binary",
arguments: { path: valid },
})
).isError,
).not.toBe(true);
expect(
(await client.callTool({ name: "inspect_artifact", arguments: {} }))
.isError,
).not.toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close(), session.close()]);
}
});
+27
View File
@@ -0,0 +1,27 @@
/** Serialize a header-only ASAR, including Chromium pickle alignment. */
export const asarHeaderBytes = (json: string): Buffer => {
const text = Buffer.from(json);
const headerSize = 8 + Math.ceil(text.length / 4) * 4;
const bytes = Buffer.alloc(8 + headerSize);
bytes.writeUInt32LE(4, 0);
bytes.writeUInt32LE(headerSize, 4);
bytes.writeUInt32LE(headerSize - 4, 8);
bytes.writeUInt32LE(text.length, 12);
text.copy(bytes, 16);
return bytes;
};
/** Nested metadata without a recursive fixture builder or real directories. */
export const nestedAsarHeader = (
depth: number,
name: string,
leaves: number,
): Buffer => {
let json = `{"files":{${Array.from(
{ length: leaves },
(_, index) => `"f${index}":{"size":0,"offset":"0"}`,
).join(",")}}}`;
for (let index = 0; index < depth; index++)
json = `{"files":{${JSON.stringify(name)}:${json}}}`;
return asarHeaderBytes(json);
};