From a44ff73676918ba8783d1a5dd6ab48b7041f385e Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 21:41:40 +0800 Subject: [PATCH] fix(apple): bound bundle Info.plist reads before decoding (#12279) * fix(apple): bound bundle Info.plist reads before decoding * refactor(apple): report plist input limits through shared failures * fix(apple): retain bundle plist descriptors through target cleanup * test(apple): verify Hopper retries bundle plist cleanup * fix(apple): preserve typed cancellation through bundle plist cleanup * fix(apple): preserve plist read failure through late cancellation * fix(apple): preserve cancellation during plist close retry * docs(apple): document bundle plist admission policy --------- Co-authored-by: ShuaixinHuang <197200901+ShuaixinHuang@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- docs/guides/native/native-investigation.md | 4 + src/application/AppBundleExecutable.test.ts | 50 +++- src/application/AppBundleExecutable.ts | 217 +++++++++++++++--- src/application/BinaryTargetResolver.ts | 7 +- src/application/MacHopper.test.ts | 103 ++++++++- src/application/MacHopper.ts | 16 +- .../boundary/filesystem/binaryTarget.test.ts | 20 +- .../filesystem/binaryTargetCleanup.test.ts | 82 ++++++- .../binaryTargetAdmissionCancellation.test.ts | 75 +++++- 9 files changed, 512 insertions(+), 62 deletions(-) diff --git a/docs/guides/native/native-investigation.md b/docs/guides/native/native-investigation.md index 6cc958caf8..c2bf35dc48 100644 --- a/docs/guides/native/native-investigation.md +++ b/docs/guides/native/native-investigation.md @@ -984,6 +984,10 @@ complete observation. a source-owned AppKit XIB with `ibtool`. Storyboards require an installed iOS platform; unsupported archive forms remain explicit. XML plist archives accept UTF-8 and BOM-marked UTF-16 in either byte order. + Bundle executable resolution and Hopper's minimum-version check admit + `Info.plist` only when its opened descriptor is a regular file of at most + 64 MiB. A symlink at the selected path can resolve to that regular file. + The separate 16 MiB budget applies to the decoded representation. App bundle `Info.plist` executable resolution uses the same decoder as keyed archives and Interface Builder. The decoder consumes an initial BOM and rejects malformed byte sequences, unsupported encoding declarations, diff --git a/src/application/AppBundleExecutable.test.ts b/src/application/AppBundleExecutable.test.ts index d761323c69..1aa4074e1e 100644 --- a/src/application/AppBundleExecutable.test.ts +++ b/src/application/AppBundleExecutable.test.ts @@ -1,4 +1,4 @@ -import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, rm, truncate, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -61,6 +61,30 @@ it.each([ }, ); +it("reports an oversized Info.plist as an input refusal before decoding", async () => { + const root = await createTestTempDirectory("rea-app-plist-input-"); + const bundle = join(root, "Fixture.app"); + const plist = join(bundle, "Contents", "Info.plist"); + await mkdir(join(bundle, "Contents"), { recursive: true }); + await writeFile(plist, ""); + await truncate(plist, 64 * 1024 * 1024 + 1); + + expect(await resolveAppleBundleExecutable(bundle)).toMatchObject({ + ok: false, + error: { + path: plist, + reason: expect.stringContaining("67108864-byte input allowance"), + cause: { + name: "ParseFailureError", + kind: "limit", + failure: { + limit: { maximum: 64 * 1024 * 1024, required: 64 * 1024 * 1024 + 1 }, + }, + }, + }, + }); +}); + describe("app bundle Info.plist magic", () => { it("decodes an executable when an unrelated UID uses a three-byte width", async () => { const root = await createTestTempDirectory("rea-app-three-byte-uid-"); @@ -139,17 +163,19 @@ describe("app bundle program directory containment", () => { let childResolved = false; const result = await resolveAppleBundleExecutable(bundle, { - readFile: async () => Buffer.from(plist), - realpath: async (path) => { - if (path === bundle) return canonicalBundle; - if (path === programs) return outsidePrograms; - if (path === executable) { - childResolved = true; - throw Object.assign(new Error("missing executable"), { - code: "ENOENT", - }); - } - return path; + fileSystem: { + readFile: async () => Buffer.from(plist), + realpath: async (path) => { + if (path === bundle) return canonicalBundle; + if (path === programs) return outsidePrograms; + if (path === executable) { + childResolved = true; + throw Object.assign(new Error("missing executable"), { + code: "ENOENT", + }); + } + return path; + }, }, }); diff --git a/src/application/AppBundleExecutable.ts b/src/application/AppBundleExecutable.ts index c689cb7ddf..d292ba0fda 100644 --- a/src/application/AppBundleExecutable.ts +++ b/src/application/AppBundleExecutable.ts @@ -1,11 +1,18 @@ -import { lstat, opendir, readFile, realpath, stat } from "node:fs/promises"; +import { lstat, opendir, realpath, stat } from "node:fs/promises"; import { extname, join, sep } from "node:path"; import { z } from "zod"; +import { + AnalysisCancelledError, + cancelledBy, + carriedReason, +} from "../domain/analysisErrorCore.js"; +import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js"; import { isPlistDecodeBudgetFailure } from "../domain/apple/propertyListDecodeBudget.js"; import { decodeInfoPlistValue } from "../domain/apple/infoPlist.js"; import { BinaryTargetError } from "../domain/configurationErrors.js"; +import { decodeLimit, ParseFailureError } from "../domain/parseFailure.js"; import { isPathWithinRoot } from "../domain/localPath.js"; import type { BundleResourceRoot, @@ -17,6 +24,46 @@ import { } from "../domain/apple/appleBundleTypes.js"; import { err, ok, type Result } from "../domain/result.js"; import { absoluteCallerPath } from "../filesystem/callerPath.js"; +import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js"; +import type { ArtifactResourceScope } from "../resources/index.js"; +import { errorMessage } from "../kernel/errorMessage.js"; + +import { + bindRegularFileCleanup, + readRegularFile, + RegularFileReadFailure, + RetainedRegularFileCleanupFailure, + retryRegularFileCleanup, +} from "../process/RegularFileRead.js"; + +/** Match the native plist inspector's input allowance, independent of decoding. */ +const BUNDLE_INFO_PLIST_INPUT_BYTES = 64 * 1024 * 1024; + +const bundlePlistCancellation = (reason: unknown): AnalysisCancelledError => + cancelledBy("resolve_binary_target", carriedReason(reason)); + +export const readBundleInfoPlist = ( + path: string, + signal?: AbortSignal, +): Promise => + readRegularFile(path, { + symlinks: "follow", + ...(signal === undefined + ? {} + : { signal, cancellationFailure: bundlePlistCancellation }), + admit: ({ size }) => { + if (size > BUNDLE_INFO_PLIST_INPUT_BYTES) + throw decodeLimit( + "plist", + `Info.plist exceeds the ${String(BUNDLE_INFO_PLIST_INPUT_BYTES)}-byte input allowance: ${path} (${String(size)} bytes)`, + { + name: "bundle Info.plist input bytes", + maximum: BUNDLE_INFO_PLIST_INPUT_BYTES, + required: size, + }, + ); + }, + }); /** Where one app bundle layout keeps its Info.plist and program file. */ interface BundleLayout { @@ -81,7 +128,11 @@ interface AppBundleFileSystem { readonly realpath: (path: string) => Promise; } -const defaultFileSystem: AppBundleFileSystem = { readFile, realpath }; +interface AppBundleResolutionOptions { + readonly fileSystem?: AppBundleFileSystem; + readonly resources?: ArtifactResourceScope; + readonly signal?: AbortSignal | undefined; +} /** * Resolve an app bundle directory to its declared program file. macOS and @@ -91,12 +142,13 @@ const defaultFileSystem: AppBundleFileSystem = { readFile, realpath }; */ const resolveAppBundleExecutable = async ( path: string, - fileSystem: AppBundleFileSystem = defaultFileSystem, + fileSystem: AppBundleFileSystem, + options: AppBundleResolutionOptions, ): Promise> => { try { const layout = await presentLayout(path); if (layout !== undefined) - return await resolveLayoutExecutable(path, layout, fileSystem); + return await resolveLayoutExecutable(path, layout, fileSystem, options); const wrapped = await wrappedBundle(path); if (wrapped !== undefined) { const wrappedLayout = await presentLayout(wrapped); @@ -105,9 +157,11 @@ const resolveAppBundleExecutable = async ( wrapped, wrappedLayout, fileSystem, + options, ); } } catch (cause: unknown) { + if (cause instanceof AnalysisCancelledError) throw cause; if (cause instanceof BinaryTargetError) return err(cause); return err( new BinaryTargetError(path, errorReason(cause, path), { cause }), @@ -136,12 +190,17 @@ const resolveAppBundleExecutable = async ( */ export const resolveAppleBundleExecutable = async ( path: string, - fileSystem: AppBundleFileSystem = defaultFileSystem, + options: AppBundleResolutionOptions = {}, ): Promise> => { + const fileSystem = options.fileSystem ?? { + readFile: (plistPath: string) => + readBundleInfoPlist(plistPath, options.signal), + realpath, + }; if (extname(path).toLowerCase() === ".app") - return resolveAppBundleExecutable(path, fileSystem); + return resolveAppBundleExecutable(path, fileSystem, options); try { - const layout = await declaredBundleLayout(path, fileSystem); + const layout = await declaredBundleLayout(path, fileSystem.realpath); if (!layout.ok) return layout; if (layout.value === undefined) return err( @@ -156,8 +215,14 @@ export const resolveAppleBundleExecutable = async ( }, ), ); - return await resolveLayoutExecutable(path, layout.value, fileSystem); + return await resolveLayoutExecutable( + path, + layout.value, + fileSystem, + options, + ); } catch (cause: unknown) { + if (cause instanceof AnalysisCancelledError) throw cause; if (cause instanceof BinaryTargetError) return err(cause); return err( new BinaryTargetError(path, errorReason(cause, path), { cause }), @@ -182,7 +247,7 @@ const bundleLayouts = async ( */ const declaredBundleLayout = async ( path: string, - fileSystem: AppBundleFileSystem, + canonicalize: AppBundleFileSystem["realpath"], ): Promise> => { const layouts = await bundleLayouts(path); if (layouts === VERSIONED_FRAMEWORK_LAYOUTS) { @@ -220,10 +285,7 @@ const declaredBundleLayout = async ( ); const plistPath = join(path, ...layout.plist); if ( - !isPathWithinRoot( - await fileSystem.realpath(path), - await fileSystem.realpath(plistPath), - ) + !isPathWithinRoot(await canonicalize(path), await canonicalize(plistPath)) ) return err( new BinaryTargetError(path, "bundle Info.plist leaves the bundle", { @@ -258,10 +320,7 @@ export const findAppBundleResourceRoot = async ( extension !== ".app" && openableAppleBundleExtension(extension) !== undefined ) { - const declared = await declaredBundleLayout( - canonicalInput, - defaultFileSystem, - ); + const declared = await declaredBundleLayout(canonicalInput, realpath); if (!declared.ok) return declared; // An admitted bundle type without Info.plist is a native admission // failure, not an application directory for other routes. @@ -412,34 +471,124 @@ const wrappedBundle = async (bundle: string): Promise => { return app; }; +const plistReadFailure = ( + plistPath: string, + noun: string, + failure: unknown, + signal?: AbortSignal, +): BinaryTargetError => { + const cause = + failure instanceof RegularFileReadFailure + ? failure.operationCause + : failure; + const error = new BinaryTargetError( + plistPath, + cause instanceof ParseFailureError && cause.kind === "limit" + ? cause.message + : isPermissionDenied(cause) + ? `permission denied reading ${noun} Info.plist ${plistPath}` + : isAbsence(cause) + ? `${noun} Info.plist is missing: ${plistPath}` + : `could not read ${noun} Info.plist ${plistPath}${codeDescription(cause)}`, + { cause }, + ); + if (signal?.aborted === true) + analysisErrorWithCancellation( + error, + bundlePlistCancellation(signal.reason), + ); + return error; +}; + +const readLayoutPlist = async ( + path: string, + noun: string, + read: AppBundleFileSystem["readFile"], + { resources, signal }: AppBundleResolutionOptions, +): Promise> => { + try { + return ok(await read(path)); + } catch (cause: unknown) { + if (cause instanceof AnalysisCancelledError) throw cause; + if (!(cause instanceof RetainedRegularFileCleanupFailure)) + return err(plistReadFailure(path, noun, cause, signal)); + + // The target resolver already tracks this operation. Retry only the owned + // descriptor, since re-entering scope admission could wait on this read. + const failure = cause as RetainedRegularFileCleanupFailure; + const retry = + resources === undefined + ? undefined + : await retryRegularFileCleanup(failure, resources, signal); + const { outcome } = failure; + const cancellation = + regularFileCancellation(failure) ?? + (outcome.kind === "completed" && signal?.aborted === true + ? { reason: signal.reason } + : undefined); + if (retry !== undefined && retry.failure === undefined) { + if (cancellation !== undefined) + throw bundlePlistCancellation(cancellation.reason); + return outcome.kind === "completed" + ? ok(outcome.value) + : err( + plistReadFailure( + path, + noun, + failure.operationFailure ?? outcome.cause, + signal, + ), + ); + } + + const primary = + failure.operationFailure !== undefined + ? plistReadFailure(path, noun, failure.operationFailure, signal) + : cancellation !== undefined + ? bundlePlistCancellation(cancellation.reason) + : outcome.kind === "failed" + ? plistReadFailure(path, noun, outcome.cause, signal) + : undefined; + const retained = retry?.failure ?? failure; + const error = new BinaryTargetError( + path, + "The Info.plist file handle could not be closed", + { + cause: retained, + cleanupPrimary: primary, + cleanup: retry?.cleanup ?? { + reason: errorMessage(failure.cleanupCause), + resources: [failure.path], + }, + }, + ); + bindRegularFileCleanup(retained, error); + return err(error); + } +}; + const resolveLayoutExecutable = async ( bundle: string, layout: BundleLayout, fileSystem: AppBundleFileSystem, + options: AppBundleResolutionOptions, ): Promise> => { const plistPath = join(bundle, ...layout.plist); // Reasons for an app keep their established wording. const noun = extname(bundle).toLowerCase() === ".app" ? "app" : "bundle"; - let plist: Buffer; - try { - plist = await fileSystem.readFile(plistPath); - } catch (cause: unknown) { - return err( - new BinaryTargetError( - plistPath, - isPermissionDenied(cause) - ? `permission denied reading ${noun} Info.plist ${plistPath}` - : isAbsence(cause) - ? `${noun} Info.plist is missing: ${plistPath}` - : `could not read ${noun} Info.plist ${plistPath}${codeDescription(cause)}`, - { cause }, - ), - ); - } + const plist = await readLayoutPlist( + plistPath, + noun, + fileSystem.readFile, + options, + ); + if (!plist.ok) return plist; let name: string; try { - name = executableName(decodeInfoPlistValue(plist, ["CFBundleExecutable"])); + name = executableName( + decodeInfoPlistValue(plist.value, ["CFBundleExecutable"]), + ); } catch (cause: unknown) { if (isPlistDecodeBudgetFailure(cause)) return err( diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 67a2e0e427..f357906ff5 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -194,9 +194,9 @@ export const parseBinaryTarget = async ( const sourcePath = HOST_PLATFORM.platform === "win32" ? candidate : canonical; throwIfTargetResolutionCancelled(signal); - const resolved = await resolveAppBundle(canonical); - throwIfTargetResolutionCancelled(signal); + const resolved = await resolveAppBundle(canonical, options); if (!resolved.ok) return resolved; + throwIfTargetResolutionCancelled(signal); const { executable: path, infoPlist } = resolved.value; const bundle = infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist }; @@ -926,11 +926,12 @@ const sha256Handle = async ( const resolveAppBundle = async ( path: string, + options: Pick, ): Promise> => { const metadata = await stat(path); if (!metadata.isDirectory()) return ok({ executable: path }); if (openableAppleBundleExtension(extname(path)) !== undefined) - return resolveAppleBundleExecutable(path); + return resolveAppleBundleExecutable(path, options); // Another Apple bundle type, such as a driver or kernel extension, is not // an application directory and has no JavaScript route. if (isUnopenedAppleBundleExtension(extname(path))) diff --git a/src/application/MacHopper.test.ts b/src/application/MacHopper.test.ts index 3aef489dda..c7e9b91b00 100644 --- a/src/application/MacHopper.test.ts +++ b/src/application/MacHopper.test.ts @@ -1,8 +1,19 @@ import { createHash } from "node:crypto"; +import { + mkdir, + realpath, + symlink, + truncate, + writeFile, +} from "node:fs/promises"; +import { join } from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; +import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; import { err, ok } from "../domain/result.js"; +import { resolveAppleBundleExecutable } from "./AppBundleExecutable.js"; import { HOPPER_METADATA_TIMEOUT_MS, type HopperDownload, @@ -10,11 +21,101 @@ import { } from "./HopperDownload.js"; import { installMacHopper, + systemMacHopperInstallHost, type MacHopperBundleVerification, type MacHopperBundleInstallResult, type MacHopperInstallHost, } from "./MacHopper.js"; +it("bounds the system host's Hopper minimum-version plist read", async () => { + const root = await createTestTempDirectory("rea-hopper-plist-input-"); + const app = join(root, "Hopper.app"); + const plist = join(app, "Contents", "Info.plist"); + await mkdir(join(app, "Contents"), { recursive: true }); + await writeFile( + plist, + "LSMinimumSystemVersion13.0", + ); + const host = systemMacHopperInstallHost(root, {}, async () => "15.0"); + + await expect(host.minimumSystemVersion(app)).resolves.toBe("13.0"); + await truncate(plist, 64 * 1024 * 1024 + 1); + await expect(host.minimumSystemVersion(app)).rejects.toMatchObject({ + name: "ParseFailureError", + kind: "limit", + failure: { + limit: { maximum: 64 * 1024 * 1024, required: 64 * 1024 * 1024 + 1 }, + }, + message: expect.stringContaining("67108864-byte input allowance"), + }); +}); + +it.skipIf(process.platform === "win32")( + "keeps symlinked Info.plist selection in bundle resolution and the Hopper version check", + async () => { + const root = await createTestTempDirectory("rea-symlinked-info-plist-"); + const app = join(root, "Hopper.app"); + const contents = join(app, "Contents"); + const plist = join(contents, "Info.plist"); + const selected = join(root, "Selected.plist"); + const executable = join(contents, "MacOS", "Hopper"); + await mkdir(join(contents, "MacOS"), { recursive: true }); + await writeFile(executable, "inert fixture"); + await writeFile( + selected, + "CFBundleExecutableHopperLSMinimumSystemVersion13.0", + ); + await symlink(selected, plist); + const host = systemMacHopperInstallHost(root, {}, async () => "15.0"); + try { + await expect(resolveAppleBundleExecutable(app)).resolves.toEqual({ + ok: true, + value: { executable: await realpath(executable), infoPlist: plist }, + }); + await expect(host.minimumSystemVersion(app)).resolves.toBe("13.0"); + } finally { + await host.close(); + } + }, +); + +it("retains the system host's minimum-version plist descriptor until close can retry it", async () => { + const root = await createTestTempDirectory("rea-hopper-plist-cleanup-"); + const app = join(root, "Hopper.app"); + const plist = join(app, "Contents", "Info.plist"); + await mkdir(join(app, "Contents"), { recursive: true }); + await writeFile( + plist, + "LSMinimumSystemVersion13.0", + ); + const host = systemMacHopperInstallHost(root, {}, async () => "15.0"); + const closeHandle = OwnedFileHandle.prototype.close; + const attempts: OwnedFileHandle[] = []; + let denied = true; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + attempts.push(this); + if (denied) throw new Error("controlled Info.plist close denial"); + await closeHandle.call(this); + }); + try { + await expect(host.minimumSystemVersion(app)).rejects.toBeDefined(); + await expect(host.close?.()).resolves.toMatchObject({ resources: [plist] }); + expect(attempts).toHaveLength(2); + expect(attempts[0]).toBe(attempts[1]); + denied = false; + await expect(host.close?.()).resolves.toBeUndefined(); + expect(attempts[0]!.handle.fd).toBe(-1); + await expect(host.minimumSystemVersion(app)).resolves.toBe("13.0"); + } finally { + denied = false; + await host.close?.(); + await Promise.all(attempts.map((owner) => closeHandle.call(owner))); + close.mockRestore(); + } +}); + class FakeMacHopperHost implements MacHopperInstallHost { readonly archive = new TextEncoder().encode("hopper-dmg"); feedFailure: HopperDownloadFailure | undefined; diff --git a/src/application/MacHopper.ts b/src/application/MacHopper.ts index dfd6abd585..ca2e968ca4 100644 --- a/src/application/MacHopper.ts +++ b/src/application/MacHopper.ts @@ -4,7 +4,6 @@ import { mkdir, mkdtemp, readdir, - readFile, rename, rm, writeFile, @@ -36,6 +35,8 @@ import { macHopperReleaseMinimumSystemVersion, } from "./HopperReleaseFeed.js"; import type { HopperInstallFailureReason } from "./SetupInstallFailure.js"; +import { regularFileCleanupLeases } from "../process/RegularFileRead.js"; +import { readBundleInfoPlist } from "./AppBundleExecutable.js"; import { decodeInfoPlistValue } from "../domain/apple/infoPlist.js"; import { macosMajorVersion, @@ -520,8 +521,19 @@ export const systemMacHopperInstallHost = ( macosVersion, async minimumSystemVersion(appPath) { const plist = posix.join(appPath, "Contents", "Info.plist"); + let bytes: Buffer; + try { + bytes = await readBundleInfoPlist(plist); + } catch (cause: unknown) { + for (const lease of regularFileCleanupLeases(cause) ?? []) + pendingCleanup.set( + () => lease.release(), + lease.cleanupResources ?? [plist], + ); + throw cause; + } const declared = minimumSystemVersionSchema.safeParse( - decodeInfoPlistValue(await readFile(plist), ["LSMinimumSystemVersion"]), + decodeInfoPlistValue(bytes, ["LSMinimumSystemVersion"]), ); if (!declared.success) throw new TypeError( diff --git a/tests/boundary/filesystem/binaryTarget.test.ts b/tests/boundary/filesystem/binaryTarget.test.ts index 478b35a4e4..a0a0b0cba7 100644 --- a/tests/boundary/filesystem/binaryTarget.test.ts +++ b/tests/boundary/filesystem/binaryTarget.test.ts @@ -352,14 +352,16 @@ describe("binary target I/O: app plist permissions and decoding", () => { await writeFile(join(app, "Contents", "Info.plist"), "placeholder"); const denied = Object.assign(new Error("denied"), { code }); const fileSystem: NonNullable< - Parameters[1] + NonNullable< + Parameters[1] + >["fileSystem"] > = { readFile: async () => { throw denied; }, realpath, }; - const result = await resolveAppleBundleExecutable(app, fileSystem); + const result = await resolveAppleBundleExecutable(app, { fileSystem }); expect(result).toMatchObject({ ok: false, error: { @@ -379,10 +381,12 @@ describe("binary target I/O: app plist permissions and decoding", () => { await writeFile(join(app, "Contents", "Info.plist"), "placeholder"); const readError = Object.assign(new Error("I/O failure"), { code: "EIO" }); const result = await resolveAppleBundleExecutable(app, { - readFile: async () => { - throw readError; + fileSystem: { + readFile: async () => { + throw readError; + }, + realpath, }, - realpath, }); expect(result).toMatchObject({ ok: false, @@ -407,7 +411,9 @@ describe("binary target I/O: app plist permissions and decoding", () => { ); const denied = Object.assign(new Error("denied"), { code }); const fileSystem: NonNullable< - Parameters[1] + NonNullable< + Parameters[1] + >["fileSystem"] > = { readFile, realpath: async (path) => { @@ -415,7 +421,7 @@ describe("binary target I/O: app plist permissions and decoding", () => { return realpath(path); }, }; - const result = await resolveAppleBundleExecutable(app, fileSystem); + const result = await resolveAppleBundleExecutable(app, { fileSystem }); expect(result).toMatchObject({ ok: false, error: { diff --git a/tests/boundary/filesystem/binaryTargetCleanup.test.ts b/tests/boundary/filesystem/binaryTargetCleanup.test.ts index a113ddaaa2..1da453d209 100644 --- a/tests/boundary/filesystem/binaryTargetCleanup.test.ts +++ b/tests/boundary/filesystem/binaryTargetCleanup.test.ts @@ -1,5 +1,5 @@ import { createHash } from "node:crypto"; -import { writeFile } from "node:fs/promises"; +import { mkdir, realpath, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; @@ -142,6 +142,86 @@ it.each([true, false])( }, ); +it.each([ + { closeMode: "clean", cancelAt: 1 }, + { closeMode: "retry", cancelAt: 1 }, + { closeMode: "retry", cancelAt: 2 }, + { closeMode: "retained", cancelAt: 1 }, + { closeMode: "retained", cancelAt: 2 }, + { closeMode: "retained", cancelAt: null }, +])( + "preserves the Info.plist descriptor outcome (close=$closeMode, cancelAt=$cancelAt)", + async ({ closeMode, cancelAt }) => { + const root = await createTestTempDirectory("rea-bundle-plist-close-"); + const bundle = join(root, "Fixture.app"); + const contents = join(bundle, "Contents"); + const plist = join(contents, "Info.plist"); + const programs = join(contents, "MacOS"); + await mkdir(programs, { recursive: true }); + await writeFile( + plist, + "CFBundleExecutabletarget.hop", + ); + await writeFile(join(programs, "target.hop"), "database bytes"); + + const resources = new ArtifactResourceScope(); + const controller = new AbortController(); + const reason = { caller: "cancel during bundle metadata close" }; + const nativeClose = OwnedFileHandle.prototype.close; + const owners: OwnedFileHandle[] = []; + let exerciseClose = true; + const close = vi + .spyOn(OwnedFileHandle.prototype, "close") + .mockImplementation(async function (this: OwnedFileHandle) { + if (exerciseClose) { + owners.push(this); + if (owners.length === cancelAt) controller.abort(reason); + if ( + closeMode === "retained" || + (closeMode === "retry" && owners.length === 1) + ) + throw new Error("controlled Info.plist close denial"); + } + await nativeClose.call(this); + }); + try { + const result = await parseBinaryTarget(bundle, { + resources, + signal: controller.signal, + }); + if (result.ok) + throw new Error("Expected bundle metadata finalization failure"); + const retainedClose = closeMode === "retained"; + expect(result.error.cleanupIncomplete).toBe(retainedClose); + const selectedPlist = await realpath(plist); + expect(resources.cleanupResources).toEqual( + retainedClose ? [selectedPlist] : [], + ); + expect(owners).toHaveLength(closeMode === "clean" ? 1 : 2); + expect(owners.every((owner) => owner === owners[0])).toBe(true); + if (cancelAt !== null) { + const primary = result.error.cleanupPrimary ?? result.error; + expect(primary._tag).toBe("AnalysisCancelledError"); + expect(primary.cause).toBe(reason); + } + if (retainedClose) { + expect(result.error.cleanup?.resources).toEqual([selectedPlist]); + expect(owners[0]?.handle.fd).toBeGreaterThanOrEqual(0); + } + exerciseClose = false; + await resources.retryCleanup(); + expect(owners[0]?.handle.fd).toBe(-1); + expect(result.error.cleanupIncomplete).toBe(false); + expect((await parseBinaryTarget(bundle, { resources })).ok).toBe(true); + } finally { + exerciseClose = false; + await resources.close(); + await Promise.all(owners.map((owner) => owner.close())); + close.mockRestore(); + } + }, +); + it("retries target and provider owners independently through the same MCP connection", async () => { const directory = await createTestTempDirectory("rea-target-mcp-close-"); const first = join(directory, "first.hop"); diff --git a/tests/process-global/binaryTargetAdmissionCancellation.test.ts b/tests/process-global/binaryTargetAdmissionCancellation.test.ts index b595e8450f..e34ee70854 100644 --- a/tests/process-global/binaryTargetAdmissionCancellation.test.ts +++ b/tests/process-global/binaryTargetAdmissionCancellation.test.ts @@ -1,5 +1,5 @@ import type { FileHandle } from "node:fs/promises"; -import { readFile, writeFile } from "node:fs/promises"; +import { mkdir, readFile, realpath, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, expect, it, onTestFinished, vi } from "vitest"; @@ -11,11 +11,13 @@ const admission = vi.hoisted(() => ({ reason: undefined as unknown, statFailure: undefined as Error | undefined, closeFailure: undefined as Error | undefined, + readFailure: undefined as Error | undefined, + beforeClose: undefined as (() => void) | undefined, handles: [] as FileHandle[], afterStat: undefined as ((count: number) => Promise) | undefined, })); -// Only control when cancellation arrives; preserve real open/stat/close IO. +// Inject failures and cancellation timing only on the selected real descriptor. vi.mock("node:fs/promises", async (importOriginal) => { const fs = await importOriginal(); return { @@ -24,6 +26,8 @@ vi.mock("node:fs/promises", async (importOriginal) => { const handle = await fs.open(...args); if (args[0] !== admission.path) return handle; admission.handles.push(handle); + if (admission.readFailure !== undefined) + vi.spyOn(handle, "read").mockRejectedValue(admission.readFailure); const stat = handle.stat.bind(handle); const close = handle.close.bind(handle); handle.stat = (async (...options: Parameters) => { @@ -37,6 +41,7 @@ vi.mock("node:fs/promises", async (importOriginal) => { return metadata; }) as FileHandle["stat"]; handle.close = async () => { + admission.beforeClose?.(); if (admission.closeFailure !== undefined) { const failure = admission.closeFailure; admission.closeFailure = undefined; @@ -80,6 +85,7 @@ const fixture = async (abortAt: number, reason?: unknown) => { afterEach(async () => { admission.closeFailure = undefined; + admission.beforeClose = undefined; for (const handle of admission.handles) if (handle.fd >= 0) await handle.close(); Object.assign(admission, { @@ -89,6 +95,7 @@ afterEach(async () => { controller: undefined, reason: undefined, statFailure: undefined, + readFailure: undefined, afterStat: undefined, handles: [], }); @@ -216,6 +223,70 @@ it("retains the cleanup failure and its file owner when cancelled admission cann expect(result.error.cleanupIncomplete).toBe(false); }); +it.each([false, true])( + "keeps physical Info.plist read failure ahead of cancellation during its close (close fails: %s)", + async (closeFails) => { + const root = await realpath( + await createTestTempDirectory("rea-plist-read-failure-"), + ); + const bundle = join(root, "Fixture.app"); + const programs = join(bundle, "Contents", "MacOS"); + const path = join(bundle, "Contents", "Info.plist"); + await mkdir(programs, { recursive: true }); + await writeFile( + path, + "CFBundleExecutabletarget.hop", + ); + await writeFile(join(programs, "target.hop"), "database bytes"); + const resources = new ArtifactResourceScope(); + const controller = new AbortController(); + const reason = { caller: "cancel during plist close" }; + const physical = Object.assign(new Error("Info.plist disk read failed"), { + code: "EIO", + }); + const closeFailure = new Error("Info.plist close denied"); + admission.path = path; + admission.readFailure = physical; + let denied = closeFails; + admission.beforeClose = () => { + controller.abort(reason); + if (denied) throw closeFailure; + }; + try { + const result = await parseBinaryTarget(bundle, { + resources, + signal: controller.signal, + }); + if (result.ok) + throw new Error("Expected the physical bundle read failure"); + const primary = result.error.cleanupPrimary ?? result.error; + expect(primary).toMatchObject({ + _tag: "BinaryTargetError", + reason: expect.stringContaining("(EIO)"), + }); + expect(primary.cause).toBe(physical); + expect(primary.secondaryFailures).toHaveLength(1); + expect(primary.secondaryFailures[0]?.cause).toBe(reason); + expect( + projectAnalysisError(result.error).details?.secondary_failures, + ).toEqual([expect.objectContaining({ code: "cancelled" })]); + expect(result.error.cleanupIncomplete).toBe(closeFails); + expect(resources.cleanupResources).toEqual(closeFails ? [path] : []); + expect(admission.handles).toHaveLength(1); + if (closeFails) + expect(admission.handles[0]?.fd).toBeGreaterThanOrEqual(0); + denied = false; + await resources.retryCleanup(); + expect(admission.handles[0]?.fd).toBe(-1); + expect(result.error.cleanupIncomplete).toBe(false); + expect(primary.cause).toBe(physical); + } finally { + denied = false; + await resources.close(); + } + }, +); + it.each([ "stop before admission", Object.assign(new Error("caller-selected reason"), { code: "EIO" }),