From a27794c246b3f11d7f92ae7f6d276718190ab731 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:22:25 +0800 Subject: [PATCH] fix(artifacts): retain DMG ownership through uncertain attachment --- src/artifacts/NativeDmgArtifactReader.ts | 292 +++++-- src/artifacts/NativeDmgOwnership.ts | 192 +++++ .../native/nativeDmgArtifactReader.test.ts | 769 +++++++++++++++--- 3 files changed, 1065 insertions(+), 188 deletions(-) create mode 100644 src/artifacts/NativeDmgOwnership.ts diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts index c087f987f..9ff38905b 100644 --- a/src/artifacts/NativeDmgArtifactReader.ts +++ b/src/artifacts/NativeDmgArtifactReader.ts @@ -3,9 +3,6 @@ import { tmpdir } from "node:os"; import { basename, join } from "node:path"; import type { Readable } from "node:stream"; -import { parse } from "plist"; -import { z } from "zod"; - import type { ArtifactCommand } from "../domain/artifactGraph.js"; import { ArtifactReaderFailure, @@ -13,32 +10,22 @@ import { type ArtifactReader, } from "./ArtifactReader.js"; import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js"; -import { execFileOutput } from "../process/ExecFileOutput.js"; -const DETACH_TIMEOUT_MS = 120_000; -/** - * Waits before rechecking devices whose detach failed. A related device's - * later detach can eject one, `hdiutil info` can still list an ejected device - * briefly, and a volume can report busy just after it was read. - */ +import { + execFileOutput, + execFileOutputFailure, +} from "../process/ExecFileOutput.js"; +import { + parseNativeDmgAttachOutput, + parseNativeDmgInfo, + resolveNativeDmgOwnership, + type NativeDmgAttachOutput, + type NativeDmgInfo, +} from "./NativeDmgOwnership.js"; +const HDIUTIL_COMMAND_TIMEOUT_MS = 120_000; +// APFS ejects and busy reporting can lag a detach attempt. const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const; const delay = (milliseconds: number): Promise => new Promise((resolve) => setTimeout(resolve, milliseconds)); -const attachOutputSchema = z.object({ - "system-entities": z.array( - z.object({ - "dev-entry": z.string().startsWith("/dev/"), - "mount-point": z.string().optional(), - }), - ), -}); -const infoOutputSchema = z.object({ - images: z.array( - z.object({ - "system-entities": z.array(z.object({ "dev-entry": z.string() })), - }), - ), -}); - /** Narrow host seam for tested, shell-free hdiutil lifecycle operations. */ export interface NativeDmgHost { run( @@ -55,6 +42,27 @@ export interface NativeDmgHost { delay?(milliseconds: number): Promise; } +class NativeDmgCommandFailure extends ArtifactReaderFailure { + readonly processNotStarted: boolean; + + constructor( + reason: ArtifactReaderFailure["reason"], + message: string, + readonly stdout: string, + options?: { + readonly cause?: unknown; + readonly processNotStarted?: boolean; + }, + ) { + super( + reason, + message, + options?.cause === undefined ? undefined : { cause: options.cause }, + ); + this.processNotStarted = options?.processNotStarted ?? false; + } +} + const createSystemHost = ( environment: Readonly, ): NativeDmgHost => ({ @@ -66,26 +74,35 @@ const createSystemHost = ( [...arguments_], { env: environment, + stopSignal: "SIGTERM", ...(options === undefined ? {} : { timeout: options.timeoutMs }), ...(signal === undefined ? {} : { signal }), }, ); return { stdout, stderr, exitCode: 0 }; } catch (cause: unknown) { + const output = execFileOutputFailure(cause); if (cause instanceof Error && cause.name === "AbortError") - throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled"); - const exitCode = processExitCode(cause); + throw new NativeDmgCommandFailure( + "cancelled", + "DMG operation cancelled", + output?.stdout ?? "", + { cause }, + ); + const exitCode = + typeof output?.code === "number" ? output.code : processExitCode(cause); if (exitCode !== undefined) return { - stdout: processOutput(cause, "stdout"), - stderr: processOutput(cause, "stderr"), + stdout: output?.stdout ?? processOutput(cause, "stdout"), + stderr: output?.stderr ?? processOutput(cause, "stderr"), exitCode, cause, }; - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( commandFailureReason(cause, arguments_[0]), `hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure(cause, arguments_)}`, - { cause }, + output?.stdout ?? "", + { cause, processNotStarted: processNotStarted(cause) }, ); } }, @@ -97,7 +114,13 @@ export class NativeDmgArtifactReader implements ArtifactReader { readonly #provenance: ArtifactCommand[] = []; #directory: DirectoryArtifactReader | undefined; #devices: string[] = []; + #inventoryConfirmedDevices = new Set(); #mountRoot: string | undefined; + #baselineDevices = new Set(); + #attachOutput: NativeDmgAttachOutput | undefined; + #attachOutputReturned = false; + #attachMayHaveMounted = false; + #ownershipUncertainty: string | undefined; private constructor( private readonly path: string, @@ -145,7 +168,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { } async close(): Promise { - let detachFailure: unknown; + let detachFailure = await this.#reconcileAttachState(); let remainingDevices: string[] = []; for (const device of [...this.#devices].reverse()) { const failure = await this.#detach(device); @@ -154,10 +177,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { detachFailure ??= failure; } } - // Detaching a synthesized APFS container also ejects the image that backs - // it, so a device whose own detach failed may be gone by the end of the - // pass, and hdiutil can list an ejected device or report busy briefly. - // Only a device that stays attached through every recheck is a failure. + // APFS container detach may briefly leave its backing image listed. for (const delayMs of DETACH_SETTLE_DELAYS_MS) { if (remainingDevices.length === 0) break; await (this.host.delay ?? delay)(delayMs); @@ -174,7 +194,11 @@ export class NativeDmgArtifactReader implements ArtifactReader { } if (remainingDevices.length === 0) detachFailure = undefined; this.#devices = remainingDevices.reverse(); - if (this.#devices.length === 0 && this.#mountRoot !== undefined) + if ( + this.#devices.length === 0 && + this.#mountRoot !== undefined && + !this.#attachMayHaveMounted + ) await rm(this.#mountRoot, { recursive: true, force: true }).then( () => { this.#mountRoot = undefined; @@ -184,6 +208,12 @@ export class NativeDmgArtifactReader implements ArtifactReader { detachFailure ??= cause; }, ); + if (this.#attachMayHaveMounted) { + detachFailure ??= new Error( + this.#ownershipUncertainty ?? + "hdiutil attachment ownership remains unknown", + ); + } if (detachFailure !== undefined) throw new ArtifactReaderFailure( "unavailable", @@ -194,6 +224,11 @@ export class NativeDmgArtifactReader implements ArtifactReader { reason: failureMessage(detachFailure), resources: [ ...this.#devices.map((device) => `DMG device ${device}`), + ...(this.#attachMayHaveMounted + ? [ + `DMG attachment ownership unknown at mount root ${this.#mountRoot ?? this.path}`, + ] + : []), ...(this.#mountRoot === undefined ? [] : [`DMG mount root ${this.#mountRoot}`]), @@ -207,7 +242,7 @@ export class NativeDmgArtifactReader implements ArtifactReader { async #detach(device: string): Promise { try { await runChecked(this.host, ["detach", device], undefined, { - timeoutMs: DETACH_TIMEOUT_MS, + timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS, }); this.#provenance.push(command(["detach", device], ["mount"])); return undefined; @@ -216,22 +251,31 @@ export class NativeDmgArtifactReader implements ArtifactReader { } } - /** - * Report whether hdiutil still lists a device; unknown state counts as - * attached. Like detach, this cleanup query runs after the inventory - * snapshot has captured provenance, so it is not recorded there. - */ + async #reconcileAttachState(): Promise { + if (!this.#attachMayHaveMounted) return undefined; + try { + await this.#resolveAttachOwnership(); + return undefined; + } catch (cause: unknown) { + this.#ownershipUncertainty = failureMessage(cause); + return cause; + } + } + + /** Treat unknown hdiutil state as attached during cleanup. */ async #isAttached(device: string): Promise { try { - const info = await runChecked(this.host, ["info", "-plist"], undefined, { - timeoutMs: DETACH_TIMEOUT_MS, - }); - const parsed = infoOutputSchema.parse(parse(info.stdout)); - return parsed.images.some((image) => + const parsed = await this.#readInfo(); + const isListed = parsed.images.some((image) => image["system-entities"].some( (entity) => entity["dev-entry"] === device, ), ); + if (isListed) { + this.#inventoryConfirmedDevices.add(device); + return true; + } + return !this.#inventoryConfirmedDevices.has(device); } catch { return true; } @@ -240,8 +284,16 @@ export class NativeDmgArtifactReader implements ArtifactReader { async attach(signal?: AbortSignal): Promise { await runChecked(this.host, ["verify", this.path], signal); this.#provenance.push(command(["verify", this.path], ["read"])); - this.#mountRoot = await realpath(await mkdtemp(join(tmpdir(), "rea-dmg-"))); + const baseline = await this.#readInfo(); + this.#baselineDevices = new Set( + baseline.images.flatMap((image) => + image["system-entities"].map(({ "dev-entry": device }) => device), + ), + ); + const mountRoot = await realpath(await mkdtemp(join(tmpdir(), "rea-dmg-"))); + this.#mountRoot = mountRoot; try { + this.#attachMayHaveMounted = true; const attached = await runChecked( this.host, [ @@ -250,42 +302,37 @@ export class NativeDmgArtifactReader implements ArtifactReader { "-nobrowse", "-plist", "-mountroot", - this.#mountRoot, + mountRoot, this.path, ], signal, + { timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS }, ); - const parsed = attachOutputSchema.parse(parse(attached.stdout)); - const devices = [ - ...new Set( - parsed["system-entities"].map((entity) => entity["dev-entry"]), - ), - ]; - // Detaching an observed whole disk also detaches its partitions. Do not - // subsequently detach the now-unavailable child devices. - this.#devices = devices.filter( - (device) => - !devices.some( - (parent) => - /^\/dev\/disk\d+$/u.test(parent) && - device.startsWith(`${parent}s`) && - /^\d+$/u.test(device.slice(parent.length + 1)), - ), - ); - if (this.#devices.length === 0) + this.#attachOutputReturned = true; + let parsed: NativeDmgAttachOutput; + try { + parsed = parseNativeDmgAttachOutput(attached.stdout); + } catch (cause: unknown) { + throw new ArtifactReaderFailure( + "format", + "hdiutil returned a malformed attachment plist", + { cause }, + ); + } + if (parsed["system-entities"].length === 0) throw new ArtifactReaderFailure( "format", "hdiutil returned no attached devices", ); - for (const entity of parsed["system-entities"]) - if ( - entity["mount-point"] !== undefined && - !entity["mount-point"].startsWith(`${this.#mountRoot}/`) - ) - throw new ArtifactReaderFailure( - "path", - "hdiutil mounted outside the owned root", - ); + this.#attachOutput = parsed; + const ownership = await this.#resolveAttachOwnership(); + if (ownership !== "owned") + throw new ArtifactReaderFailure( + ownership === "unknown" ? "unavailable" : "path", + ownership === "unknown" + ? `DMG attachment ownership is uncertain: ${this.#ownershipUncertainty ?? "no unique mount under the owned root"}` + : "hdiutil did not mount a new image beneath the owned root", + ); this.#provenance.push( command( [ @@ -294,14 +341,26 @@ export class NativeDmgArtifactReader implements ArtifactReader { "-nobrowse", "-plist", "-mountroot", - this.#mountRoot, + mountRoot, this.path, ], ["read", "mount"], ), ); - this.#directory = new DirectoryArtifactReader(this.#mountRoot); + this.#directory = new DirectoryArtifactReader(mountRoot); } catch (cause: unknown) { + if (cause instanceof NativeDmgCommandFailure && cause.stdout !== "") { + try { + this.#attachOutput = parseNativeDmgAttachOutput(cause.stdout); + this.#attachOutputReturned = true; + } catch { + // The original command failure remains primary; fresh info still recovers mounts. + } + } + if (cause instanceof NativeDmgCommandFailure && cause.processNotStarted) { + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + } let cleanupFailure: unknown; try { await this.close(); @@ -319,11 +378,64 @@ export class NativeDmgArtifactReader implements ArtifactReader { throw cause; } } + + async #readInfo(): Promise { + const info = await runChecked(this.host, ["info", "-plist"], undefined, { + timeoutMs: HDIUTIL_COMMAND_TIMEOUT_MS, + }); + return parseNativeDmgInfo(info.stdout); + } + + async #resolveAttachOwnership(): Promise<"owned" | "none" | "unknown"> { + const mountRoot = this.#mountRoot; + if (mountRoot === undefined) + throw new Error("DMG mount root is unavailable for ownership discovery"); + const ownership = resolveNativeDmgOwnership({ + info: await this.#readInfo(), + ...(this.#attachOutput === undefined + ? {} + : { attachOutput: this.#attachOutput }), + attachOutputReturned: this.#attachOutputReturned, + mountRoot, + baselineDevices: this.#baselineDevices, + }); + if (ownership.status === "owned") { + this.#devices = [...ownership.devices]; + if (ownership.source === "info") + for (const device of ownership.devices) + this.#inventoryConfirmedDevices.add(device); + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + return "owned"; + } + if (ownership.status === "unknown") { + this.#ownershipUncertainty = ownership.reason; + return "unknown"; + } + this.#attachMayHaveMounted = false; + this.#ownershipUncertainty = undefined; + this.#devices = []; + return "none"; + } } const failureMessage = (cause: unknown): string => cause instanceof Error ? cause.message : String(cause); +const processNotStarted = (cause: unknown): boolean => { + if (!(cause instanceof Error)) return false; + const syscall = Reflect.get(cause, "syscall"); + const code = Reflect.get(cause, "code"); + const errno = Reflect.get(cause, "errno"); + return ( + typeof syscall === "string" && + syscall.startsWith("spawn ") && + (typeof code === "string" || + typeof code === "number" || + typeof errno === "number") + ); +}; + const runChecked = async ( host: NativeDmgHost, arguments_: readonly string[], @@ -336,16 +448,21 @@ const runChecked = async ( } catch (cause: unknown) { if (cause instanceof ArtifactReaderFailure) throw cause; if (cause instanceof Error && cause.name === "AbortError") - throw new ArtifactReaderFailure("cancelled", "DMG operation cancelled", { - cause, - }); - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( + "cancelled", + "DMG operation cancelled", + execFileOutputFailure(cause)?.stdout ?? "", + { cause }, + ); + const output = execFileOutputFailure(cause); + throw new NativeDmgCommandFailure( commandFailureReason(cause, arguments_[0]), `hdiutil ${arguments_[0] ?? "operation"} failed: ${describeCommandFailure( cause, arguments_, )}`, - { cause }, + output?.stdout ?? "", + { cause, processNotStarted: processNotStarted(cause) }, ); } if (result.exitCode !== 0) { @@ -362,12 +479,13 @@ const runChecked = async ( const details = describeCommandFailure(failure, arguments_); const unknownVerifyFailure = arguments_[0] === "verify" && reason === "unavailable"; - throw new ArtifactReaderFailure( + throw new NativeDmgCommandFailure( reason, unknownVerifyFailure ? `hdiutil verify failed; captured diagnostics do not establish the failure cause: ${details}` : `hdiutil ${arguments_[0] ?? "operation"} failed: ${details}`, - result.cause === undefined ? undefined : { cause: result.cause }, + result.stdout, + { cause: result.cause ?? failure }, ); } return { stdout: result.stdout, exitCode: 0 }; diff --git a/src/artifacts/NativeDmgOwnership.ts b/src/artifacts/NativeDmgOwnership.ts new file mode 100644 index 000000000..ac9bf7cff --- /dev/null +++ b/src/artifacts/NativeDmgOwnership.ts @@ -0,0 +1,192 @@ +import { relative, resolve, sep } from "node:path"; + +import { parse } from "plist"; +import { z } from "zod"; + +const systemEntitySchema = z.object({ + "dev-entry": z.string().startsWith("/dev/"), + "mount-point": z.string().optional(), +}); + +const attachOutputSchema = z.object({ + "system-entities": z.array(systemEntitySchema), +}); + +const infoOutputSchema = z.object({ + images: z.array( + z.object({ + "system-entities": z.array(systemEntitySchema), + }), + ), +}); + +/** Parsed hdiutil image inventory used to reconcile owned mount groups. */ +export type NativeDmgInfo = z.output; +/** Parsed hdiutil attach response used to detect unresolved new devices. */ +export type NativeDmgAttachOutput = z.output; + +/** Parse hdiutil's current image inventory. */ +export const parseNativeDmgInfo = (stdout: string): NativeDmgInfo => + infoOutputSchema.parse(parse(stdout)); + +/** Parse hdiutil's attach response while preserving device and mount facts. */ +export const parseNativeDmgAttachOutput = ( + stdout: string, +): NativeDmgAttachOutput => attachOutputSchema.parse(parse(stdout)); + +/** Ownership result for one fresh hdiutil inventory. */ +export type NativeDmgOwnership = + | { + readonly status: "owned"; + readonly devices: readonly string[]; + readonly source: "info" | "attach"; + } + | { readonly status: "none" } + | { readonly status: "unknown"; readonly reason: string }; + +/** Classify only fresh image groups tied to the exclusively owned mount root. */ +export const resolveNativeDmgOwnership = (input: { + readonly info: NativeDmgInfo; + readonly attachOutput?: NativeDmgAttachOutput; + readonly attachOutputReturned: boolean; + readonly mountRoot: string; + readonly baselineDevices: ReadonlySet; +}): NativeDmgOwnership => { + const rootedImages = input.info.images.filter((image) => + image["system-entities"].some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && isBelowRoot(input.mountRoot, mountPoint), + ), + ); + if (rootedImages.length > 1) + return { + status: "unknown", + reason: + "multiple hdiutil image groups report mounts beneath the owned root", + }; + const rootedImage = rootedImages[0]; + if (rootedImage !== undefined) { + const hasOutsideMount = rootedImage["system-entities"].some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && !isBelowRoot(input.mountRoot, mountPoint), + ); + const groupDevices = rootedImage["system-entities"].map( + ({ "dev-entry": device }) => device, + ); + const devices = topLevelDevices(groupDevices); + const overlapsBaseline = groupDevices.some((device) => + input.baselineDevices.has(device), + ); + if (hasOutsideMount || overlapsBaseline || devices.length === 0) + return { + status: "unknown", + reason: hasOutsideMount + ? "the image group contains a mount outside the owned root" + : overlapsBaseline + ? "the image group includes a device present before attachment" + : "the owned mount group contains no detachable device", + }; + return { status: "owned", devices, source: "info" }; + } + + if (input.attachOutputReturned) { + const attachOwnership = ownershipFromAttachOutput( + input.attachOutput, + input.mountRoot, + input.baselineDevices, + ); + if (attachOwnership.status === "owned") { + return attachOwnership; + } + if (attachOwnership.status === "unknown") return attachOwnership; + } + + const newlyListedDevice = input.info.images.some((image) => + image["system-entities"].some( + ({ "dev-entry": device }) => !input.baselineDevices.has(device), + ), + ); + if (newlyListedDevice) + return { + status: "unknown", + reason: + "hdiutil lists devices absent from the pre-attach baseline, but none is tied uniquely to the owned root; ownership is unknown", + }; + return { status: "none" }; +}; + +const ownershipFromAttachOutput = ( + output: NativeDmgAttachOutput | undefined, + mountRoot: string, + baselineDevices: ReadonlySet, +): NativeDmgOwnership => { + if (output === undefined) + return { + status: "unknown", + reason: "hdiutil attach succeeded but its ownership facts were malformed", + }; + const entities = output["system-entities"]; + const hasRootMount = entities.some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && isBelowRoot(mountRoot, mountPoint), + ); + const hasOutsideMount = entities.some( + ({ "mount-point": mountPoint }) => + mountPoint !== undefined && !isBelowRoot(mountRoot, mountPoint), + ); + const devices = entities.map(({ "dev-entry": device }) => device); + const uniqueDevices = topLevelDevices(devices); + const overlapsBaseline = devices.some((device) => + baselineDevices.has(device), + ); + + if (hasRootMount) { + if (hasOutsideMount || overlapsBaseline || uniqueDevices.length === 0) + return { + status: "unknown", + reason: hasOutsideMount + ? "the attach result includes a mount outside the owned root" + : overlapsBaseline + ? "the attach result includes a device present before attachment" + : "the attach result's owned mount has no detachable device", + }; + return { status: "owned", devices: uniqueDevices, source: "attach" }; + } + + if (devices.length === 0) + return { + status: "unknown", + reason: + "hdiutil attach succeeded without reporting device ownership facts", + }; + if (devices.some((device) => !baselineDevices.has(device))) + return { + status: "unknown", + reason: + "the attach result reports new devices without a mount beneath the owned root", + }; + return { status: "none" }; +}; + +const topLevelDevices = (devices: readonly string[]): string[] => { + const unique = [...new Set(devices)]; + return unique.filter( + (device) => + !unique.some( + (parent) => + /^\/dev\/disk\d+$/u.test(parent) && + device.startsWith(`${parent}s`) && + /^\d+$/u.test(device.slice(parent.length + 1)), + ), + ); +}; + +const isBelowRoot = (root: string, path: string): boolean => { + const child = relative(root, resolve(path)); + return ( + child !== "" && + child !== "." && + child !== ".." && + !child.startsWith(`..${sep}`) + ); +}; diff --git a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts index beb17922e..276db13e1 100644 --- a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts +++ b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts @@ -19,25 +19,141 @@ import { type NativeDmgHost, } from "../../../../src/artifacts/NativeDmgArtifactReader.js"; +const infoPlist = ( + imagePath: string, + entities: { "dev-entry": string; "mount-point"?: string }[], +): string => + build({ + images: [{ "image-path": imagePath, "system-entities": entities }], + }); + +const emptyInfoPlist = build({ images: [] }); + +const attachPlist = ( + entities: { "dev-entry": string; "mount-point"?: string }[], +): string => build({ "system-entities": entities }); + +const createMountFixture = () => { + let root: string | undefined; + onTestFinished(async () => { + if (root !== undefined) await rm(root, { recursive: true, force: true }); + }); + const rememberRoot = (arguments_: readonly string[]): string => { + root = arguments_[arguments_.indexOf("-mountroot") + 1]; + if (root === undefined) throw new Error("missing mount root"); + return root; + }; + return { + root: () => root, + rememberRoot, + async createVolume( + arguments_: readonly string[], + contents?: string, + ): Promise<{ readonly mountRoot: string; readonly mountPoint: string }> { + const mountRoot = rememberRoot(arguments_); + const mountPoint = join(mountRoot, "Fixture"); + await mkdir(mountPoint); + if (contents !== undefined) + await writeFile(join(mountPoint, "hello.txt"), contents); + return { mountRoot, mountPoint }; + }, + }; +}; + +const createOmittedInventoryHost = () => { + const mount = createMountFixture(); + const state: { + calls: string[][]; + mountRoot: string | undefined; + mountPoint: string | undefined; + inventoryMode: "omitted" | "listed"; + attached: boolean; + detachAttempts: number; + } = { + calls: [], + mountRoot: undefined, + mountPoint: undefined, + inventoryMode: "omitted", + attached: false, + detachAttempts: 0, + }; + const host: NativeDmgHost = { + async run(arguments_) { + state.calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + state.attached && + state.inventoryMode === "listed" && + state.mountPoint !== undefined + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk24", + "mount-point": state.mountPoint, + }, + ]) + : emptyInfoPlist, + exitCode: 0, + }; + if (arguments_[0] === "detach") { + state.detachAttempts += 1; + if (state.detachAttempts < 5) + return { stdout: "", stderr: "device busy", exitCode: 1 }; + state.attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + const mounted = await mount.createVolume(arguments_, "owned mount"); + state.mountRoot = mounted.mountRoot; + state.mountPoint = mounted.mountPoint; + state.attached = true; + return { + stdout: attachPlist([ + { "dev-entry": "/dev/disk24", "mount-point": state.mountPoint }, + ]), + exitCode: 0, + }; + }, + delay: () => Promise.resolve(), + }; + return { host, state }; +}; + describe("native DMG artifact reader", () => { it("uses plist attachment metadata and detaches returned devices", async () => { const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; const host: NativeDmgHost = { async run(arguments_) { const args = [...arguments_]; calls.push(args); + if (args[0] === "info") + return { + stdout: attached + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk-fixture", + ...(mountPoint === undefined + ? {} + : { "mount-point": mountPoint }), + }, + ]) + : emptyInfoPlist, + exitCode: 0, + }; + if (args[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } if (args[0] !== "attach") return { stdout: "", exitCode: 0 }; - const mountRoot = args[args.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - const mountPoint = join(mountRoot, "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "hello"); + ({ mountPoint } = await mount.createVolume(args, "hello")); + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk-fixture", "mount-point": mountPoint }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk-fixture", "mount-point": mountPoint }, + ]), exitCode: 0, }; }, @@ -61,7 +177,7 @@ describe("native DMG artifact reader", () => { expect(calls).toContainEqual(["detach", "/dev/disk-fixture"]); }); - it("rejects non-zero results and surfaces detach failure during attach cleanup", async () => { + it("rejects non-zero verification results", async () => { await expect( NativeDmgArtifactReader.create("/tmp/image.dmg", process.env, undefined, { run: () => @@ -77,39 +193,29 @@ describe("native DMG artifact reader", () => { /"arguments":\["verify","\/tmp\/image\.dmg"\].*"exitCode":1.*"stderr":"hdiutil: verify failed - image not recognized"/u, ), }); + }); - let mountRoot: string | undefined; - onTestFinished(async () => { - if (mountRoot !== undefined) - await rm(mountRoot, { recursive: true, force: true }); - }); + it("retains the root and reports unknown ownership when recovery discovery fails", async () => { + const mount = createMountFixture(); const host: NativeDmgHost = { - delay: () => Promise.resolve(), run(arguments_) { - if (arguments_[0] === "detach") - return Promise.reject(new Error("detach failed")); - if (arguments_[0] === "info") + if (arguments_[0] === "info") { + if (mount.root() === undefined) + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); return Promise.resolve({ - stdout: build({ - images: [ - { "system-entities": [{ "dev-entry": "/dev/disk-fixture" }] }, - ], - }), - exitCode: 0, + stdout: "unavailable info plist", + stderr: "hdiutil info failed", + exitCode: 1, }); + } if (arguments_[0] !== "attach") return Promise.resolve({ stdout: "", exitCode: 0 }); - mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); + mount.rememberRoot(arguments_); return Promise.resolve({ - stdout: build({ - "system-entities": [ - { - "dev-entry": "/dev/disk-fixture", - "mount-point": "/tmp/not-owned", - }, - ], - }), + stdout: build({ unexpected: true }), exitCode: 0, }); }, @@ -122,23 +228,459 @@ describe("native DMG artifact reader", () => { host, ), ).rejects.toMatchObject({ + reason: "format", cleanup: { resources: expect.arrayContaining([ - "DMG device /dev/disk-fixture", + expect.stringMatching( + /^DMG attachment ownership unknown at mount root /u, + ), expect.stringMatching(/^DMG mount root /u), ]), }, }); + expect(mount.root()).toBeDefined(); + expect(await realpath(mount.root() ?? "")).toBe(mount.root()); + }); +}); + +describe("DMG attach recovery", () => { + it("keeps attach-output ownership when the first inventory omits the mount", async () => { + const { host, state } = createOmittedInventoryHost(); + const reader = await NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ); + await expect(reader.close()).rejects.toMatchObject({ + reason: "unavailable", + cleanup: { + resources: expect.arrayContaining([ + "DMG device /dev/disk24", + expect.stringMatching(/^DMG mount root /u), + ]), + }, + }); + expect(state.detachAttempts).toBe(4); + expect(await realpath(state.mountRoot ?? "")).toBe(state.mountRoot); + + state.inventoryMode = "listed"; + await reader.close(); + expect(state.detachAttempts).toBe(5); + expect( + await realpath(state.mountRoot ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG rooted ownership isolation", () => { + it("detaches its rooted group while leaving a concurrent foreign image alone", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + let mountPoint: string | undefined; + let ownedAttached = false; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !ownedAttached || mountPoint === undefined + ? emptyInfoPlist + : build({ + images: [ + { + "image-path": "/tmp/image.dmg", + "system-entities": [ + { + "dev-entry": "/dev/disk26", + "mount-point": mountPoint, + }, + ], + }, + { + "image-path": "/tmp/foreign.dmg", + "system-entities": [ + { + "dev-entry": "/dev/disk99", + "mount-point": "/Volumes/Foreign", + }, + ], + }, + ], + }), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + if (arguments_[1] === "/dev/disk26") ownedAttached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + ({ mountPoint } = await mount.createVolume(arguments_)); + ownedAttached = true; + return { + stdout: attachPlist([ + { "dev-entry": "/dev/disk26", "mount-point": mountPoint }, + ]), + exitCode: 0, + }; + }, + }; + + const reader = await NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ); + await reader.close(); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([ + ["detach", "/dev/disk26"], + ]); + expect(ownedAttached).toBe(false); + expect(calls).not.toContainEqual(["detach", "/dev/disk99"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG failed attach output recovery", () => { + it("uses captured attach stdout to recover a failed command's rooted device", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); + if (arguments_[0] === "attach") { + const mountRoot = mount.rememberRoot(arguments_); + return Promise.resolve({ + stdout: attachPlist([ + { + "dev-entry": "/dev/disk25", + "mount-point": join(mountRoot, "Fixture"), + }, + ]), + stderr: "attach interrupted after mounting", + exitCode: 1, + }); + } + return Promise.resolve({ stdout: "", exitCode: 0 }); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toThrow(/hdiutil attach failed/u); + expect(calls).toContainEqual(["detach", "/dev/disk25"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("DMG attach fallback recovery", () => { + it("recovers a mounted image after the attach plist is malformed", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { "dev-entry": "/dev/disk20" }, + { + "dev-entry": "/dev/disk20s1", + "mount-point": mountPoint, + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + ({ mountPoint } = await mount.createVolume( + arguments_, + "recovered mount", + )); + attached = true; + return { stdout: "{invalid plist", exitCode: 0 }; + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toThrow(); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + "detach", + ]); + expect(calls).toContainEqual(["detach", "/dev/disk20"]); + expect( + await realpath(mount.root() ?? "").catch(() => undefined), + ).toBeUndefined(); + }); + + it("keeps unmounted new devices ambiguous without detaching them", async () => { + const calls: string[][] = []; + const mount = createMountFixture(); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: + mount.root() === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [{ "dev-entry": "/dev/disk23" }]), + exitCode: 0, + }); + if (arguments_[0] !== "attach") + return Promise.resolve({ stdout: "", exitCode: 0 }); + mount.rememberRoot(arguments_); + return Promise.resolve({ + stdout: attachPlist([{ "dev-entry": "/dev/disk23" }]), + exitCode: 0, + }); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ + reason: "unavailable", + cleanup: { + resources: expect.arrayContaining([ + expect.stringMatching( + /^DMG attachment ownership unknown at mount root /u, + ), + expect.stringMatching(/^DMG mount root /u), + ]), + }, + }); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([]); + expect(await realpath(mount.root() ?? "")).toBe(mount.root()); + }); +}); + +describe("DMG attach cancellation and preexisting mounts", () => { + it("waits for an aborted attach result before discovering and detaching its mount", async () => { + const calls: string[][] = []; + const controller = new AbortController(); + const mount = createMountFixture(); + let markAttachStarted = (): void => {}; + const attachStarted = new Promise((resolveStarted) => { + markAttachStarted = resolveStarted; + }); + let attached = false; + let mountPoint: string | undefined; + const host: NativeDmgHost = { + async run(arguments_, signal) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk21", + "mount-point": mountPoint, + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } + if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; + mountPoint = join(mount.rememberRoot(arguments_), "Fixture"); + markAttachStarted(); + return new Promise((_, reject) => { + signal?.addEventListener( + "abort", + () => { + void mkdir(mountPoint ?? "").then(async () => { + attached = true; + await writeFile( + join(mountPoint ?? "", "hello.txt"), + "after exit", + ); + reject( + Object.assign(new Error("attach aborted"), { + name: "AbortError", + }), + ); + }); + }, + { once: true }, + ); + }); + }, + }; + + const creating = NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + controller.signal, + host, + ); + await attachStarted; + controller.abort(); + await expect(creating).rejects.toMatchObject({ reason: "cancelled" }); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + "detach", + ]); + expect(calls).toContainEqual(["detach", "/dev/disk21"]); + }); + + it("leaves a preexisting outside-root mount attached", async () => { + const calls: string[][] = []; + const host: NativeDmgHost = { + async run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk22", + "mount-point": "/Volumes/AlreadyMounted", + }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "attach") + return { + stdout: attachPlist([ + { + "dev-entry": "/dev/disk22", + "mount-point": "/Volumes/AlreadyMounted", + }, + ]), + exitCode: 0, + }; + return { stdout: "", exitCode: 0 }; + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ reason: "path" }); + expect(calls.filter(([operation]) => operation === "detach")).toEqual([]); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + "info", + ]); }); }); describe("native DMG command failure diagnostics", () => { + it("removes an empty root when the attach process never started", async () => { + const calls: string[][] = []; + let mountRoot: string | undefined; + onTestFinished(async () => { + if (mountRoot !== undefined) + await rm(mountRoot, { recursive: true, force: true }); + }); + const host: NativeDmgHost = { + run(arguments_) { + calls.push([...arguments_]); + if (arguments_[0] === "verify") + return Promise.resolve({ stdout: "", exitCode: 0 }); + if (arguments_[0] === "info") + return Promise.resolve({ stdout: emptyInfoPlist, exitCode: 0 }); + if (arguments_[0] === "attach") { + mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; + return Promise.reject( + Object.assign(new Error("could not spawn hdiutil"), { + code: "ENOENT", + syscall: "spawn /usr/bin/hdiutil", + errno: -2, + }), + ); + } + throw new Error(`unexpected command: ${arguments_[0] ?? ""}`); + }, + }; + + await expect( + NativeDmgArtifactReader.create( + "/tmp/image.dmg", + process.env, + undefined, + host, + ), + ).rejects.toMatchObject({ + reason: "unavailable", + message: expect.stringContaining('"code":"ENOENT"'), + cleanup: undefined, + }); + expect(calls.map(([operation]) => operation)).toEqual([ + "verify", + "info", + "attach", + ]); + expect( + await realpath(mountRoot ?? "").catch(() => undefined), + ).toBeUndefined(); + }); +}); + +describe("native DMG command diagnostics", () => { it("keeps unknown attach failures unavailable with command evidence", async () => { await expect( NativeDmgArtifactReader.create("/tmp/image.dmg", process.env, undefined, { run(arguments_) { if (arguments_[0] === "verify") return Promise.resolve({ stdout: "", exitCode: 0 }); + if (arguments_[0] === "info") + return Promise.resolve({ + stdout: emptyInfoPlist, + exitCode: 0, + }); return Promise.resolve({ stdout: "attach output", stderr: "attach failed for an unknown reason", @@ -370,26 +912,43 @@ describe("native DMG real verification diagnostics", () => { it("owns the canonical mount root and detaches each observed whole image once", async () => { const calls: string[][] = []; + const mount = createMountFixture(); + let attached = false; + let mountPoint: string | undefined; const host: NativeDmgHost = { async run(arguments_) { calls.push([...arguments_]); + if (arguments_[0] === "info") + return { + stdout: + !attached || mountPoint === undefined + ? emptyInfoPlist + : infoPlist("/tmp/image.dmg", [ + { "dev-entry": "/dev/disk41" }, + { "dev-entry": "/dev/disk41s1" }, + { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk42" }, + { "dev-entry": "/dev/disk42s1" }, + ]), + exitCode: 0, + }; + if (arguments_[0] === "detach") { + attached = false; + return { stdout: "", exitCode: 0 }; + } if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; - const mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - expect(mountRoot).toBe(await realpath(mountRoot)); - const mountPoint = join(await realpath(mountRoot), "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "hello"); + const mounted = await mount.createVolume(arguments_, "hello"); + expect(mounted.mountRoot).toBe(await realpath(mounted.mountRoot)); + mountPoint = mounted.mountPoint; + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk41" }, - { "dev-entry": "/dev/disk41s1" }, - { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, - { "dev-entry": "/dev/disk42" }, - { "dev-entry": "/dev/disk42s1" }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk41" }, + { "dev-entry": "/dev/disk41s1" }, + { "dev-entry": "/dev/disk41s2", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk42" }, + { "dev-entry": "/dev/disk42s1" }, + ]), exitCode: 0, }; }, @@ -421,11 +980,9 @@ const apfsHost = ( ) => { const calls: string[][] = []; let infoReads = 0; - let mountRoot: string | undefined; - onTestFinished(async () => { - if (mountRoot !== undefined) - await rm(mountRoot, { recursive: true, force: true }); - }); + const mount = createMountFixture(); + let mountPoint: string | undefined; + let attached = false; const host: NativeDmgHost = { delay: () => Promise.resolve(), async run(arguments_) { @@ -435,33 +992,48 @@ const apfsHost = ( if (arguments_[0] === "info") return { stdout: build({ - images: - stillListed.length === 0 || (infoReads += 1) > listedInfoReads - ? [] - : [ + images: !attached + ? [] + : infoReads++ === 0 + ? [ { - "system-entities": stillListed.map((device) => ({ - "dev-entry": device, - })), + "image-path": "/tmp/image.dmg", + "system-entities": [ + { "dev-entry": "/dev/disk4" }, + { "dev-entry": "/dev/disk4s1" }, + { + "dev-entry": "/dev/disk5s1", + ...(mountPoint === undefined + ? {} + : { "mount-point": mountPoint }), + }, + { "dev-entry": "/dev/disk5" }, + ], }, - ], + ] + : stillListed.length === 0 || infoReads > listedInfoReads + 1 + ? [] + : [ + { + "image-path": "/tmp/image.dmg", + "system-entities": stillListed.map((device) => ({ + "dev-entry": device, + })), + }, + ], }), exitCode: 0, }; if (arguments_[0] !== "attach") return { stdout: "", exitCode: 0 }; - mountRoot = arguments_[arguments_.indexOf("-mountroot") + 1]; - if (mountRoot === undefined) throw new Error("missing mount root"); - const mountPoint = join(mountRoot, "Fixture"); - await mkdir(mountPoint); + ({ mountPoint } = await mount.createVolume(arguments_)); + attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk4" }, - { "dev-entry": "/dev/disk4s1" }, - { "dev-entry": "/dev/disk5s1", "mount-point": mountPoint }, - { "dev-entry": "/dev/disk5" }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk4" }, + { "dev-entry": "/dev/disk4s1" }, + { "dev-entry": "/dev/disk5s1", "mount-point": mountPoint }, + { "dev-entry": "/dev/disk5" }, + ]), exitCode: 0, }; }, @@ -471,16 +1043,13 @@ const apfsHost = ( // One mounted device whose detach reports busy while `busy(attempt)` holds. const singleDeviceHost = (busy: (attempt: number) => boolean) => { + const mount = createMountFixture(); const state = { - attached: true, + attached: false, attempts: 0, mountRoot: undefined as string | undefined, waits: [] as number[], }; - onTestFinished(async () => { - if (state.mountRoot !== undefined) - await rm(state.mountRoot, { recursive: true, force: true }); - }); const host: NativeDmgHost = { delay: (milliseconds) => { state.waits.push(milliseconds); @@ -488,28 +1057,26 @@ const singleDeviceHost = (busy: (attempt: number) => boolean) => { }, async run(args) { if (args[0] === "attach") { - state.mountRoot = args[args.indexOf("-mountroot") + 1]; - if (state.mountRoot === undefined) - throw new Error("missing mount root"); - const mountPoint = join(state.mountRoot, "Fixture"); - await mkdir(mountPoint); - await writeFile(join(mountPoint, "hello.txt"), "owned observation"); + const mounted = await mount.createVolume(args, "owned observation"); + state.mountRoot = mounted.mountRoot; + state.attached = true; return { - stdout: build({ - "system-entities": [ - { "dev-entry": "/dev/disk7", "mount-point": mountPoint }, - ], - }), + stdout: attachPlist([ + { "dev-entry": "/dev/disk7", "mount-point": mounted.mountPoint }, + ]), exitCode: 0, }; } if (args[0] === "info") return { - stdout: build({ - images: state.attached - ? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }] - : [], - }), + stdout: state.attached + ? infoPlist("/tmp/image.dmg", [ + { + "dev-entry": "/dev/disk7", + "mount-point": join(state.mountRoot ?? "", "Fixture"), + }, + ]) + : emptyInfoPlist, exitCode: 0, }; if (args[0] === "detach") { @@ -545,9 +1112,9 @@ const closeApfsFixture = async ( await reader.close(); return { reader, - cleanup: calls.filter( - (call) => call[0] !== "verify" && call[0] !== "attach", - ), + cleanup: calls + .slice(calls.findIndex((call) => call[0] === "attach") + 1) + .slice(1), }; };