fix(artifacts): retain Mach-O source identity through inventory
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
import { createReadStream } from "node:fs";
|
import { lstat } from "node:fs/promises";
|
||||||
import { open as openFile, stat } from "node:fs/promises";
|
import type { FileHandle } from "node:fs/promises";
|
||||||
import { Readable } from "node:stream";
|
import { Readable } from "node:stream";
|
||||||
|
|
||||||
import type { ArtifactCommand } from "../domain/artifactGraph.js";
|
import type { ArtifactCommand } from "../domain/artifactGraph.js";
|
||||||
@@ -19,11 +19,21 @@ import {
|
|||||||
type ArtifactReader,
|
type ArtifactReader,
|
||||||
} from "./ArtifactReader.js";
|
} from "./ArtifactReader.js";
|
||||||
import { streamChunkToBuffer } from "./StreamBytes.js";
|
import { streamChunkToBuffer } from "./StreamBytes.js";
|
||||||
|
import {
|
||||||
|
openRegularFile,
|
||||||
|
sameRegularFileState,
|
||||||
|
type StableRegularFileDescriptor,
|
||||||
|
} from "../filesystem/RegularFile.js";
|
||||||
|
|
||||||
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
|
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
|
||||||
export class MachOSliceArtifactReader implements ArtifactReader {
|
export class MachOSliceArtifactReader implements ArtifactReader {
|
||||||
readonly format = "file" as const;
|
readonly format = "file" as const;
|
||||||
#command: ArtifactCommand | undefined;
|
#command: ArtifactCommand | undefined;
|
||||||
|
#source: StableRegularFileDescriptor | undefined;
|
||||||
|
#pendingSource: Promise<StableRegularFileDescriptor> | undefined;
|
||||||
|
readonly #ownsSource: boolean;
|
||||||
|
#closed = false;
|
||||||
|
#closePromise: Promise<void> | undefined;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly path: string,
|
private readonly path: string,
|
||||||
@@ -31,9 +41,15 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
|||||||
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
|
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
|
||||||
environment,
|
environment,
|
||||||
),
|
),
|
||||||
) {}
|
source?: StableRegularFileDescriptor,
|
||||||
|
) {
|
||||||
|
this.#source = source;
|
||||||
|
this.#ownsSource = source === undefined;
|
||||||
|
}
|
||||||
|
|
||||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||||
|
const source = await this.#ensureSource();
|
||||||
|
await this.#verifySource(source);
|
||||||
const captured = await this.runner.run(
|
const captured = await this.runner.run(
|
||||||
"lipo",
|
"lipo",
|
||||||
["-detailed_info", this.path],
|
["-detailed_info", this.path],
|
||||||
@@ -53,9 +69,11 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
|||||||
exit_code: captured.value.exitCode,
|
exit_code: captured.value.exitCode,
|
||||||
effects: ["read"],
|
effects: ["read"],
|
||||||
};
|
};
|
||||||
const fileSize = (await stat(this.path)).size;
|
await this.#verifySource(source);
|
||||||
|
const fileSize = source.initial.size;
|
||||||
const architectures = parseLipoArchitectures(captured.value.stdout);
|
const architectures = parseLipoArchitectures(captured.value.stdout);
|
||||||
const structural = await readStructuralSlices(this.path, fileSize);
|
const structural = await readStructuralSlices(source.handle, fileSize);
|
||||||
|
await this.#verifySource(source);
|
||||||
if (structural.status === "malformed")
|
if (structural.status === "malformed")
|
||||||
throw new ArtifactReaderFailure(
|
throw new ArtifactReaderFailure(
|
||||||
"integrity",
|
"integrity",
|
||||||
@@ -168,22 +186,28 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
|||||||
"integrity",
|
"integrity",
|
||||||
"Invalid Mach-O slice byte range",
|
"Invalid Mach-O slice byte range",
|
||||||
);
|
);
|
||||||
const fileSize = (await stat(this.path)).size;
|
const source = await this.#ensureSource();
|
||||||
if (!Number.isSafeInteger(offset + size) || offset + size > fileSize)
|
await this.#verifySource(source);
|
||||||
|
if (
|
||||||
|
!Number.isSafeInteger(offset + size) ||
|
||||||
|
offset + size > source.initial.size
|
||||||
|
)
|
||||||
throw new ArtifactReaderFailure(
|
throw new ArtifactReaderFailure(
|
||||||
"integrity",
|
"integrity",
|
||||||
`Mach-O slice range is outside the artifact: ${entry.path}`,
|
`Mach-O slice range is outside the artifact: ${entry.path}`,
|
||||||
);
|
);
|
||||||
const source = createReadStream(this.path, {
|
const sourceStream = source.handle.createReadStream({
|
||||||
start: offset,
|
start: offset,
|
||||||
end: offset + size - 1,
|
end: offset + size - 1,
|
||||||
|
autoClose: false,
|
||||||
...(signal === undefined ? {} : { signal }),
|
...(signal === undefined ? {} : { signal }),
|
||||||
});
|
});
|
||||||
|
const verifySource = () => this.#verifySource(source);
|
||||||
return Readable.from(
|
return Readable.from(
|
||||||
(async function* () {
|
(async function* () {
|
||||||
let observedBytes = 0;
|
let observedBytes = 0;
|
||||||
try {
|
try {
|
||||||
for await (const raw of source) {
|
for await (const raw of sourceStream) {
|
||||||
const chunk = streamChunkToBuffer(raw);
|
const chunk = streamChunkToBuffer(raw);
|
||||||
observedBytes += chunk.byteLength;
|
observedBytes += chunk.byteLength;
|
||||||
if (observedBytes > size)
|
if (observedBytes > size)
|
||||||
@@ -212,6 +236,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
|||||||
"integrity",
|
"integrity",
|
||||||
`Mach-O slice size disagrees with lipo metadata: ${entry.path}`,
|
`Mach-O slice size disagrees with lipo metadata: ${entry.path}`,
|
||||||
);
|
);
|
||||||
|
await verifySource();
|
||||||
})(),
|
})(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -220,28 +245,80 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
|||||||
return this.#command === undefined ? [] : [structuredClone(this.#command)];
|
return this.#command === undefined ? [] : [structuredClone(this.#command)];
|
||||||
}
|
}
|
||||||
|
|
||||||
close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
return Promise.resolve();
|
this.#closed = true;
|
||||||
|
this.#closePromise ??= this.#closeSource().catch((cause: unknown) => {
|
||||||
|
this.#closePromise = undefined;
|
||||||
|
throw cause;
|
||||||
|
});
|
||||||
|
return this.#closePromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
async #ensureSource(): Promise<StableRegularFileDescriptor> {
|
||||||
|
if (this.#closed)
|
||||||
|
throw new ArtifactReaderFailure(
|
||||||
|
"unavailable",
|
||||||
|
"Universal Mach-O reader is closed",
|
||||||
|
);
|
||||||
|
if (this.#source !== undefined) return this.#source;
|
||||||
|
this.#pendingSource ??= this.#acquireSource();
|
||||||
|
const source = await this.#pendingSource;
|
||||||
|
if (this.#closed)
|
||||||
|
throw new ArtifactReaderFailure(
|
||||||
|
"unavailable",
|
||||||
|
"Universal Mach-O reader closed during source acquisition",
|
||||||
|
);
|
||||||
|
return source;
|
||||||
|
}
|
||||||
|
|
||||||
|
async #acquireSource(): Promise<StableRegularFileDescriptor> {
|
||||||
|
const handle = await openRegularFile(this.path, { symlinks: "reject" });
|
||||||
|
try {
|
||||||
|
const initial = await handle.stat();
|
||||||
|
const source = { handle, initial };
|
||||||
|
this.#source = source;
|
||||||
|
return source;
|
||||||
|
} catch (cause: unknown) {
|
||||||
|
await handle.close().catch(() => undefined);
|
||||||
|
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();
|
||||||
|
this.#source = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
async #verifySource(source: StableRegularFileDescriptor): Promise<void> {
|
||||||
|
const [opened, currentPath] = await Promise.all([
|
||||||
|
source.handle.stat(),
|
||||||
|
lstat(this.path),
|
||||||
|
]);
|
||||||
|
if (
|
||||||
|
!sameRegularFileState(source.initial, opened) ||
|
||||||
|
!sameRegularFileState(source.initial, currentPath)
|
||||||
|
)
|
||||||
|
throw new ArtifactReaderFailure(
|
||||||
|
"integrity",
|
||||||
|
`Universal Mach-O source changed during inventory: ${this.path}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Compare lipo's independent ranges with structurally parsed slice identity. */
|
/** Compare lipo's independent ranges with structurally parsed slice identity. */
|
||||||
const readStructuralSlices = async (
|
const readStructuralSlices = async (
|
||||||
path: string,
|
file: FileHandle,
|
||||||
size: number,
|
size: number,
|
||||||
): Promise<Awaited<ReturnType<typeof readMachoImage>>> => {
|
): Promise<Awaited<ReturnType<typeof readMachoImage>>> => {
|
||||||
const file = await openFile(path, "r");
|
const readAt: ReadAt = async (offset, length) => {
|
||||||
try {
|
const bytes = Buffer.alloc(length);
|
||||||
const readAt: ReadAt = async (offset, length) => {
|
const { bytesRead } = await file.read(bytes, 0, length, offset);
|
||||||
const bytes = Buffer.alloc(length);
|
return bytes.subarray(0, bytesRead);
|
||||||
const { bytesRead } = await file.read(bytes, 0, length, offset);
|
};
|
||||||
return bytes.subarray(0, bytesRead);
|
return readMachoImage(readAt, size);
|
||||||
};
|
|
||||||
const facts = await readMachoImage(readAt, size);
|
|
||||||
return facts;
|
|
||||||
} finally {
|
|
||||||
await file.close();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const lipoMatchesSlice = (
|
const lipoMatchesSlice = (
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ interface RootClassification {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type RootInventoryClassification = RootClassification & {
|
type RootInventoryClassification = RootClassification & {
|
||||||
readonly zipSource: StableRegularFileDescriptor | undefined;
|
readonly rootSource: StableRegularFileDescriptor | undefined;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Classify and hash one file root through the same stable open descriptor. */
|
/** Classify and hash one file root through the same stable open descriptor. */
|
||||||
@@ -43,7 +43,7 @@ export const classifyAndHashRoot = async (
|
|||||||
try {
|
try {
|
||||||
return { format: result.format, digest: result.digest };
|
return { format: result.format, digest: result.digest };
|
||||||
} finally {
|
} finally {
|
||||||
await result.zipSource?.handle.close();
|
await result.rootSource?.handle.close();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -55,7 +55,7 @@ export const classifyAndHashRootForInventory = async (
|
|||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
): Promise<RootInventoryClassification> => {
|
): Promise<RootInventoryClassification> => {
|
||||||
if (directory)
|
if (directory)
|
||||||
return { format: "directory", digest: null, zipSource: undefined };
|
return { format: "directory", digest: null, rootSource: undefined };
|
||||||
const handle = await openRootFile(path, signal);
|
const handle = await openRootFile(path, signal);
|
||||||
let transferHandle = false;
|
let transferHandle = false;
|
||||||
try {
|
try {
|
||||||
@@ -72,12 +72,12 @@ export const classifyAndHashRootForInventory = async (
|
|||||||
initial,
|
initial,
|
||||||
signal,
|
signal,
|
||||||
);
|
);
|
||||||
const zipSource = isZipFormat(format);
|
const retainSource = isZipFormat(format) || format === "mach-o-universal";
|
||||||
if (zipSource) transferHandle = true;
|
if (retainSource) transferHandle = true;
|
||||||
return {
|
return {
|
||||||
format,
|
format,
|
||||||
digest,
|
digest,
|
||||||
zipSource: zipSource ? { handle, initial } : undefined,
|
rootSource: retainSource ? { handle, initial } : undefined,
|
||||||
};
|
};
|
||||||
} finally {
|
} finally {
|
||||||
if (!transferHandle) await handle.close();
|
if (!transferHandle) await handle.close();
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ export const createReader = async (
|
|||||||
format: ArtifactOccurrence["artifact_format"],
|
format: ArtifactOccurrence["artifact_format"],
|
||||||
environment: Readonly<NodeJS.ProcessEnv>,
|
environment: Readonly<NodeJS.ProcessEnv>,
|
||||||
signal?: AbortSignal,
|
signal?: AbortSignal,
|
||||||
zipSource?: StableRegularFileDescriptor,
|
rootSource?: StableRegularFileDescriptor,
|
||||||
): Promise<ArtifactReader | undefined> => {
|
): Promise<ArtifactReader | undefined> => {
|
||||||
switch (format) {
|
switch (format) {
|
||||||
case "directory":
|
case "directory":
|
||||||
@@ -23,12 +23,12 @@ export const createReader = async (
|
|||||||
case "apk":
|
case "apk":
|
||||||
case "msix":
|
case "msix":
|
||||||
case "appx":
|
case "appx":
|
||||||
return new ZipArtifactReader(path, format, undefined, zipSource);
|
return new ZipArtifactReader(path, format, undefined, rootSource);
|
||||||
case "asar":
|
case "asar":
|
||||||
return new AsarArtifactReader(path);
|
return new AsarArtifactReader(path);
|
||||||
case "mach-o-universal":
|
case "mach-o-universal":
|
||||||
return process.platform === "darwin"
|
return process.platform === "darwin"
|
||||||
? new MachOSliceArtifactReader(path, environment)
|
? new MachOSliceArtifactReader(path, environment, undefined, rootSource)
|
||||||
: undefined;
|
: undefined;
|
||||||
case "dmg":
|
case "dmg":
|
||||||
if (process.platform !== "darwin") return undefined;
|
if (process.platform !== "darwin") return undefined;
|
||||||
|
|||||||
@@ -58,7 +58,7 @@ export const scanCanonicalArtifactInventory = async (
|
|||||||
const {
|
const {
|
||||||
format: rootFormat,
|
format: rootFormat,
|
||||||
digest: rootDigest,
|
digest: rootDigest,
|
||||||
zipSource,
|
rootSource,
|
||||||
} = await classifyAndHashRootForInventory(
|
} = await classifyAndHashRootForInventory(
|
||||||
path,
|
path,
|
||||||
metadata.isDirectory(),
|
metadata.isDirectory(),
|
||||||
@@ -73,7 +73,7 @@ export const scanCanonicalArtifactInventory = async (
|
|||||||
rootFormat,
|
rootFormat,
|
||||||
options.environment ?? {},
|
options.environment ?? {},
|
||||||
options.signal,
|
options.signal,
|
||||||
zipSource,
|
rootSource,
|
||||||
);
|
);
|
||||||
} catch (cause: unknown) {
|
} catch (cause: unknown) {
|
||||||
readerCreationFailure = { cause };
|
readerCreationFailure = { cause };
|
||||||
@@ -102,7 +102,7 @@ export const scanCanonicalArtifactInventory = async (
|
|||||||
metadata,
|
metadata,
|
||||||
rootFormat,
|
rootFormat,
|
||||||
rootDigest,
|
rootDigest,
|
||||||
zipSource,
|
rootSource,
|
||||||
reader,
|
reader,
|
||||||
signal: options.signal,
|
signal: options.signal,
|
||||||
nodes,
|
nodes,
|
||||||
@@ -133,13 +133,13 @@ export const scanCanonicalArtifactInventory = async (
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (zipSource !== undefined) {
|
if (rootSource !== undefined) {
|
||||||
try {
|
try {
|
||||||
await zipSource.handle.close();
|
await rootSource.handle.close();
|
||||||
} catch (cleanupCause: unknown) {
|
} catch (cleanupCause: unknown) {
|
||||||
const cleanup = ArtifactReaderFailure.cleanupObservation(
|
const cleanup = ArtifactReaderFailure.cleanupObservation(
|
||||||
cleanupCause,
|
cleanupCause,
|
||||||
`root ZIP descriptor for ${path}`,
|
`root artifact descriptor for ${path}`,
|
||||||
);
|
);
|
||||||
cleanupFailure = ArtifactReaderFailure.withCleanup(
|
cleanupFailure = ArtifactReaderFailure.withCleanup(
|
||||||
cleanupFailure ??
|
cleanupFailure ??
|
||||||
@@ -161,7 +161,7 @@ interface SnapshotBuildInput {
|
|||||||
readonly metadata: Stats;
|
readonly metadata: Stats;
|
||||||
readonly rootFormat: ArtifactOccurrence["artifact_format"];
|
readonly rootFormat: ArtifactOccurrence["artifact_format"];
|
||||||
readonly rootDigest: HashResult | null;
|
readonly rootDigest: HashResult | null;
|
||||||
readonly zipSource: StableRegularFileDescriptor | undefined;
|
readonly rootSource: StableRegularFileDescriptor | undefined;
|
||||||
readonly reader: ArtifactReader | undefined;
|
readonly reader: ArtifactReader | undefined;
|
||||||
readonly signal: AbortSignal | undefined;
|
readonly signal: AbortSignal | undefined;
|
||||||
readonly nodes: Map<string, ArtifactNode>;
|
readonly nodes: Map<string, ArtifactNode>;
|
||||||
@@ -173,7 +173,7 @@ interface SnapshotBuildInput {
|
|||||||
const buildInventorySnapshot = async (
|
const buildInventorySnapshot = async (
|
||||||
input: SnapshotBuildInput,
|
input: SnapshotBuildInput,
|
||||||
): Promise<ArtifactInventorySnapshot> => {
|
): Promise<ArtifactInventorySnapshot> => {
|
||||||
const { path, metadata, rootFormat, rootDigest, zipSource, reader, signal } =
|
const { path, metadata, rootFormat, rootDigest, rootSource, reader, signal } =
|
||||||
input;
|
input;
|
||||||
materializeDirectoryNodes(input.occurrences, input.nodes);
|
materializeDirectoryNodes(input.occurrences, input.nodes);
|
||||||
const rootNode = createRootNode({
|
const rootNode = createRootNode({
|
||||||
@@ -218,7 +218,7 @@ const buildInventorySnapshot = async (
|
|||||||
ordinal,
|
ordinal,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
await verifyRootDigest(path, rootDigest, zipSource, signal);
|
await verifyRootDigest(path, rootDigest, rootSource, signal);
|
||||||
|
|
||||||
const graphSha256 = artifactGraphDigest({
|
const graphSha256 = artifactGraphDigest({
|
||||||
nodes: orderedNodes,
|
nodes: orderedNodes,
|
||||||
@@ -293,17 +293,17 @@ const buildIntegrityContradictions = (
|
|||||||
const verifyRootDigest = async (
|
const verifyRootDigest = async (
|
||||||
path: string,
|
path: string,
|
||||||
rootDigest: HashResult | null,
|
rootDigest: HashResult | null,
|
||||||
zipSource: StableRegularFileDescriptor | undefined,
|
rootSource: StableRegularFileDescriptor | undefined,
|
||||||
signal: AbortSignal | undefined,
|
signal: AbortSignal | undefined,
|
||||||
): Promise<void> => {
|
): Promise<void> => {
|
||||||
if (rootDigest === null) return;
|
if (rootDigest === null) return;
|
||||||
const verified =
|
const verified =
|
||||||
zipSource === undefined
|
rootSource === undefined
|
||||||
? await hashStableRootArtifact(path, signal)
|
? await hashStableRootArtifact(path, signal)
|
||||||
: await hashStableRootArtifactHandle(
|
: await hashStableRootArtifactHandle(
|
||||||
path,
|
path,
|
||||||
zipSource.handle,
|
rootSource.handle,
|
||||||
zipSource.initial,
|
rootSource.initial,
|
||||||
signal,
|
signal,
|
||||||
);
|
);
|
||||||
if (
|
if (
|
||||||
|
|||||||
Reference in New Issue
Block a user