refactor!: enforce canonical evidence and provider boundaries

Deliver complete Evidence directly through MCP with required nullable analysis profiles and immutable per-server delivery settings. Bind selected environments at construction and require typed cleanup outcomes with retained retry ownership.

Remove test-only routing, duplicate session and snapshot metadata, producer-field repairs, and ambiguous provider arguments. Separate artifact byte identity from occurrence classification and retain typed source-map and partial native facts across CLI, MCP, and verifier consumers.

BREAKING CHANGE: obsolete Evidence envelopes, session aliases, incomplete snapshots, and missing normalized producer facts are no longer accepted.
This commit is contained in:
morluto
2026-10-09 20:18:52 +08:00
parent 2a7746998d
commit 63bf91405c
514 changed files with 9296 additions and 5825 deletions
+16 -6
View File
@@ -1,3 +1,4 @@
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -30,7 +31,7 @@ import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js";
import { err, ok } from "../domain/result.js";
import { err, ok, type Result } from "../domain/result.js";
import { ArtifactReaderFailure } from "./ArtifactReader.js";
import {
ARTIFACT_PROVIDER_IDENTITY as IDENTITY,
@@ -44,8 +45,13 @@ import { resolveArtifactIntegrityPolicy } from "./inventory/policy.js";
export class ArtifactProvider implements AnalysisProvider {
readonly #capabilities: readonly CapabilityDescriptor[];
readonly #platform: NodeJS.Platform;
private readonly environment: Readonly<NodeJS.ProcessEnv>;
constructor(platform: NodeJS.Platform = process.platform) {
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
platform: NodeJS.Platform = process.platform,
) {
this.environment = snapshotEnvironment(environment, platform);
this.#capabilities = artifactCapabilities(platform);
this.#platform = platform;
}
@@ -59,13 +65,14 @@ export class ArtifactProvider implements AnalysisProvider {
}
createClient(target: BinaryTarget): AnalysisClient {
return new ArtifactClient(target, this.#platform);
return new ArtifactClient(target, this.environment, this.#platform);
}
}
class ArtifactClient implements AnalysisClient {
constructor(
private readonly target: BinaryTarget,
private readonly environment: Readonly<NodeJS.ProcessEnv>,
private readonly platform: NodeJS.Platform,
) {}
@@ -178,6 +185,7 @@ class ArtifactClient implements AnalysisClient {
inputPath: this.target.sourcePath ?? this.target.path,
inputFormat: this.target.format,
outputRoot: parsed.output_root,
environment: this.environment,
},
options?.signal,
);
@@ -217,8 +225,8 @@ class ArtifactClient implements AnalysisClient {
}
}
close(): Promise<void> {
return Promise.resolve();
close(): Promise<Result<null, AnalysisError>> {
return Promise.resolve(ok(null));
}
/** The active target's kind is outside this operation's supported targets. */
@@ -248,6 +256,7 @@ class ArtifactClient implements AnalysisClient {
"inspect_asset_catalog requires an active .app bundle target",
);
const result = await analyzeAppleAssetCatalogs({
environment: this.environment,
bundlePath,
targetSha256: this.target.sha256,
page: parameters,
@@ -353,6 +362,7 @@ class ArtifactClient implements AnalysisClient {
options?: ExecutionOptions,
) {
return inventoryArtifact(this.target.sourcePath ?? this.target.path, {
environment: this.environment,
...(options?.signal === undefined ? {} : { signal: options.signal }),
integrity: resolveArtifactIntegrityPolicy({
mode: parsed.integrity_policy,
@@ -393,7 +403,7 @@ const subjectFor = (
path: string,
manifest: {
readonly root_sha256: string;
readonly root_format: import("../domain/artifactGraph.js").ArtifactNode["format"];
readonly root_format: import("../domain/artifactGraph.js").ArtifactInventoryResult["manifest"]["root_format"];
},
) => ({
path,
+3 -1
View File
@@ -3,6 +3,8 @@ import { lstat, open, opendir, realpath } from "node:fs/promises";
import { isAbsolute, join, relative, sep } from "node:path";
import type { Readable } from "node:stream";
import { compareCodePoints } from "../domain/canonicalOrdering.js";
import {
ArtifactReaderFailure,
type ArtifactEntry,
@@ -47,7 +49,7 @@ export class DirectoryArtifactReader implements ArtifactReader {
await withDirectoryIoContext("inspect directory", directory, () =>
assertContainedDirectory(root, directory),
);
children.sort((left, right) => left.localeCompare(right, "en"));
children.sort(compareCodePoints);
const directories: string[] = [];
for (const name of children) {
abortIfNeeded(signal);
@@ -23,7 +23,7 @@ describe("Mach-O slice reader with system lipo", () => {
it.skipIf(process.platform !== "darwin")(
"checks real /bin/ls lipo CPU symbols and ptrauth capabilities against the FAT table",
async () => {
const reader = new MachOSliceArtifactReader("/bin/ls");
const reader = new MachOSliceArtifactReader("/bin/ls", {});
const entries = [];
for await (const entry of reader.entries()) entries.push(entry);
expect(entries.map(({ path }) => path)).toEqual([
+4 -1
View File
@@ -27,7 +27,10 @@ export class MachOSliceArtifactReader implements ArtifactReader {
constructor(
private readonly path: string,
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
environment: Readonly<NodeJS.ProcessEnv>,
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(
environment,
),
) {}
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
+16 -8
View File
@@ -21,6 +21,8 @@ const DETACH_TIMEOUT_MS = 120_000;
* briefly, and a volume can report busy just after it was read.
*/
const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const;
const delay = (milliseconds: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, milliseconds));
const attachOutputSchema = z.object({
"system-entities": z.array(
z.object({
@@ -53,15 +55,17 @@ export interface NativeDmgHost {
delay?(milliseconds: number): Promise<void>;
}
const systemHost: NativeDmgHost = {
delay: (milliseconds) =>
new Promise((resolve) => setTimeout(resolve, milliseconds)),
const createSystemHost = (
environment: Readonly<NodeJS.ProcessEnv>,
): NativeDmgHost => ({
delay,
async run(arguments_, signal, options) {
try {
const { stdout, stderr } = await execFileOutput(
"/usr/bin/hdiutil",
[...arguments_],
{
env: environment,
...(options === undefined ? {} : { timeout: options.timeoutMs }),
...(signal === undefined ? {} : { signal }),
},
@@ -85,7 +89,7 @@ const systemHost: NativeDmgHost = {
);
}
},
};
});
/** Read-only macOS DMG adapter that owns attachment and reverse-order detach. */
export class NativeDmgArtifactReader implements ArtifactReader {
@@ -103,15 +107,19 @@ export class NativeDmgArtifactReader implements ArtifactReader {
/** Verify and attach one image beneath an exclusively owned temporary root. */
static async create(
path: string,
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
host: NativeDmgHost = systemHost,
host?: NativeDmgHost,
): Promise<NativeDmgArtifactReader> {
if (process.platform !== "darwin" && host === systemHost)
if (process.platform !== "darwin" && host === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Native DMG traversal is available only on macOS",
);
const reader = new NativeDmgArtifactReader(path, host);
const reader = new NativeDmgArtifactReader(
path,
host ?? createSystemHost(environment),
);
await reader.attach(signal);
return reader;
}
@@ -152,7 +160,7 @@ export class NativeDmgArtifactReader implements ArtifactReader {
// Only a device that stays attached through every recheck is a failure.
for (const delayMs of DETACH_SETTLE_DELAYS_MS) {
if (remainingDevices.length === 0) break;
await (this.host.delay ?? systemHost.delay)?.(delayMs);
await (this.host.delay ?? delay)(delayMs);
const stillAttached: string[] = [];
for (const device of remainingDevices) {
if (!(await this.#isAttached(device))) continue;
@@ -54,6 +54,7 @@ describe("Apple asset catalog application workflow", () => {
await mkdir(join(bundle, "Contents", "Resources"), { recursive: true });
await writeFile(join(bundle, "Contents", "Resources", "icon.icns"), "");
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () => {
@@ -80,6 +81,7 @@ describe("Apple asset catalog application workflow", () => {
await writeFile(join(bundle, "outside.car"), "catalog");
await symlink("../../outside.car", join(resources, "Assets.car"));
const rejected = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () => Promise.resolve("[]"),
@@ -100,6 +102,7 @@ describe("Apple asset catalog application workflow", () => {
await writeFile(join(resources, "Assets.car"), "catalog");
await symlink("../Assets.car", join(resources, "Nested", "Assets.car"));
const result = await analyzeAppleAssetCatalogs({
environment: {},
bundlePath: bundle,
targetSha256: "a".repeat(64),
runAssetUtil: () => Promise.resolve("[]"),
@@ -29,6 +29,7 @@ const RESOURCE_KEY_FIELDS = new Set([
export const analyzeAppleAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly page?: unknown;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
@@ -60,7 +61,9 @@ export const analyzeAppleAssetCatalogs = async (input: {
const inspected = await inspectAssetCatalogEntry({
reader,
entry,
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
runAssetUtil:
input.runAssetUtil ??
((path, signal) => runAssetUtil(path, input.environment, signal)),
...(input.signal === undefined ? {} : { signal: input.signal }),
});
totalMetadataBytes += inspected.metadataBytes;
@@ -222,11 +225,13 @@ export const collectInterfaceBuilderResourceKeys = (
const runAssetUtil = async (
path: string,
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
): Promise<string> => {
try {
return (
await execFileOutput(ASSETUTIL, ["--info", path], {
env: environment,
timeout: 60_000,
maxBuffer: MAX_CATALOG_BYTES,
...(signal === undefined ? {} : { signal }),
@@ -32,6 +32,7 @@ export interface ArtifactExtractionInput {
readonly inputPath: string;
readonly inputFormat: BinaryTarget["format"];
readonly outputRoot: string;
readonly environment: Readonly<NodeJS.ProcessEnv>;
}
/** Extract every regular inventory occurrence into an exclusively owned absent root. */
@@ -45,6 +46,7 @@ export const extractArtifact = async (
await requireExtractableFormat(sourcePath, input);
const snapshot = await scanArtifactInventory(sourcePath, {
signal,
environment: input.environment,
});
const selectedOccurrences = snapshot.occurrences.filter(
(occurrence) =>
@@ -286,14 +288,17 @@ const requireExtractableFormat = async (
const createReader = async (
path: string,
input: Pick<ArtifactExtractionInput, "inputPath" | "inputFormat">,
input: Pick<
ArtifactExtractionInput,
"inputPath" | "inputFormat" | "environment"
>,
): Promise<ArtifactReader> => {
const format = input.inputFormat;
if (await requireExtractableFormat(path, input))
return new DirectoryArtifactReader(path);
if (format === "asar") return new AsarArtifactReader(path);
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
return new MachOSliceArtifactReader(path);
return new MachOSliceArtifactReader(path, input.environment);
};
const preflight = (entry: ArtifactEntry): void => {
@@ -1,3 +1,4 @@
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import { canonicalDigest } from "../../domain/comparisonSemantics.js";
import {
artifactEdgeId,
@@ -11,7 +12,10 @@ import type {
ArtifactNode,
ArtifactOccurrence,
} from "../../domain/artifactGraph.js";
import { zipPackageFormatForPath } from "../../domain/zipPackageFormat.js";
import {
hasZipSignature,
zipPackageFormatForPath,
} from "../../domain/zipPackageFormat.js";
import { mzWindowsHeaderOffset, parseDosMzHeader } from "../../domain/dosMz.js";
/** Mutable internal occurrence used until root-bound IDs are known. */
@@ -21,6 +25,8 @@ export interface MutableOccurrence {
parent_occurrence_id: string | null;
logical_path: string;
entry_kind: ArtifactOccurrence["entry_kind"];
artifact_kind: ArtifactOccurrence["artifact_kind"];
artifact_format: ArtifactOccurrence["artifact_format"];
declared_size: number | null;
compressed_size: number | null;
executable: boolean;
@@ -51,6 +57,16 @@ export const createOccurrence = (
parent_occurrence_id: parent,
logical_path: path,
entry_kind: entry.kind,
artifact_kind:
entry.kind === "directory"
? path.toLowerCase().endsWith(".framework")
? "framework"
: "container"
: classifyArtifactPath(path).kind,
artifact_format:
entry.kind === "directory"
? "directory"
: classifyArtifactPath(path).format,
declared_size: entry.declaredSize,
compressed_size: entry.compressedSize,
executable: entry.executable,
@@ -63,16 +79,8 @@ export const createOccurrence = (
limitations: [...entry.limitations],
});
/** Preserve collation order and break distinct-name ties by UTF-16 code units. */
export const compareDirectoryChildNames = (
left: string,
right: string,
): number => {
const collated = left.localeCompare(right);
if (collated !== 0) return collated;
if (left < right) return -1;
return left > right ? 1 : 0;
};
/** Compare exact child names independently of host locale and traversal order. */
export const compareDirectoryChildNames = compareCodePoints;
export const materializeDirectoryNodes = (
occurrences: MutableOccurrence[],
@@ -103,28 +111,21 @@ export const materializeDirectoryNodes = (
const node = createArtifactNode({
sha256: canonicalDigest({ kind: "directory", children }, "Artifact"),
size: 0,
kind: directory.logical_path.toLowerCase().endsWith(".framework")
? "framework"
: "container",
format: "directory",
executable: false,
contentState: "virtual",
});
const existing = nodes.get(node.artifact_id);
nodes.set(
node.artifact_id,
existing?.kind === "framework" ? existing : node,
);
nodes.set(node.artifact_id, node);
directory.artifact_id = node.artifact_id;
directory.hash_status = "verified";
}
};
export const createRootNode = (input: {
readonly path: string;
readonly format: ArtifactNode["format"];
readonly directory: boolean;
readonly digest: { readonly sha256: string; readonly bytes: number } | null;
readonly digest: {
readonly sha256: string;
readonly bytes: number;
readonly prefix: Buffer;
} | null;
readonly occurrences: readonly MutableOccurrence[];
}): ArtifactNode =>
createArtifactNode({
@@ -133,65 +134,70 @@ export const createRootNode = (input: {
canonicalDigest(
{
kind: "directory-root",
children: input.occurrences.map(({ logical_path, artifact_id }) => ({
logical_path,
artifact_id,
})),
children: input.occurrences
.map(({ logical_path, artifact_id }) => ({
logical_path,
artifact_id,
}))
.sort((left, right) =>
compareDirectoryChildNames(left.logical_path, right.logical_path),
),
},
"Artifact",
),
size: input.digest?.bytes ?? 0,
kind:
input.directory ||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(
input.format,
)
? "container"
: input.format === "dos-mz"
? "executable"
: classifyArtifactPath(input.path).kind,
format: input.format,
executable: false,
format:
input.digest === null
? "directory"
: classifyArtifactBytes(input.digest.prefix, input.digest.bytes),
contentState: "materialized",
});
export const createArtifactNode = (input: {
readonly sha256: string;
readonly size: number;
readonly kind: ArtifactNode["kind"];
readonly format: ArtifactNode["format"];
readonly executable: boolean;
readonly contentState: ArtifactNode["content_state"];
readonly limitations?: readonly string[];
}): ArtifactNode => ({
artifact_id: artifactIdForContent(input.sha256),
kind: input.kind,
format: input.format,
sha256: input.sha256,
size: input.size,
media_type: null,
architecture: null,
executable: input.executable,
content_state: input.contentState,
limitations: [...(input.limitations ?? [])],
limitations: [],
});
export const rootOccurrenceFor = (
node: ArtifactNode,
declaredSize: number,
metadata: {
readonly size: number;
readonly executable: boolean;
readonly format: ArtifactOccurrence["artifact_format"];
readonly path: string;
},
): MutableOccurrence => ({
occurrence_id: occurrenceIdForLocation({
rootArtifactId: node.artifact_id,
logicalPath: ".",
entryKind: node.format === "directory" ? "directory" : "file",
entryKind: metadata.format === "directory" ? "directory" : "file",
}),
artifact_id: node.artifact_id,
parent_occurrence_id: null,
logical_path: ".",
entry_kind: node.format === "directory" ? "directory" : "file",
declared_size: declaredSize,
entry_kind: metadata.format === "directory" ? "directory" : "file",
artifact_kind:
metadata.format === "directory" ||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(
metadata.format,
)
? "container"
: artifactRoleForFormat(metadata.path, metadata.format).kind,
artifact_format: metadata.format,
declared_size: metadata.size,
compressed_size: null,
executable: node.executable,
executable: metadata.executable,
encrypted: false,
hash_status: "verified",
source_location: null,
@@ -284,7 +290,10 @@ export const nearestParent = (
export const classifyArtifactPath = (
path: string,
): Pick<ArtifactNode, "kind" | "format"> => {
): {
readonly kind: ArtifactOccurrence["artifact_kind"];
readonly format: ArtifactOccurrence["artifact_format"];
} => {
const lower = path.toLowerCase();
if (lower.endsWith(".map"))
return { kind: "source-map", format: "source-map" };
@@ -312,29 +321,49 @@ export const classifyArtifactContent = (
path: string,
prefix: Buffer,
fileSize = prefix.length,
): Pick<ArtifactNode, "kind" | "format"> => {
): {
readonly kind: ArtifactOccurrence["artifact_kind"];
readonly format: ArtifactOccurrence["artifact_format"];
} => {
return artifactRoleForFormat(path, classifyArtifactBytes(prefix, fileSize));
};
const artifactRoleForFormat = (
path: string,
format: ArtifactOccurrence["artifact_format"],
): ReturnType<typeof classifyArtifactPath> => {
const byPath = classifyArtifactPath(path);
if (format === "file" || format === byPath.format) return byPath;
if (format === "unknown") return { kind: "unknown", format };
if (format === "zip")
return {
kind: "container",
format: zipPackageFormatForPath(path) ?? format,
};
if (format === "plist") return { kind: "plist", format };
return {
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
? byPath.kind
: ("executable" as const),
format,
};
};
/** Classify storage bytes independently of path names, roles, and permissions. */
export const classifyArtifactBytes = (
prefix: Buffer,
fileSize = prefix.length,
): ArtifactNode["format"] => {
if (hasZipSignature(prefix)) return "zip";
if (prefix.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist";
if (prefix.length >= 4) {
const magic = prefix.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return {
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
format: "mach-o-universal",
};
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return {
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
? byPath.kind
: "executable",
format: "mach-o",
};
return "mach-o";
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
return {
kind: ["native-addon", "dynamic-library"].includes(byPath.kind)
? byPath.kind
: "executable",
format: "elf",
};
return "elf";
}
if (prefix.length >= 2 && prefix[0] === 0x4d && prefix[1] === 0x5a) {
if (
@@ -342,7 +371,7 @@ export const classifyArtifactContent = (
fileSize < prefix.length ||
prefix.length < Math.min(fileSize, 64)
)
return { kind: "unknown", format: "unknown" };
return "unknown";
const windowsOffset = mzWindowsHeaderOffset(prefix);
if (windowsOffset !== null) {
if (
@@ -352,17 +381,11 @@ export const classifyArtifactContent = (
.subarray(windowsOffset, windowsOffset + 4)
.equals(Buffer.from([0x50, 0x45, 0, 0]))
)
return {
kind: byPath.kind === "native-addon" ? "native-addon" : "executable",
format: "pe",
};
} else if (parseDosMzHeader(prefix, fileSize).ok) {
return { kind: "executable", format: "dos-mz" };
}
// Missing bounded evidence and malformed MZ bytes both remain unclassified.
return { kind: "unknown", format: "unknown" };
return "pe";
} else if (parseDosMzHeader(prefix, fileSize).ok) return "dos-mz";
return "unknown";
}
return byPath;
return "file";
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
+1 -5
View File
@@ -7,7 +7,6 @@ import {
import { abortIfNeeded } from "../ArtifactHash.js";
import { scanCanonicalArtifactInventory } from "./scanCanonical.js";
import type {
ArtifactIntegrityPolicy,
ArtifactInventoryOptions,
ArtifactInventorySnapshot,
} from "./types.js";
@@ -23,10 +22,7 @@ export type {
/** Inventory one local artifact and return every graph collection inline. */
export const inventoryArtifact = async (
inputPath: string,
options: {
readonly signal?: AbortSignal;
readonly integrity?: ArtifactIntegrityPolicy;
} = {},
options: ArtifactInventoryOptions = {},
): Promise<ArtifactInventoryResult> => {
const snapshot = await scanArtifactInventory(inputPath, options);
return artifactInventoryResultSchema.parse(snapshot);
@@ -0,0 +1,132 @@
import { chmod, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
import { describe, expect, it } from "vitest";
import { inventoryArtifact } from "./ArtifactInventory.js";
import { compareArtifacts } from "../../domain/artifactComparison.js";
import { createEvidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
const names = ["main.js", "payload.bin", "addon.node"];
const observeArchive = async (order: readonly string[]) => {
const directory = await createTestTempDirectory("rea-occurrence-identity-");
const path = join(directory, "fixture.zip");
const writer = new ZipWriter(new Uint8ArrayWriter());
for (const name of order)
await writer.add(name, new TextReader("same content\n"), {
lastModDate: new Date("2020-01-01T00:00:00Z"),
executable: name === "addon.node",
});
await writeFile(path, await writer.close());
const inventory = await inventoryArtifact(path);
const evidence = createEvidence(
{ path, sha256: inventory.manifest.root_sha256, format: "zip" },
{ id: "rea-artifact-graph", name: "artifact inventory", version: "1" },
{
operation: "inventory_artifact",
parameters: {},
result: jsonValueSchema.parse(inventory),
confidence: "observed",
authority: "shipped-artifact",
},
);
return { inventory, evidence };
};
describe("content identity and occurrence facts", () => {
it("retains all roles and permissions for identical bytes in either archive order", async () => {
const left = await observeArchive(names);
const right = await observeArchive([...names].reverse());
const childNodes = (inventory: typeof left.inventory) =>
inventory.nodes.filter(
(node) => node.artifact_id !== inventory.manifest.root_artifact_id,
);
expect(childNodes(left.inventory)).toEqual(childNodes(right.inventory));
expect(childNodes(left.inventory)).toHaveLength(1);
expect(childNodes(left.inventory)[0]).toMatchObject({ format: "file" });
expect(childNodes(left.inventory)[0]).not.toHaveProperty("kind");
expect(childNodes(left.inventory)[0]).not.toHaveProperty("executable");
const occurrences = left.inventory.occurrences.filter(
(item) => item.logical_path !== ".",
);
expect(new Set(occurrences.map((item) => item.artifact_id)).size).toBe(1);
expect(
occurrences.map(
({ logical_path, artifact_kind, artifact_format, executable }) => ({
logical_path,
artifact_kind,
artifact_format,
executable,
}),
),
).toEqual([
{
logical_path: "addon.node",
artifact_kind: "native-addon",
artifact_format: "file",
executable: true,
},
{
logical_path: "main.js",
artifact_kind: "javascript",
artifact_format: "javascript-bundle",
executable: false,
},
{
logical_path: "payload.bin",
artifact_kind: "resource",
artifact_format: "file",
executable: false,
},
]);
expect(
compareArtifacts(left.evidence, right.evidence).changes.map(
(item) => item.logical_path,
),
).toEqual(["."]);
});
it("keeps framework and ordinary directory roles separate for identical trees", async () => {
const root = await createTestTempDirectory("rea-directory-roles-");
for (const name of ["Widget.framework", "resources"])
await mkdir(join(root, name));
const inventory = await inventoryArtifact(root);
const entries = inventory.occurrences.filter(
(item) => item.logical_path !== ".",
);
expect(entries[0]?.artifact_id).toBe(entries[1]?.artifact_id);
expect(entries.map((item) => item.artifact_kind).sort()).toEqual([
"container",
"framework",
]);
expect(
inventory.nodes.filter((node) => node.content_state === "virtual"),
).toHaveLength(1);
});
it("reports only an occurrence permission change for identical content", async () => {
const root = await createTestTempDirectory("rea-permission-identity-");
const path = join(root, "payload.bin");
await writeFile(path, "same content\n", { mode: 0o600 });
const before = await inventoryArtifact(root);
await chmod(path, 0o700);
const after = await inventoryArtifact(root);
expect(before.nodes).toEqual(after.nodes);
expect(before.manifest.root_artifact_id).toBe(
after.manifest.root_artifact_id,
);
const oldFile = before.occurrences.find(
(item) => item.logical_path === "payload.bin",
);
const newFile = after.occurrences.find(
(item) => item.logical_path === "payload.bin",
);
expect(oldFile?.artifact_id).toBe(newFile?.artifact_id);
expect(oldFile?.executable).toBe(false);
expect(newFile?.executable).toBe(true);
});
});
+3 -3
View File
@@ -2,7 +2,7 @@ import { open } from "node:fs/promises";
import { classifyArtifactContent } from "./ArtifactGraphConstruction.js";
import { ARTIFACT_CLASSIFICATION_PREFIX_BYTES } from "../ArtifactHash.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
import {
hasZipSignature,
zipPackageFormatForPath,
@@ -10,7 +10,7 @@ import {
const classifyContainerExtension = (
path: string,
): ArtifactNode["format"] | undefined => {
): ArtifactOccurrence["artifact_format"] | undefined => {
const lower = path.toLowerCase();
const zipPackage = zipPackageFormatForPath(lower);
if (zipPackage !== undefined) return zipPackage;
@@ -22,7 +22,7 @@ const classifyContainerExtension = (
export const classifyRoot = async (
path: string,
directory: boolean,
): Promise<ArtifactNode["format"]> => {
): Promise<ArtifactOccurrence["artifact_format"]> => {
if (directory) return "directory";
const extensionFormat = classifyContainerExtension(path);
if (extensionFormat !== undefined) return extensionFormat;
+6 -5
View File
@@ -4,11 +4,12 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import { NativeDmgArtifactReader } from "../NativeDmgArtifactReader.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
import type { ArtifactOccurrence } from "../../domain/artifactGraph.js";
export const createReader = async (
path: string,
format: ArtifactNode["format"],
format: ArtifactOccurrence["artifact_format"],
environment: Readonly<NodeJS.ProcessEnv>,
signal?: AbortSignal,
): Promise<ArtifactReader | undefined> => {
switch (format) {
@@ -24,18 +25,18 @@ export const createReader = async (
return new AsarArtifactReader(path);
case "mach-o-universal":
return process.platform === "darwin"
? new MachOSliceArtifactReader(path)
? new MachOSliceArtifactReader(path, environment)
: undefined;
case "dmg":
if (process.platform !== "darwin") return undefined;
return NativeDmgArtifactReader.create(path, signal);
return NativeDmgArtifactReader.create(path, environment, signal);
default:
return undefined;
}
};
export const inventoryLimitations = (
format: ArtifactNode["format"],
format: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
): string[] => {
if (reader !== undefined) return [];
+28 -12
View File
@@ -1,3 +1,5 @@
import { compareCodePoints } from "../../domain/canonicalOrdering.js";
import { createReadStream } from "node:fs";
import { lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
@@ -10,6 +12,7 @@ import {
artifactInventoryResultSchema,
type ArtifactInventoryResult,
type ArtifactNode,
type ArtifactOccurrence,
type IntegrityContradiction,
} from "../../domain/artifactGraph.js";
import {
@@ -49,7 +52,12 @@ export const scanCanonicalArtifactInventory = async (
const rootDigest = metadata.isDirectory()
? null
: await hashReadable(createReadStream(path), options.signal);
const reader = await createReader(path, rootFormat, options.signal);
const reader = await createReader(
path,
rootFormat,
options.environment ?? {},
options.signal,
);
try {
const { nodes, occurrences, pendingContradictions } = await scanReader(
@@ -76,7 +84,7 @@ export const scanCanonicalArtifactInventory = async (
interface SnapshotBuildInput {
readonly path: string;
readonly metadata: Stats;
readonly rootFormat: ArtifactNode["format"];
readonly rootFormat: ArtifactOccurrence["artifact_format"];
readonly rootDigest: HashResult | null;
readonly reader: ArtifactReader | undefined;
readonly signal: AbortSignal | undefined;
@@ -91,15 +99,17 @@ const buildInventorySnapshot = async (
const { path, metadata, rootFormat, rootDigest, reader, signal } = input;
materializeDirectoryNodes(input.occurrences, input.nodes);
const rootNode = createRootNode({
path,
format: rootFormat,
directory: metadata.isDirectory(),
digest: rootDigest,
occurrences: input.occurrences,
});
input.nodes.set(rootNode.artifact_id, rootNode);
rekeyOccurrences(rootNode.artifact_id, input.occurrences);
const rootOccurrence = rootOccurrenceFor(rootNode, metadata.size);
const rootOccurrence = rootOccurrenceFor(rootNode, {
size: metadata.size,
executable: (metadata.mode & 0o111) !== 0,
format: rootFormat,
path,
});
for (const occurrence of input.occurrences)
if (occurrence.parent_occurrence_id === null)
occurrence.parent_occurrence_id = rootOccurrence.occurrence_id;
@@ -125,7 +135,10 @@ const buildInventorySnapshot = async (
);
const orderedNodes = sortNodes([...input.nodes.values()]);
const orderedOccurrences = sortOccurrences(input.occurrences);
const orderedEdges = sortEdges(edges);
const orderedEdges = sortEdges(edges).map((edge, ordinal) => ({
...edge,
ordinal,
}));
await verifyRootDigest(path, rootDigest, signal);
@@ -137,6 +150,7 @@ const buildInventorySnapshot = async (
});
const manifest = buildManifest({
rootNode,
rootFormat,
graphSha256,
orderedNodes,
orderedOccurrences,
@@ -212,27 +226,29 @@ const verifyRootDigest = async (
const sortNodes = (nodes: ArtifactNode[]): ArtifactNode[] =>
nodes.sort((left, right) =>
left.artifact_id.localeCompare(right.artifact_id),
compareCodePoints(left.artifact_id, right.artifact_id),
);
const sortOccurrences = (
occurrences: MutableOccurrence[],
): MutableOccurrence[] =>
occurrences.sort((left, right) =>
left.logical_path.localeCompare(right.logical_path, "en"),
compareCodePoints(left.logical_path, right.logical_path),
);
const sortEdges = <T extends { edge_id: string }>(edges: T[]): T[] =>
edges.sort((left, right) => left.edge_id.localeCompare(right.edge_id));
edges.sort((left, right) => compareCodePoints(left.edge_id, right.edge_id));
const buildManifest = ({
rootNode,
rootFormat,
graphSha256,
orderedNodes,
orderedOccurrences,
orderedEdges,
}: {
readonly rootNode: ArtifactNode;
readonly rootFormat: ArtifactOccurrence["artifact_format"];
readonly graphSha256: string;
readonly orderedNodes: readonly ArtifactNode[];
readonly orderedOccurrences: readonly unknown[];
@@ -242,7 +258,7 @@ const buildManifest = ({
manifest_id: artifactManifestId(rootNode.artifact_id, graphSha256),
root_artifact_id: rootNode.artifact_id,
root_sha256: rootNode.sha256,
root_format: rootNode.format,
root_format: rootFormat,
graph_sha256: graphSha256,
node_count: orderedNodes.length,
occurrence_count: orderedOccurrences.length,
@@ -250,7 +266,7 @@ const buildManifest = ({
});
const buildLimitations = (
rootFormat: ArtifactNode["format"],
rootFormat: ArtifactOccurrence["artifact_format"],
reader: ArtifactReader | undefined,
integrityContradictions: readonly IntegrityContradiction[],
): string[] => [
+16 -10
View File
@@ -13,6 +13,7 @@ import { AsarArtifactReader } from "../AsarArtifactReader.js";
import type { ArtifactNode } from "../../domain/artifactGraph.js";
import {
classifyArtifactContent,
classifyArtifactBytes,
createArtifactNode,
createOccurrence,
nearestParent,
@@ -130,7 +131,11 @@ const visitArtifactEntries = async (
);
const occurrence = createOccurrence(entry, logicalPath, null);
let digested:
| { readonly node: ArtifactNode; readonly mismatched: boolean }
| {
readonly node: ArtifactNode;
readonly mismatched: boolean;
readonly classification: ReturnType<typeof classifyArtifactContent>;
}
| undefined;
try {
digested = await digestArtifactEntry(
@@ -147,6 +152,8 @@ const visitArtifactEntries = async (
if (digested !== undefined) {
context.nodes.set(digested.node.artifact_id, digested.node);
occurrence.artifact_id = digested.node.artifact_id;
occurrence.artifact_kind = digested.classification.kind;
occurrence.artifact_format = digested.classification.format;
occurrence.hash_status = digested.mismatched
? "mismatched"
: "verified";
@@ -187,7 +194,12 @@ const digestArtifactEntry = async (
entry: ArtifactEntry,
logicalPath: string,
): Promise<
{ readonly node: ArtifactNode; readonly mismatched: boolean } | undefined
| {
readonly node: ArtifactNode;
readonly mismatched: boolean;
readonly classification: ReturnType<typeof classifyArtifactContent>;
}
| undefined
> => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
return undefined;
@@ -226,17 +238,11 @@ const digestArtifactEntry = async (
node: createArtifactNode({
sha256: digest.sha256,
size: digest.bytes,
kind: classified.kind,
format: classified.format,
executable: entry.executable,
format: classifyArtifactBytes(digest.prefix, digest.bytes),
contentState: "embedded",
limitations: mismatched
? [
"Observed content contradicts declared integrity metadata and is untrusted.",
]
: [],
}),
mismatched,
classification: classified,
};
};
+1
View File
@@ -11,6 +11,7 @@ export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
export interface ArtifactInventoryOptions {
readonly signal?: AbortSignal | undefined;
readonly integrity?: ArtifactIntegrityPolicy | undefined;
readonly environment?: Readonly<NodeJS.ProcessEnv> | undefined;
}
export type { ArtifactInventorySnapshot } from "../../domain/artifactInventorySnapshot.js";