fix(targets): cancel resolution before provider admission
This commit is contained in:
@@ -10,6 +10,7 @@ import {
|
||||
import { extname, isAbsolute, resolve } from "node:path";
|
||||
|
||||
import { BinaryTargetError } from "../domain/configurationErrors.js";
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -32,6 +33,15 @@ import {
|
||||
type ExecutableMetadata,
|
||||
} from "../domain/binaryTarget.js";
|
||||
|
||||
/** Options for resolving a local binary target and its stable identity. */
|
||||
export interface BinaryTargetResolverOptions {
|
||||
readonly cwd?: string;
|
||||
readonly hostArchitecture?: NodeJS.Architecture;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
@@ -39,24 +49,32 @@ import {
|
||||
*/
|
||||
export const parseBinaryTarget = async (
|
||||
input: string,
|
||||
cwd = process.cwd(),
|
||||
hostArchitecture: NodeJS.Architecture = process.arch,
|
||||
targetKind?: BinaryTarget["kind"],
|
||||
formatHint?: ExecutableFormatHint,
|
||||
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
|
||||
options: BinaryTargetResolverOptions = {},
|
||||
): Promise<
|
||||
Result<BinaryTarget, BinaryTargetError | AnalysisCancelledError>
|
||||
> => {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const hostArchitecture = options.hostArchitecture ?? process.arch;
|
||||
const { targetKind, formatHint, signal } = options;
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
await access(candidate, constants.R_OK);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const canonical = await realpath(candidate);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const resolved = await resolveAppBundle(canonical);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (!resolved.ok) return err(resolved.error);
|
||||
const { executable: path, infoPlist } = resolved.value;
|
||||
const bundle =
|
||||
infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist };
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (!(await handle.stat()).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (formatHint === "dos-com") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
@@ -70,7 +88,7 @@ export const parseBinaryTarget = async (
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
sha256: await sha256Handle(handle, signal),
|
||||
kind: "executable",
|
||||
format: "dos-com",
|
||||
architecture: "x86",
|
||||
@@ -84,28 +102,32 @@ export const parseBinaryTarget = async (
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
sha256: await sha256Handle(handle, signal),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
const artifactFormat = await detectArtifactFormat(path, handle);
|
||||
const artifactFormat = await detectArtifactFormat(path, handle, signal);
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
sha256: await sha256Handle(handle, signal),
|
||||
};
|
||||
return isArchiveFormat(artifactFormat)
|
||||
? ok({ ...identity, kind: "archive", format: artifactFormat })
|
||||
: ok({ ...identity, kind: "artifact", format: artifactFormat });
|
||||
}
|
||||
const detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
const detected = await readExecutableMetadata(
|
||||
handle,
|
||||
hostArchitecture,
|
||||
signal,
|
||||
);
|
||||
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
...bundle,
|
||||
sha256: await sha256Handle(handle),
|
||||
sha256: await sha256Handle(handle, signal),
|
||||
kind: "executable",
|
||||
...detected.value,
|
||||
});
|
||||
@@ -113,6 +135,7 @@ export const parseBinaryTarget = async (
|
||||
await handle.close();
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof AnalysisCancelledError) return err(cause);
|
||||
if (!(cause instanceof Error)) throw cause;
|
||||
const code = filesystemErrorCode(cause);
|
||||
if (code === undefined) throw cause;
|
||||
@@ -146,9 +169,15 @@ const targetFailureReason = (code: string, detail: string): string => {
|
||||
}
|
||||
};
|
||||
|
||||
const throwIfTargetResolutionCancelled = (signal?: AbortSignal): void => {
|
||||
if (signal?.aborted === true)
|
||||
throw new AnalysisCancelledError("resolve_binary_target");
|
||||
};
|
||||
|
||||
const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
signal?: AbortSignal,
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
@@ -156,9 +185,11 @@ const detectArtifactFormat = async (
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const lower = path.toLowerCase();
|
||||
const magic = Buffer.alloc(8);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (hasZipSignature(magic.subarray(0, observed.bytesRead))) {
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
@@ -171,10 +202,13 @@ const detectArtifactFormat = async (
|
||||
)
|
||||
return "pkg";
|
||||
if (lower.endsWith(".dmg")) {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const size = (await handle.stat()).size;
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (size >= 512) {
|
||||
const trailer = Buffer.alloc(4);
|
||||
const read = await handle.read(trailer, 0, trailer.length, size - 512);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (read.bytesRead === 4 && trailer.toString("ascii") === "koly")
|
||||
return "dmg";
|
||||
}
|
||||
@@ -199,12 +233,17 @@ const isArchiveFormat = (
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
const sha256Handle = async (handle: FileHandle): Promise<string> => {
|
||||
const sha256Handle = async (
|
||||
handle: FileHandle,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
const chunk = Buffer.allocUnsafe(64 * 1024);
|
||||
let position = 0;
|
||||
while (true) {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const observed = await handle.read(chunk, 0, chunk.length, position);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (observed.bytesRead === 0) break;
|
||||
hash.update(chunk.subarray(0, observed.bytesRead));
|
||||
position += observed.bytesRead;
|
||||
@@ -233,19 +272,23 @@ const resolveAppBundle = async (
|
||||
const readExecutableMetadata = async (
|
||||
handle: FileHandle,
|
||||
hostArchitecture: NodeJS.Architecture,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const prefix = Buffer.alloc(4096);
|
||||
const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const bytes = prefix.subarray(0, prefixRead.bytesRead);
|
||||
// Header commitments such as Mach-O load commands and FAT slices are
|
||||
// checked against the whole file, not the probed prefix.
|
||||
const fileSize = (await handle.stat()).size;
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
|
||||
const offset = mzWindowsHeaderOffset(bytes);
|
||||
if (offset !== null) {
|
||||
if (offset < 64)
|
||||
return err("invalid Windows new-header offset in MZ image");
|
||||
return readPeMetadata(handle, offset);
|
||||
return readPeMetadata(handle, offset, signal);
|
||||
}
|
||||
// MZ relocation records may extend past the initial probe; their format
|
||||
// bounds are at most 65535 records inside a 65535-paragraph header.
|
||||
@@ -261,6 +304,7 @@ const readExecutableMetadata = async (
|
||||
) {
|
||||
const table = Buffer.alloc(tableEnd);
|
||||
const observed = await handle.read(table, 0, table.length, 0);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
return parseExecutableHeader(
|
||||
table.subarray(0, observed.bytesRead),
|
||||
hostArchitecture,
|
||||
@@ -278,6 +322,7 @@ const readExecutableMetadata = async (
|
||||
if (count <= 128 && required > bytes.length) {
|
||||
const header = Buffer.alloc(required);
|
||||
const headerRead = await handle.read(header, 0, header.length, 0);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
return parseExecutableHeader(
|
||||
header.subarray(0, headerRead.bytesRead),
|
||||
hostArchitecture,
|
||||
@@ -292,7 +337,9 @@ const readExecutableMetadata = async (
|
||||
const readPeMetadata = async (
|
||||
handle: FileHandle,
|
||||
offset: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const fileHeader = Buffer.alloc(24);
|
||||
const fileHeaderRead = await handle.read(
|
||||
fileHeader,
|
||||
@@ -300,6 +347,7 @@ const readPeMetadata = async (
|
||||
fileHeader.length,
|
||||
offset,
|
||||
);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (fileHeaderRead.bytesRead !== fileHeader.length)
|
||||
return err("invalid or truncated PE header");
|
||||
const signature = fileHeader.toString("ascii", 0, 2);
|
||||
@@ -309,6 +357,7 @@ const readPeMetadata = async (
|
||||
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
|
||||
const record = Buffer.alloc(24 + optionalHeaderSize);
|
||||
const recordRead = await handle.read(record, 0, record.length, offset);
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
return recordRead.bytesRead === record.length
|
||||
? parsePeRecord(record)
|
||||
: err("invalid or truncated PE header");
|
||||
|
||||
Reference in New Issue
Block a user