Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(electron): retain fuse descriptor ownership through failed final close (#4668)

nosmile996b27d8f4e3be
diff --git a/src/electron/ElectronFuseProvider.ts b/src/electron/ElectronFuseProvider.ts
index af3a29bb6..f1a906dd7 100644
--- a/src/electron/ElectronFuseProvider.ts
+++ b/src/electron/ElectronFuseProvider.ts
@@ -18,6 +18,11 @@ import {
type InspectElectronFusesInput,
} from "../domain/electron/electronFuses.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
+import { ProviderCleanupError } from "../domain/providerCleanupError.js";
+import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
+import { createEvidence, type Evidence } from "../domain/evidence.js";
+import { jsonValueSchema } from "../domain/jsonValue.js";
+import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
import { err, ok, type Result } from "../domain/result.js";
import { ZodError } from "zod";
import { RegularFileChangedError } from "../filesystem/RegularFile.js";
@@ -31,6 +36,7 @@ import {
ElectronFuseFormatFailure,
ElectronFuseResourceFailure,
readElectronFuseImage,
+ type ElectronFuseImage,
} from "./ElectronFuseReader.js";
/** Bundled fuse-wire reader. It does not flip fuses or launch the application. */
@@ -88,12 +94,128 @@ export class ElectronFuseProvider implements ElectronFusePort {
}
}
+/**
+ * Completed fuse evidence kept when the final descriptor close cannot be
+ * confirmed. Marked explicitly partial: cleanup is still incomplete and the
+ * retained observation must not be mistaken for a finished report.
+ */
+const fuseImagePartialEvidence = (
+ path: string,
+ image: ElectronFuseImage,
+): Evidence =>
+ createEvidence(
+ { path, sha256: image.sha256, format: image.format },
+ ELECTRON_FUSE_PROVIDER_IDENTITY,
+ {
+ operation: OPERATION,
+ parameters: { path },
+ result: jsonValueSchema.parse({
+ artifact: {
+ sha256: image.sha256,
+ bytes: image.bytes,
+ format: image.format,
+ },
+ slices: image.slices,
+ }),
+ confidence: "observed",
+ limitations: [
+ "Partial observation: the file was read successfully, but the final descriptor close could not be confirmed, so cleanup remains incomplete.",
+ ],
+ },
+ );
+
+const cleanupErrorFor = (
+ cause: RegularFileCleanupFailure,
+): ProviderCleanupError =>
+ new ProviderCleanupError(
+ ELECTRON_FUSE_PROVIDER_IDENTITY.id,
+ [cause.path],
+ {
+ reason:
+ cause.cleanupCause instanceof Error
+ ? cause.cleanupCause.message
+ : String(cause.cleanupCause),
+ retention: cause.retention.kind,
+ },
+ { operation: OPERATION, cause },
+ );
+
+/**
+ * A rejected descriptor close keeps its exact owner and must never replace
+ * the read outcome or be classified as a read permission failure. Report the
+ * primary error with its own classification and incomplete cleanup as a
+ * separate, truthful error.
+ *
+ * In this provider the only producer of these failures is
+ * {@link readElectronFuseImage}, so a completed outcome always carries an
+ * {@link ElectronFuseImage}.
+ */
+const cleanupIncompleteFor = (
+ cause: RegularFileCleanupFailure<ElectronFuseImage>,
+ path: string,
+ signal?: AbortSignal,
+): AnalysisError => {
+ const cleanup = cleanupErrorFor(cause);
+ // Cancellation must not hide the failed cleanup: compose it as the primary
+ // outcome while keeping the incomplete-cleanup report and descriptor owner.
+ const cancellation = regularFileCancellation(cause);
+ if (cancellation !== undefined)
+ return analysisErrorWithCleanupFailure(
+ new AnalysisCancelledError(OPERATION, {
+ cause: cancellation.reason,
+ ...(cause.outcome.kind === "completed"
+ ? {
+ partialObservation: fuseImagePartialEvidence(
+ path,
+ cause.outcome.value,
+ ),
+ }
+ : {}),
+ }),
+ cleanup,
+ OPERATION,
+ );
+ if (cause.outcome.kind === "failed")
+ return analysisErrorWithCleanupFailure(
+ failureFor(
+ cause.outcome.cause,
+ path,
+ // A late abort during close must not replace an earlier read failure.
+ cause.outcome.cause === signal?.reason ? signal : undefined,
+ ),
+ cleanup,
+ OPERATION,
+ );
+ return analysisErrorWithCleanupFailure(
+ new ProviderAdapterError(ELECTRON_FUSE_PROVIDER_IDENTITY.id, OPERATION, {
+ cause,
+ partialObservation: fuseImagePartialEvidence(path, cause.outcome.value),
+ diagnostics: {
+ path,
+ reason:
+ "The file was read, but the descriptor close could not be confirmed, so only a partial observation is reported and cleanup stays incomplete.",
+ },
+ }),
+ cleanup,
+ OPERATION,
+ );
+};
+
const failureFor = (
cause: unknown,
path: string,
signal?: AbortSignal,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
+ // A failed cleanup keeps its owner and incomplete-cleanup report even when
+ // the caller cancelled: cancelling must not turn it into a bare
+ // cancellation that silently drops the still-live descriptor.
+ if (cause instanceof RegularFileCleanupFailure)
+ return cleanupIncompleteFor(
+ cause as RegularFileCleanupFailure<ElectronFuseImage>,
+ path,
+ signal,
+ );
const cancellation = regularFileCancellation(cause);
if (cancellation !== undefined)
return new AnalysisCancelledError(OPERATION, {
diff --git a/src/electron/ElectronFuseReader.ts b/src/electron/ElectronFuseReader.ts
index 4db52b9c7..dc135c78c 100644
--- a/src/electron/ElectronFuseReader.ts
+++ b/src/electron/ElectronFuseReader.ts
@@ -1,6 +1,6 @@
import type { ResolvedElectronFuseFile } from "./ElectronFusePath.js";
import { createHash } from "node:crypto";
-import { lstat } from "node:fs/promises";
+import { lstat, type FileHandle } from "node:fs/promises";
import {
hasMachoMagic,
@@ -15,10 +15,13 @@ import {
type ElectronFuseSlice,
} from "../domain/electron/electronFuses.js";
import {
- openRegularFile,
RegularFileChangedError,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
+import {
+ withOwnedRegularFile,
+ type OwnedRegularFileOptions,
+} from "../filesystem/OwnedRegularFile.js";
/** Admission and search bounds for one Electron executable. */
export const ELECTRON_FUSE_LIMITS = {
@@ -80,6 +83,7 @@ export const readElectronFuseImage = async (
readonly signal?: AbortSignal;
readonly chunkBytes?: number;
readonly selection?: ResolvedElectronFuseFile;
+ readonly retainFailedClose?: OwnedRegularFileOptions["retainFailedClose"];
},
): Promise<ElectronFuseImage> => {
const signal = options?.signal;
@@ -138,35 +142,42 @@ export const readElectronFuseImage = async (
throw new TypeError(
`chunkBytes must be an integer between 1 and ${ELECTRON_FUSE_LIMITS.chunkBytes}.`,
);
- const handle = await openRegularFile(path, { symlinks: "reject", signal });
- try {
- const opened = await handle.stat({ bigint: true });
- if (!sameRegularFileState(before, opened))
- throw new RegularFileChangedError(path);
- await assertPathNodes();
- const readAt = readerFor(handle, size, path, signal);
- const container = await identifyContainer(readAt, size, path);
- const scanned = await scanSlices(
- handle,
- path,
- size,
- container.slices,
- chunkBytes,
- signal,
- );
- const current = await recheckPath(path);
- if (!sameRegularFileState(before, current))
- throw new RegularFileChangedError(path);
- await assertPathNodes();
- return {
- sha256: scanned.sha256,
- bytes: size,
- format: container.format,
- slices: scanned.slices,
- };
- } finally {
- await handle.close();
- }
+ return withOwnedRegularFile(
+ path,
+ {
+ symlinks: "reject",
+ ...(signal === undefined ? {} : { signal }),
+ ...(options?.retainFailedClose === undefined
+ ? {}
+ : { retainFailedClose: options.retainFailedClose }),
+ },
+ async (owned) => {
+ const opened = await owned.stat({ bigint: true });
+ if (!sameRegularFileState(before, opened))
+ throw new RegularFileChangedError(path);
+ await assertPathNodes();
+ const readAt = readerFor(owned, size, path, signal);
+ const container = await identifyContainer(readAt, size, path);
+ const scanned = await scanSlices(
+ owned,
+ path,
+ size,
+ container.slices,
+ chunkBytes,
+ signal,
+ );
+ const current = await recheckPath(path);
+ if (!sameRegularFileState(before, current))
+ throw new RegularFileChangedError(path);
+ await assertPathNodes();
+ return {
+ sha256: scanned.sha256,
+ bytes: size,
+ format: container.format,
+ slices: scanned.slices,
+ };
+ },
+ );
};
/** Sentence describing the file and sentinel bounds enforced by this reader. */
@@ -175,7 +186,7 @@ export const electronFuseReadLimitation = (): string =>
const readerFor =
(
- handle: Awaited<ReturnType<typeof openRegularFile>>,
+ handle: FileHandle,
size: number,
path: string,
signal: AbortSignal | undefined,
@@ -271,7 +282,7 @@ const assertNonOverlappingSlices = (ranges: readonly SliceRange[]): void => {
};
const scanSlices = async (
- handle: Awaited<ReturnType<typeof openRegularFile>>,
+ handle: FileHandle,
path: string,
size: number,
ranges: readonly SliceRange[],
@@ -368,7 +379,7 @@ const absorbChunk = (
};
const parseWire = async (
- handle: Awaited<ReturnType<typeof openRegularFile>>,
+ handle: FileHandle,
path: string,
sentinelOffset: number,
sliceEnd: number,
@@ -421,7 +432,7 @@ const parseWire = async (
};
const readExact = async (
- handle: Awaited<ReturnType<typeof openRegularFile>>,
+ handle: FileHandle,
path: string,
offset: number,
length: number,
diff --git a/src/electron/ElectronFuseReaderCleanup.test.ts b/src/electron/ElectronFuseReaderCleanup.test.ts
new file mode 100644
index 000000000..6de350ff2
--- /dev/null
+++ b/src/electron/ElectronFuseReaderCleanup.test.ts
@@ -0,0 +1,303 @@
+import { fstatSync } from "node:fs";
+import type { FileHandle } from "node:fs/promises";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { AnalysisAccessDeniedError } from "../domain/analysisErrorCore.js";
+import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
+import { RegularFileCleanupFailure } from "../filesystem/OwnedRegularFile.js";
+import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
+import { elfFuseImage } from "../../tests/fixtures/electron/fuseImage.js";
+import { ElectronFuseProvider } from "./ElectronFuseProvider.js";
+import { readElectronFuseImage } from "./ElectronFuseReader.js";
+
+const { mockOpen } = vi.hoisted(() => ({ mockOpen: vi.fn() }));
+
+vi.mock("node:fs/promises", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs/promises")>();
+ return { ...actual, open: mockOpen };
+});
+
+const actualFs =
+ await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
+
+const openedHandles: FileHandle[] = [];
+const originalCloses = new Map<FileHandle, () => Promise<void>>();
+
+const passthroughOpen = (path: unknown, ...rest: unknown[]) =>
+ (actualFs.open as (...args: unknown[]) => Promise<FileHandle>)(path, ...rest);
+
+beforeEach(() => {
+ mockOpen.mockImplementation(passthroughOpen);
+});
+
+/**
+ * Route open() through the real filesystem but fault the returned handle for
+ * one target path: reads can be made to fail with a primary error while the
+ * final close rejects, mirroring issue #4658's controlled reproduction.
+ */
+const armFaults = (
+ target: string,
+ faults: {
+ readonly readFailure?: unknown;
+ readonly closeFailure: unknown;
+ readonly onClose?: () => void;
+ },
+) => {
+ mockOpen.mockImplementation(
+ async (path: unknown, ...rest: unknown[]): Promise<FileHandle> => {
+ const handle = await passthroughOpen(path, ...rest);
+ if (String(path) === target) {
+ originalCloses.set(handle, handle.close.bind(handle));
+ if (faults.readFailure !== undefined) {
+ const readFailure = faults.readFailure;
+ handle.read = (async () => {
+ throw readFailure;
+ }) as unknown as FileHandle["read"];
+ }
+ const closeFailure = faults.closeFailure;
+ handle.close = (async () => {
+ faults.onClose?.();
+ throw closeFailure;
+ }) as unknown as FileHandle["close"];
+ openedHandles.push(handle);
+ }
+ return handle;
+ },
+ );
+};
+
+afterEach(async () => {
+ mockOpen.mockReset();
+ for (const handle of openedHandles) {
+ try {
+ await originalCloses.get(handle)?.();
+ } catch {
+ // The handle is already closed or the faulted close left it unusable.
+ }
+ }
+ openedHandles.length = 0;
+ originalCloses.clear();
+});
+
+const writeElfImage = async (root: string, name: string): Promise<string> => {
+ const path = join(root, name);
+ const image = elfFuseImage([1, 1]);
+ await actualFs.writeFile(path, image.bytes);
+ return path;
+};
+
+/**
+ * Walk the error cause graph for the retained cleanup failure. The provider
+ * reports cleanup through nested AggregateError causes, so a direct `.cause`
+ * read cannot reach it.
+ */
+const findRegularFileCleanupFailure = (
+ error: unknown,
+): RegularFileCleanupFailure | undefined => {
+ const seen = new Set<unknown>();
+ const queue: unknown[] = [error];
+ while (queue.length > 0) {
+ const current = queue.shift();
+ if (current === null || typeof current !== "object" || seen.has(current))
+ continue;
+ seen.add(current);
+ if (current instanceof RegularFileCleanupFailure) return current;
+ const nested = current as { errors?: unknown[]; cause?: unknown };
+ if (Array.isArray(nested.errors)) queue.push(...nested.errors);
+ if (nested.cause !== undefined) queue.push(nested.cause);
+ }
+ return undefined;
+};
+
+describe("electron fuse final-close failures", () => {
+ it("keeps the primary read error when the final close rejects", async () => {
+ const root = await createTestTempDirectory("rea-fuse-close-fault-");
+ const path = await writeElfImage(root, "app.elf");
+ const readFailure = Object.assign(new Error("physical read failure"), {
+ code: "EIO",
+ });
+ const closeFailure = Object.assign(
+ new Error("close rejected; descriptor still live"),
+ { code: "EACCES" },
+ );
+ armFaults(path, { readFailure, closeFailure });
+
+ const failure = await readElectronFuseImage(path).catch(
+ (error: unknown) => error,
+ );
+
+ // The close rejection must not replace the primary read error.
+ expect(failure).toBeInstanceOf(RegularFileCleanupFailure);
+ if (!(failure instanceof RegularFileCleanupFailure))
+ throw new Error("Expected a RegularFileCleanupFailure");
+ expect(failure.outcome.kind).toBe("failed");
+ if (failure.outcome.kind !== "failed")
+ throw new Error("Expected the read outcome to be retained");
+ expect(failure.outcome.cause).toBe(readFailure);
+ expect(failure.cleanupCause).toBe(closeFailure);
+ // Ownership of the still-live descriptor is retained, not dropped.
+ expect(failure.owner.handle).toBe(openedHandles[0]);
+ expect(() => fstatSync(openedHandles[0]?.fd ?? -1)).not.toThrow();
+ });
+
+ it("reports incomplete cleanup instead of a read permission failure when only the close fails", async () => {
+ const root = await createTestTempDirectory("rea-fuse-cleanup-report-");
+ const path = await writeElfImage(root, "app.elf");
+ const closeFailure = Object.assign(
+ new Error("close rejected; descriptor still live"),
+ { code: "EACCES" },
+ );
+ armFaults(path, { closeFailure });
+
+ const result = await new ElectronFuseProvider().inspect({ path });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected an error result");
+ // A close failure with errno EACCES must not surface as a read denial.
+ expect(result.error).not.toBeInstanceOf(AnalysisAccessDeniedError);
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toContain(path);
+ });
+
+ it("reads normally when the final close succeeds", async () => {
+ const root = await createTestTempDirectory("rea-fuse-close-ok-");
+ const path = await writeElfImage(root, "app.elf");
+
+ const image = await readElectronFuseImage(path);
+
+ expect(image.format).toBe("elf");
+ expect(image.slices).toHaveLength(1);
+ });
+
+ it("reports the primary read diagnostic with incomplete cleanup when read and close both fail", async () => {
+ const root = await createTestTempDirectory("rea-fuse-combined-fault-");
+ const path = await writeElfImage(root, "app.elf");
+ const readFailure = Object.assign(new Error("physical read failure"), {
+ code: "EIO",
+ });
+ const closeFailure = Object.assign(
+ new Error("close rejected; descriptor still live"),
+ { code: "EACCES" },
+ );
+ armFaults(path, { readFailure, closeFailure });
+
+ const result = await new ElectronFuseProvider().inspect({ path });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected an error result");
+ // The close errno must not replace the original read classification.
+ expect(result.error).not.toBeInstanceOf(AnalysisAccessDeniedError);
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toContain(path);
+ expect(JSON.stringify(result.error.diagnostics)).toContain(
+ "physical read failure",
+ );
+ // Ownership of the still-live descriptor is retained in the cause chain.
+ const cleanupFailure = findRegularFileCleanupFailure(result.error);
+ expect(cleanupFailure?.owner.handle).toBe(openedHandles[0]);
+ });
+
+ it("keeps incomplete cleanup and the descriptor owner when cancellation races the faulted close", async () => {
+ const root = await createTestTempDirectory("rea-fuse-cancel-close-");
+ const path = await writeElfImage(root, "app.elf");
+ const controller = new AbortController();
+ const abortReason = new Error("test abort during final close");
+ const closeFailure = Object.assign(
+ new Error("close rejected; descriptor still live"),
+ { code: "EACCES" },
+ );
+ // Synchronize the abort with the finalization boundary itself: the abort
+ // fires inside the faulted close, so no fixed delay is involved.
+ armFaults(path, {
+ closeFailure,
+ onClose: () => controller.abort(abortReason),
+ });
+
+ const result = await new ElectronFuseProvider().inspect(
+ { path },
+ { signal: controller.signal },
+ );
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected an error result");
+ // Typed cancellation composed with the incomplete-cleanup report instead
+ // of a bare cancellation that would drop the descriptor owner.
+ const aggregate = result.error.cause as AggregateError | undefined;
+ expect(aggregate).toBeInstanceOf(AggregateError);
+ expect(aggregate?.errors[0]).toBeInstanceOf(AnalysisCancelledError);
+ expect((aggregate?.errors[0] as Error | undefined)?.cause).toBe(
+ abortReason,
+ );
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toContain(path);
+ const cleanupFailure = findRegularFileCleanupFailure(result.error);
+ expect(cleanupFailure?.owner.handle).toBe(openedHandles[0]);
+ expect(() => fstatSync(openedHandles[0]?.fd ?? -1)).not.toThrow();
+ });
+
+ it("retains the completed fuse evidence as a partial observation when only the close fails", async () => {
+ const root = await createTestTempDirectory("rea-fuse-partial-evidence-");
+ const path = await writeElfImage(root, "app.elf");
+ const closeFailure = Object.assign(
+ new Error("close rejected; descriptor still live"),
+ { code: "EACCES" },
+ );
+ armFaults(path, { closeFailure });
+
+ const result = await new ElectronFuseProvider().inspect({ path });
+
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected an error result");
+ expect(result.error.cleanupIncomplete).toBe(true);
+ // The successfully read fuse evidence survives as an explicitly partial
+ // observation instead of being discarded with the report.
+ const partial = result.error.partialObservation;
+ expect(partial).toBeDefined();
+ const serialized = JSON.stringify(partial);
+ expect(serialized).toContain("Partial observation");
+ expect(serialized).toContain("electron-fuses");
+ });
+});
+
+describe("electron fuse read failure precedence", () => {
+ it("preserves an earlier read failure when cancellation arrives during failed close", async () => {
+ const root = await createTestTempDirectory("rea-fuse-read-cancel-close-");
+ const path = await writeElfImage(root, "app.elf");
+ const controller = new AbortController();
+ const readFailure = Object.assign(
+ new Error("primary read failed before cancellation"),
+ {
+ code: "EIO",
+ },
+ );
+ const closeFailure = Object.assign(new Error("final close failed"), {
+ code: "EACCES",
+ });
+ armFaults(path, {
+ readFailure,
+ closeFailure,
+ onClose: () => controller.abort(new Error("late close cancellation")),
+ });
+
+ const result = await new ElectronFuseProvider().inspect(
+ { path },
+ { signal: controller.signal },
+ );
+ expect(result.ok).toBe(false);
+ if (result.ok) throw new Error("Expected an error result");
+ expect(result.error.cleanupIncomplete).toBe(true);
+ expect(result.error.cleanupResources).toContain(path);
+ expect(JSON.stringify(result.error.diagnostics)).toContain(
+ readFailure.message,
+ );
+ const aggregate = result.error.cause as AggregateError;
+ expect(aggregate).toBeInstanceOf(AggregateError);
+ expect(aggregate.errors[0]).not.toBeInstanceOf(AnalysisCancelledError);
+ const retained = findRegularFileCleanupFailure(result.error);
+ expect(retained?.outcome).toEqual({ kind: "failed", cause: readFailure });
+ expect(retained?.cleanupCause).toBe(closeFailure);
+ expect(retained?.owner.handle).toBe(openedHandles[0]);
+ expect(() => fstatSync(openedHandles[0]?.fd ?? -1)).not.toThrow();
+ });
+});