fix(artifacts): retain reader owners after cleanup failures
Keep directory handles under explicit close ownership and retain ZIP and Mach-O admission owners when initialization or cleanup fails. Preserve cancellation and primary failure details, and avoid false successful release after native handle invalidation. Validation: filesystem ownership, FIFO, archive and reconstruction boundary checks; static and architecture checks; real macOS CLI/MCP bundle workflows. Windows native behavior was not verified.
This commit is contained in:
@@ -1,23 +1,32 @@
|
||||
import { constants } from "node:fs";
|
||||
import { lstat, open, opendir, realpath } from "node:fs/promises";
|
||||
import { constants, type Dir, type Stats } from "node:fs";
|
||||
import {
|
||||
lstat,
|
||||
open,
|
||||
opendir,
|
||||
realpath,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, sep } from "node:path";
|
||||
import type { Readable } from "node:stream";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactEntry,
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
|
||||
|
||||
/** Non-symlink-following directory reader. */
|
||||
export class DirectoryArtifactReader implements ArtifactReader {
|
||||
readonly format = "directory" as const;
|
||||
readonly #rootPromise: Promise<string>;
|
||||
#rootPromise: Promise<string> | undefined;
|
||||
readonly #rootPath: string;
|
||||
readonly #directories = new Set<OwnedDirectoryHandle>();
|
||||
readonly #files = new Map<OwnedFileHandle, string>();
|
||||
|
||||
constructor(root: string) {
|
||||
this.#rootPath = root;
|
||||
this.#rootPromise = realpath(root);
|
||||
}
|
||||
|
||||
/** Enumerate entries, optionally restricting descent while retaining directories. */
|
||||
@@ -25,9 +34,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
signal?: AbortSignal,
|
||||
descendInto?: (path: string) => boolean,
|
||||
): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#rootPromise.catch((cause: unknown) => {
|
||||
throw directoryIoFailure("resolve artifact root", this.#rootPath, cause);
|
||||
});
|
||||
const root = await this.#resolveRoot();
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
abortIfNeeded(signal);
|
||||
@@ -36,62 +43,100 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory),
|
||||
);
|
||||
const handle = await opendir(directory).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open directory", directory, cause);
|
||||
});
|
||||
const directories: string[] = [];
|
||||
try {
|
||||
for await (const child of handle) {
|
||||
abortIfNeeded(signal);
|
||||
const absolute = join(directory, child.name);
|
||||
const metadata = await lstat(absolute).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("inspect entry", absolute, cause);
|
||||
});
|
||||
const path = relative(root, absolute).split(sep).join("/");
|
||||
const kind = metadata.isSymbolicLink()
|
||||
? "symlink"
|
||||
: metadata.isDirectory()
|
||||
? "directory"
|
||||
: metadata.isFile()
|
||||
? "file"
|
||||
: undefined;
|
||||
if (kind === undefined) continue;
|
||||
yield {
|
||||
path,
|
||||
kind,
|
||||
declaredSize: kind === "file" ? metadata.size : null,
|
||||
compressedSize: null,
|
||||
executable: (metadata.mode & 0o111) !== 0,
|
||||
encrypted: false,
|
||||
byteOffset: null,
|
||||
declaredSha256: null,
|
||||
unpacked: false,
|
||||
limitations:
|
||||
kind === "symlink"
|
||||
? ["Symlink target was not followed or disclosed."]
|
||||
: [],
|
||||
adapterKey: absolute,
|
||||
...(kind === "file"
|
||||
? {
|
||||
sourceIdentity: { device: metadata.dev, inode: metadata.ino },
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
if (kind === "directory" && (descendInto?.(path) ?? true))
|
||||
directories.push(absolute);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure) throw cause;
|
||||
throw directoryIoFailure("read directory", directory, cause);
|
||||
} finally {
|
||||
// best-effort cleanup: directory-handle close must not mask traversal.
|
||||
await handle.close().catch(() => undefined);
|
||||
}
|
||||
for await (const entry of this.#readDirectory(
|
||||
directory,
|
||||
pending,
|
||||
signal,
|
||||
descendInto,
|
||||
))
|
||||
yield entry;
|
||||
await withDirectoryIoContext("inspect directory", directory, () =>
|
||||
assertContainedDirectory(root, directory),
|
||||
);
|
||||
directories.reverse();
|
||||
pending.push(...directories);
|
||||
}
|
||||
}
|
||||
|
||||
async #resolveRoot(): Promise<string> {
|
||||
return (this.#rootPromise ??= realpath(this.#rootPath)).catch(
|
||||
(cause: unknown) => {
|
||||
throw directoryIoFailure(
|
||||
"resolve artifact root",
|
||||
this.#rootPath,
|
||||
cause,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async *#readDirectory(
|
||||
directory: string,
|
||||
pending: string[],
|
||||
signal?: AbortSignal,
|
||||
descendInto?: (path: string) => boolean,
|
||||
): AsyncIterable<ArtifactEntry> {
|
||||
const root = await this.#resolveRoot();
|
||||
const handle = new OwnedDirectoryHandle(
|
||||
await opendir(directory).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open directory", directory, cause);
|
||||
}),
|
||||
);
|
||||
this.#directories.add(handle);
|
||||
const childDirectories: string[] = [];
|
||||
let traversal:
|
||||
| { readonly kind: "complete" }
|
||||
| { readonly kind: "failed"; readonly cause: unknown } = {
|
||||
kind: "complete",
|
||||
};
|
||||
try {
|
||||
for (;;) {
|
||||
const child = await handle.handle.read();
|
||||
if (child === null) break;
|
||||
abortIfNeeded(signal);
|
||||
const absolute = join(directory, child.name);
|
||||
const metadata = await lstat(absolute).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("inspect entry", absolute, cause);
|
||||
});
|
||||
const path = relative(root, absolute).split(sep).join("/");
|
||||
const entry = artifactEntry(path, absolute, metadata);
|
||||
if (entry === undefined) continue;
|
||||
yield entry;
|
||||
if (entry.kind === "directory" && (descendInto?.(path) ?? true))
|
||||
childDirectories.push(absolute);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
traversal = {
|
||||
kind: "failed",
|
||||
cause:
|
||||
cause instanceof ArtifactReaderFailure
|
||||
? cause
|
||||
: directoryIoFailure("read directory", directory, cause),
|
||||
};
|
||||
} finally {
|
||||
await this.#finishDirectory(handle, directory, traversal);
|
||||
}
|
||||
if (traversal.kind === "failed") throw traversal.cause;
|
||||
childDirectories.reverse();
|
||||
pending.push(...childDirectories);
|
||||
}
|
||||
|
||||
async #finishDirectory(
|
||||
handle: OwnedDirectoryHandle,
|
||||
path: string,
|
||||
traversal:
|
||||
| { readonly kind: "complete" }
|
||||
| { readonly kind: "failed"; readonly cause: unknown },
|
||||
): Promise<void> {
|
||||
try {
|
||||
await handle.close();
|
||||
this.#directories.delete(handle);
|
||||
} catch (cause: unknown) {
|
||||
const closeFailure = directoryIoFailure("close directory", path, cause);
|
||||
if (traversal.kind === "failed")
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
traversal.cause,
|
||||
ArtifactReaderFailure.cleanupObservation(closeFailure, path),
|
||||
);
|
||||
throw closeFailure;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,14 +147,16 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
"format",
|
||||
"Only regular files can be opened",
|
||||
);
|
||||
const handle = await open(
|
||||
const fileHandle = await open(
|
||||
entry.adapterKey,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
).catch((cause: unknown) => {
|
||||
throw directoryIoFailure("open entry", entry.adapterKey, cause);
|
||||
});
|
||||
const owner = new OwnedFileHandle(fileHandle);
|
||||
this.#files.set(owner, entry.adapterKey);
|
||||
try {
|
||||
const observed = await handle.stat().catch((cause: unknown) => {
|
||||
const observed = await owner.handle.stat().catch((cause: unknown) => {
|
||||
throw directoryIoFailure(
|
||||
"inspect opened entry",
|
||||
entry.adapterKey,
|
||||
@@ -127,16 +174,76 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
`Directory entry changed before open: ${entry.path}`,
|
||||
);
|
||||
}
|
||||
return handle.createReadStream({ autoClose: true });
|
||||
abortIfNeeded(signal);
|
||||
const source = Readable.from(
|
||||
mapFileReadCancellation(owner.handle, signal),
|
||||
{ objectMode: false },
|
||||
);
|
||||
source.once("close", () => {
|
||||
void this.#closeFile(owner).catch(() => undefined);
|
||||
});
|
||||
return source;
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: file-handle close must not mask the open failure.
|
||||
await handle.close().catch(() => undefined);
|
||||
try {
|
||||
await this.#closeFile(owner);
|
||||
} catch (closeCause: unknown) {
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
cause,
|
||||
ArtifactReaderFailure.cleanupObservation(
|
||||
directoryIoFailure(
|
||||
"close opened entry",
|
||||
entry.adapterKey,
|
||||
closeCause,
|
||||
),
|
||||
entry.adapterKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
async close(): Promise<void> {
|
||||
const failures: unknown[] = [];
|
||||
for (const [owner, path] of this.#files) {
|
||||
try {
|
||||
await this.#closeFile(owner);
|
||||
} catch (cause: unknown) {
|
||||
failures.push(directoryIoFailure("close opened entry", path, cause));
|
||||
}
|
||||
}
|
||||
for (const owner of this.#directories) {
|
||||
try {
|
||||
await owner.close();
|
||||
this.#directories.delete(owner);
|
||||
} catch (cause: unknown) {
|
||||
failures.push(
|
||||
directoryIoFailure("close directory", owner.handle.path, cause),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (failures.length > 0) {
|
||||
const reason = failures.map(failureMessage).join("; ");
|
||||
throw new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Directory artifact cleanup failed: ${reason}`,
|
||||
{
|
||||
cause: new AggregateError(failures),
|
||||
cleanup: {
|
||||
reason,
|
||||
resources: [
|
||||
...this.#files.values(),
|
||||
...[...this.#directories].map((owner) => owner.handle.path),
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async #closeFile(owner: OwnedFileHandle<FileHandle>): Promise<void> {
|
||||
await owner.close();
|
||||
this.#files.delete(owner);
|
||||
}
|
||||
|
||||
provenance(): readonly [] {
|
||||
@@ -144,6 +251,74 @@ export class DirectoryArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
const artifactEntry = (
|
||||
path: string,
|
||||
absolute: string,
|
||||
metadata: Stats,
|
||||
): ArtifactEntry | undefined => {
|
||||
const kind = metadata.isSymbolicLink()
|
||||
? "symlink"
|
||||
: metadata.isDirectory()
|
||||
? "directory"
|
||||
: metadata.isFile()
|
||||
? "file"
|
||||
: undefined;
|
||||
if (kind === undefined) return undefined;
|
||||
return {
|
||||
path,
|
||||
kind,
|
||||
declaredSize: kind === "file" ? metadata.size : null,
|
||||
compressedSize: null,
|
||||
executable: (metadata.mode & 0o111) !== 0,
|
||||
encrypted: false,
|
||||
byteOffset: null,
|
||||
declaredSha256: null,
|
||||
unpacked: false,
|
||||
limitations:
|
||||
kind === "symlink"
|
||||
? ["Symlink target was not followed or disclosed."]
|
||||
: [],
|
||||
adapterKey: absolute,
|
||||
...(kind === "file"
|
||||
? {
|
||||
sourceIdentity: { device: metadata.dev, inode: metadata.ino },
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
type DirectoryCloseState =
|
||||
| { readonly kind: "open" }
|
||||
| { readonly kind: "closing"; readonly attempt: Promise<void> }
|
||||
| { readonly kind: "closed" }
|
||||
| { readonly kind: "failed"; readonly cause: unknown };
|
||||
|
||||
/** Dir.close invalidates Node's private handle before its native close settles. */
|
||||
class OwnedDirectoryHandle {
|
||||
#state: DirectoryCloseState = { kind: "open" };
|
||||
|
||||
constructor(readonly handle: Dir) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
if (this.#state.kind === "closed") return Promise.resolve();
|
||||
if (this.#state.kind === "closing") return this.#state.attempt;
|
||||
if (this.#state.kind === "failed") return Promise.reject(this.#state.cause);
|
||||
const attempt = Promise.resolve().then(async () => {
|
||||
try {
|
||||
await this.handle.close();
|
||||
this.#state = { kind: "closed" };
|
||||
} catch (cause: unknown) {
|
||||
// Dir exposes no public validity signal; a second close can only lie
|
||||
// with ERR_DIR_CLOSED after Node has invalidated the first owner.
|
||||
this.#state = { kind: "failed", cause };
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
this.#state = { kind: "closing", attempt };
|
||||
return attempt;
|
||||
}
|
||||
}
|
||||
|
||||
const directoryIoFailure = (
|
||||
operation: string,
|
||||
path: string,
|
||||
@@ -157,13 +332,38 @@ const directoryIoFailure = (
|
||||
typeof cause.code === "string"
|
||||
? ` (${cause.code})`
|
||||
: "";
|
||||
const detail = failureMessage(cause);
|
||||
return new ArtifactReaderFailure(
|
||||
"io",
|
||||
`Could not ${operation} at ${path}${code}`,
|
||||
`Could not ${operation} at ${path}${code}: ${detail}`,
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const failureMessage = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
const mapFileReadCancellation = async function* (
|
||||
handle: FileHandle,
|
||||
signal?: AbortSignal,
|
||||
): AsyncGenerator<Buffer> {
|
||||
try {
|
||||
for await (const chunk of readFileHandleChunks(handle, { signal })) {
|
||||
abortIfNeeded(signal);
|
||||
yield chunk;
|
||||
}
|
||||
abortIfNeeded(signal);
|
||||
} catch (cause: unknown) {
|
||||
if (signal?.aborted === true)
|
||||
throw new ArtifactReaderFailure(
|
||||
"cancelled",
|
||||
"Directory artifact read cancelled",
|
||||
{ cause },
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
const withDirectoryIoContext = async <T>(
|
||||
operation: string,
|
||||
path: string,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type LipoArchitecture,
|
||||
} from "../native/parsers/lipo.js";
|
||||
import type { MachoSlice } from "../domain/apple/dylibResolution.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { readMachoImage, type ReadAt } from "./apple/MachoLoadCommandReader.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
@@ -22,6 +23,8 @@ import {
|
||||
} from "./ArtifactReader.js";
|
||||
import { streamChunkToBuffer } from "./StreamBytes.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
RegularFileAdmissionFailure,
|
||||
openRegularFile,
|
||||
sameRegularFileState,
|
||||
type StableRegularFileDescriptor,
|
||||
@@ -33,6 +36,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
readonly format = "file" as const;
|
||||
#command: ArtifactCommand | undefined;
|
||||
#source: StableRegularFileDescriptor | undefined;
|
||||
#ownedSource: OwnedFileHandle | undefined;
|
||||
#pendingSource: Promise<StableRegularFileDescriptor> | undefined;
|
||||
readonly #entries = new Map<string, ArtifactEntry>();
|
||||
readonly #ownsSource: boolean;
|
||||
@@ -283,23 +287,51 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async #acquireSource(): Promise<StableRegularFileDescriptor> {
|
||||
const handle = await openRegularFile(this.path, { symlinks: "reject" });
|
||||
let handle: FileHandle;
|
||||
try {
|
||||
handle = await openRegularFile(this.path, { symlinks: "reject" });
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof RegularFileAdmissionFailure)) throw cause;
|
||||
this.#ownedSource = cause.owner;
|
||||
const primary =
|
||||
cause.cause instanceof NonRegularFileReadError
|
||||
? new ArtifactReaderFailure(
|
||||
"format",
|
||||
`Universal Mach-O source is not a regular file: ${this.path}`,
|
||||
{ cause: cause.cause },
|
||||
)
|
||||
: cause.cause;
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
primary,
|
||||
ArtifactReaderFailure.cleanupObservation(cause.cleanupCause, this.path),
|
||||
);
|
||||
}
|
||||
const owner = new OwnedFileHandle(handle);
|
||||
this.#ownedSource = owner;
|
||||
try {
|
||||
const initial = await handle.stat();
|
||||
const source = { handle, initial };
|
||||
this.#source = source;
|
||||
return source;
|
||||
} catch (cause: unknown) {
|
||||
await handle.close().catch(() => undefined);
|
||||
try {
|
||||
await owner.close();
|
||||
this.#ownedSource = undefined;
|
||||
} catch (cleanupCause: unknown) {
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
cause,
|
||||
ArtifactReaderFailure.cleanupObservation(cleanupCause, this.path),
|
||||
);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
async #closeSource(): Promise<void> {
|
||||
await this.#pendingSource?.catch(() => undefined);
|
||||
if (!this.#ownsSource || this.#source === undefined) return;
|
||||
const source = this.#source;
|
||||
await source.handle.close();
|
||||
if (!this.#ownsSource || this.#ownedSource === undefined) return;
|
||||
await this.#ownedSource.close();
|
||||
this.#ownedSource = undefined;
|
||||
this.#source = undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,10 @@ import {
|
||||
type ArtifactReader,
|
||||
} from "./ArtifactReader.js";
|
||||
import type { ZipPackageFormat } from "../domain/zipPackageFormat.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import {
|
||||
NonRegularFileReadError,
|
||||
RegularFileAdmissionFailure,
|
||||
openRegularFile,
|
||||
sameRegularFileState,
|
||||
type StableRegularFileDescriptor,
|
||||
@@ -21,6 +23,7 @@ import {
|
||||
|
||||
class NodeFileReader extends Reader<string> {
|
||||
#handle: FileHandle | undefined;
|
||||
#owner: OwnedFileHandle | undefined;
|
||||
#initPromise: Promise<void> | undefined;
|
||||
readonly #ownsHandle: boolean;
|
||||
|
||||
@@ -40,10 +43,30 @@ class NodeFileReader extends Reader<string> {
|
||||
|
||||
async #initialize(): Promise<void> {
|
||||
try {
|
||||
this.#handle =
|
||||
const handle =
|
||||
this.admitted?.handle ??
|
||||
(await openRegularFile(this.path, { symlinks: "reject" }));
|
||||
this.#handle = handle;
|
||||
if (this.#ownsHandle) this.#owner = new OwnedFileHandle(handle);
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileAdmissionFailure) {
|
||||
this.#owner = cause.owner;
|
||||
const primary =
|
||||
cause.cause instanceof NonRegularFileReadError
|
||||
? new ArtifactReaderFailure(
|
||||
"format",
|
||||
`ZIP source is not a regular file: ${this.path}`,
|
||||
{ cause: cause.cause },
|
||||
)
|
||||
: cause.cause;
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
primary,
|
||||
ArtifactReaderFailure.cleanupObservation(
|
||||
cause.cleanupCause,
|
||||
this.path,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (cause instanceof NonRegularFileReadError)
|
||||
throw new ArtifactReaderFailure(
|
||||
"format",
|
||||
@@ -88,8 +111,9 @@ class NodeFileReader extends Reader<string> {
|
||||
async closeHandle(): Promise<void> {
|
||||
if (!this.#ownsHandle) return;
|
||||
await this.#initPromise?.catch(() => undefined);
|
||||
if (this.#handle === undefined) return;
|
||||
await this.#handle.close();
|
||||
if (this.#owner === undefined) return;
|
||||
await this.#owner.close();
|
||||
this.#owner = undefined;
|
||||
this.#handle = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user