fix(artifacts)!: keep streamed reads within descriptor ownership

Use bounded positional reads for unpacked ASAR members and borrowed Mach-O slices so destroying a stream cannot bypass its descriptor owner. Retain uncertain ASAR closes and preserve borrowed sources after cancellation.

BREAKING CHANGE: Injected ASAR unpacked handles expose fd and read instead of createReadStream.
This commit is contained in:
morluto
2026-10-11 05:17:10 +08:00
parent be6272f261
commit e0e49e9dd5
4 changed files with 170 additions and 26 deletions
+20 -20
View File
@@ -30,6 +30,8 @@ import {
} from "./ArtifactReader.js";
import { closeAsarHandle, readValidatedAsarEntry } from "./AsarEntryStream.js";
import { admitAsarHeader } from "./AsarHeader.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
/**
* Official Electron ASAR adapter with range-streamed member reads.
@@ -43,10 +45,12 @@ export class AsarArtifactReader implements ArtifactReader {
#archiveSize: number | undefined;
#headerSize: number | undefined;
readonly #entries = new Map<string, AsarEntryState>();
readonly #unpackedHandles = new Map<UnpackedFileHandle, string>();
readonly #unpackedHandleClosePromises = new Map<
readonly #unpackedHandles = new Map<
UnpackedFileHandle,
Promise<void>
{
readonly path: string;
readonly owner: OwnedFileHandle<UnpackedFileHandle>;
}
>();
#snapshot: { readonly path: string; readonly sha256: string } | undefined;
#snapshotRoot: string | undefined;
@@ -299,7 +303,7 @@ export class AsarArtifactReader implements ArtifactReader {
async close(): Promise<void> {
let cleanupFailure: ArtifactReaderFailure | undefined;
for (const [handle, path] of this.#unpackedHandles) {
for (const [handle, { path }] of this.#unpackedHandles) {
try {
await this.#closeUnpackedHandle(handle);
} catch (cause: unknown) {
@@ -383,7 +387,10 @@ export class AsarArtifactReader implements ArtifactReader {
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
);
const openedHandle = handle;
this.#unpackedHandles.set(openedHandle, canonical);
this.#unpackedHandles.set(openedHandle, {
path: canonical,
owner: new OwnedFileHandle(openedHandle),
});
const openedMetadata = await openedHandle.stat();
if (
!openedMetadata.isFile() ||
@@ -403,9 +410,8 @@ export class AsarArtifactReader implements ArtifactReader {
);
}
abortIfNeeded(signal);
const source = openedHandle.createReadStream({
const source = readFileHandleChunks(openedHandle, {
start: 0,
autoClose: false,
});
source.once("close", () => {
void this.#closeUnpackedHandle(openedHandle).catch(() => undefined);
@@ -427,7 +433,7 @@ export class AsarArtifactReader implements ArtifactReader {
failure,
ArtifactReaderFailure.cleanupObservation(
cleanupCause,
this.#unpackedHandles.get(handle) ?? entry.path,
this.#unpackedHandles.get(handle)?.path ?? entry.path,
),
);
}
@@ -437,17 +443,10 @@ export class AsarArtifactReader implements ArtifactReader {
}
async #closeUnpackedHandle(handle: UnpackedFileHandle): Promise<void> {
if (!this.#unpackedHandles.has(handle)) return;
const pending = this.#unpackedHandleClosePromises.get(handle);
if (pending !== undefined) return pending;
const closing = Promise.resolve()
.then(() => handle.close())
.then(() => {
this.#unpackedHandles.delete(handle);
})
.finally(() => this.#unpackedHandleClosePromises.delete(handle));
this.#unpackedHandleClosePromises.set(handle, closing);
return closing;
const owned = this.#unpackedHandles.get(handle);
if (owned === undefined) return;
await owned.owner.close();
this.#unpackedHandles.delete(handle);
}
#resetArchiveState(): void {
@@ -462,9 +461,10 @@ type AsarEntryState = {
readonly entry: ArtifactEntry;
};
type UnpackedFileHandle = {
readonly fd: number;
stat(): Promise<Stats>;
close(): Promise<void>;
createReadStream: FileHandle["createReadStream"];
read: FileHandle["read"];
};
type OpenAsarUnpackedFile = (
path: string,
@@ -0,0 +1,84 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { CPU, fatImage, machoImage } from "./apple/MachoImage.fixture.js";
import { MachOSliceArtifactReader } from "./MachOSliceArtifactReader.js";
import { ok } from "../domain/result.js";
import { openRegularFile } from "../filesystem/RegularFile.js";
import type { NativeCommandRunner } from "../native/CommandRunner.js";
describe("MachOSliceArtifactReader", () => {
it("keeps a borrowed source usable after a cancelled slice read", async () => {
const root = await createTestTempDirectory("rea-slices-cancelled-");
const binary = join(root, "fat");
const x86 = machoImage({ cpu: CPU.x86_64 });
const arm = Buffer.concat([
Buffer.from(machoImage({ cpu: CPU.arm64 })),
Buffer.alloc(160_000, 0x5a),
]);
await writeFile(
binary,
fatImage([
{ cpu: CPU.x86_64, bytes: x86 },
{ cpu: CPU.arm64, bytes: arm },
]),
);
const handle = await openRegularFile(binary, { symlinks: "reject" });
const source = { handle, initial: await handle.stat() };
const runner: NativeCommandRunner = {
run: () =>
Promise.resolve(
ok({
tool: "lipo",
executable: "/usr/bin/lipo",
executableSha256: "1".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", binary],
stdout: `architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 4096\n size ${String(x86.length)}\n align 2^12 (4096)\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8192\n size ${String(arm.length)}\n align 2^12 (4096)\n`,
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
exitCode: 0,
signal: null,
}),
),
};
const reader = new MachOSliceArtifactReader(binary, {}, runner, source);
onTestFinished(async () => {
await reader.close();
await handle.close();
});
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
const armEntry = entries.find((entry) => entry.path === "slices/arm64");
if (armEntry === undefined) throw new Error("Expected an arm64 slice");
const controller = new AbortController();
const cancelledRead = await reader.open(armEntry, controller.signal);
const iterator = cancelledRead[Symbol.asyncIterator]();
const firstChunk = await iterator.next();
expect(firstChunk.value).toHaveLength(64 * 1024);
controller.abort();
await expect(iterator.next()).rejects.toMatchObject({
reason: "cancelled",
});
const verifiedEntries = [];
for await (const entry of reader.entries()) verifiedEntries.push(entry);
const verifiedArmEntry = verifiedEntries.find(
(entry) => entry.path === "slices/arm64",
);
if (verifiedArmEntry === undefined)
throw new Error("Expected arm64 after re-verifying the borrowed source");
const verifiedChunks: Buffer[] = [];
const verifiedRead = await reader.open(verifiedArmEntry);
for await (const chunk of verifiedRead)
verifiedChunks.push(Buffer.from(chunk));
expect(Buffer.concat(verifiedChunks)).toEqual(arm);
});
});
+2 -2
View File
@@ -26,6 +26,7 @@ import {
sameRegularFileState,
type StableRegularFileDescriptor,
} from "../filesystem/RegularFile.js";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
export class MachOSliceArtifactReader implements ArtifactReader {
@@ -207,10 +208,9 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"integrity",
`Mach-O slice range is outside the artifact: ${entry.path}`,
);
const sourceStream = source.handle.createReadStream({
const sourceStream = readFileHandleChunks(source.handle, {
start: offset,
end: offset + size - 1,
autoClose: false,
...(signal === undefined ? {} : { signal }),
});
const verifySource = () => this.#verifySource(source);
@@ -343,6 +343,9 @@ describe("ASAR read failures", () => {
const handle = await openFile(path, flags);
expect(await matchingDescriptorCount(identity)).toBeGreaterThan(0);
return {
get fd() {
return handle.fd;
},
async stat() {
throw ioError;
},
@@ -351,7 +354,7 @@ describe("ASAR read failures", () => {
if (closeCount === 1) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
read: handle.read.bind(handle),
};
});
@@ -381,6 +384,54 @@ describe("ASAR read failures", () => {
);
});
it.skipIf(process.platform === "win32")(
"never treats an invalidated unpacked handle as proof of cleanup recovery",
async () => {
const { archive, unpackedPath, identity } = await createUnpackedFixture();
const statFailure = Object.assign(new Error("unpacked metadata failed"), {
code: "EIO",
errno: -5,
syscall: "fstat",
});
const closeFailure = new Error("native close outcome unavailable");
let closeCount = 0;
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
throw statFailure;
},
async close() {
closeCount += 1;
// Model Node's invalidated-descriptor rejection without leaking a
// native descriptor in the test process.
await handle.close();
throw closeFailure;
},
read: handle.read.bind(handle),
};
});
const entry = await unpackedMember(reader);
await expect(reader.open(entry)).rejects.toMatchObject({
reason: "io",
message: expect.stringContaining("unpacked metadata failed"),
cleanup: {
resources: [unpackedPath],
reason: "native close outcome unavailable",
},
});
for (let attempt = 0; attempt < 2; attempt += 1)
await expect(reader.close()).rejects.toMatchObject({
cleanup: { resources: [unpackedPath] },
});
expect(closeCount).toBe(1);
await waitForNoMatchingDescriptor(identity);
},
);
it.skipIf(process.platform === "win32")(
"retries cleanup when cancellation arrives immediately after unpacked stat",
async () => {
@@ -390,6 +441,9 @@ it.skipIf(process.platform === "win32")(
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
controller.abort();
@@ -400,7 +454,7 @@ it.skipIf(process.platform === "win32")(
if (closeCount === 1) throw new Error("first close failed");
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
read: handle.read.bind(handle),
};
});
@@ -432,6 +486,9 @@ it.skipIf(process.platform === "win32")(
const reader = new AsarArtifactReader(archive, async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
const observed = await handle.stat();
return Object.assign(Object.create(observed), {
@@ -443,7 +500,7 @@ it.skipIf(process.platform === "win32")(
if (closeCount === 1) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
read: handle.read.bind(handle),
};
});
@@ -481,6 +538,9 @@ it.skipIf(process.platform === "win32")(
async (path, flags) => {
const handle = await openFile(path, flags);
return {
get fd() {
return handle.fd;
},
async stat() {
throw Object.assign(new Error("device stat failed"), {
code: "EIO",
@@ -493,7 +553,7 @@ it.skipIf(process.platform === "win32")(
if (closeCount < 3) throw closeError;
await handle.close();
},
createReadStream: (options) => handle.createReadStream(options),
read: handle.read.bind(handle),
};
},
async (path) => {