feat(native): retain Apple bundle executable provenance

This commit is contained in:
hhang authored and Ysopwnable committed 2026-11-22 15:41:50 +08:00
1 parent c1943f196c
commit b8995f8148
15 files changed
+315 -23

No files matched your search

+13
View File
@@ -1317,6 +1317,19 @@ constraint, and `details.path` names that file. A `.dext`, `.kext`,
resource root reports its `layout` as `contents`, `root`,
`versioned-framework` or `flattened-framework`.
When the caller opens a directory, `inspect_macho` and `inspect_signature`
include `normalized_result.bundle_provenance`. It records the canonical bundle
directory, selected layout, lookup path and SHA-256 of the Info.plist bytes
read during resolution, and the declared executable name. For versioned
frameworks, `version_directory` records where the program directory resolved.
The `framework` object reports the directory's name without `.framework` and
whether it exactly matches the declared name. A mismatch does not override
`CFBundleExecutable`. The Mach-O summary includes these fields under
`summary.bundle_provenance`. The binary is still the Evidence subject.
These facts describe the selection at open time. They do not verify the
bundle's code-signing context or track subsequent changes to its directories.
Direct file selections and older Evidence can omit this object.
`open_bundle_resources` selects a separate read-only app resource session
without resolving `CFBundleExecutable`, including when it is absent or
unresolvable. `binary_session` reports `session_kind: "bundle_resources"` and the
@@ -19,7 +19,7 @@ it("resolves the declared executable from a commented OpenStep Info.plist", asyn
await writeFile(infoPlist, source);
await writeFile(executable, "fixture - never executed");
expect(await resolveAppleBundleExecutable(bundle)).toEqual({
expect(await resolveAppleBundleExecutable(bundle)).toMatchObject({
ok: true,
value: { executable, infoPlist },
});
@@ -40,7 +40,7 @@ it("resolves an OpenStep Info.plist with quoted XML-looking text", async () => {
await writeFile(infoPlist, source);
await writeFile(executable, "fixture - never executed");
expect(await resolveAppleBundleExecutable(bundle)).toEqual({
expect(await resolveAppleBundleExecutable(bundle)).toMatchObject({
ok: true,
value: { executable, infoPlist },
});
+11 -3
View File
@@ -53,9 +53,17 @@ it.each([
await writeFile(executable, "inert fixture; never executed");
const result = await resolveAppleBundleExecutable(bundle);
expect(result).toEqual({
expect(result).toMatchObject({
ok: true,
value: { executable, infoPlist: plistPath },
value: {
executable,
infoPlist: plistPath,
bundleExecutableSelection: {
canonical_path: bundle,
layout: plistDirectory.length === 0 ? "root" : "contents",
declared_executable: "Fixture",
},
},
});
},
);
@@ -94,7 +102,7 @@ describe("app bundle Info.plist magic", () => {
await writeFile(plistPath, binaryPlistExecutableWithThreeByteUid());
await writeFile(executable, "inert fixture; never executed");
expect(await resolveAppleBundleExecutable(bundle)).toEqual({
expect(await resolveAppleBundleExecutable(bundle)).toMatchObject({
ok: true,
value: { executable, infoPlist: plistPath },
});
+30 -2
View File
@@ -1,5 +1,5 @@
import { lstat, opendir, realpath, stat } from "node:fs/promises";
import { extname, join, sep } from "node:path";
import { basename, extname, join, sep } from "node:path";
import { z } from "zod";
@@ -19,6 +19,7 @@ import type {
BundleResourceRoot,
ResolvedAppBundleResourceRoot,
} from "../domain/apple/bundleResourceRoot.js";
import type { BundleExecutableSelection } from "../domain/apple/bundleExecutableProvenance.js";
import {
INFO_PLIST_DECODE_MIB,
openableAppleBundleExtension,
@@ -28,6 +29,7 @@ import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { regularFileCancellation } from "../filesystem/OwnedRegularFile.js";
import type { ArtifactResourceScope } from "../resources/index.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { sha256Hex } from "../kernel/sha256Hex.js";
import {
bindRegularFileCleanup,
@@ -121,6 +123,7 @@ const FLATTENED_FRAMEWORK_LAYOUTS: readonly BundleLayout[] = [
export interface ResolvedAppBundle {
readonly executable: string;
readonly infoPlist?: string;
readonly bundleExecutableSelection?: BundleExecutableSelection;
}
/** Filesystem operations used by the resolver, injectable for boundary tests. */
@@ -659,7 +662,32 @@ const resolveLayoutExecutable = async (
{ constraint: "bundle_path_escapes", probedPaths: [executable] },
),
);
return ok({ executable: canonicalExecutable, infoPlist: plistPath });
const extension = extname(canonicalBundle);
const frameworkName =
extension.toLowerCase() === ".framework"
? basename(canonicalBundle, extension)
: undefined;
return ok({
executable: canonicalExecutable,
infoPlist: plistPath,
bundleExecutableSelection: {
canonical_path: canonicalBundle,
layout: layout.name,
info_plist_sha256: sha256Hex(plist.value),
declared_executable: name,
...(layout.name === "versioned-framework"
? { version_directory: canonicalPrograms }
: {}),
...(frameworkName === undefined
? {}
: {
framework: {
directory_name: frameworkName,
matches_declared_executable: frameworkName === name,
},
}),
},
});
} catch (cause: unknown) {
return err(
new BinaryTargetError(
+13 -3
View File
@@ -203,7 +203,11 @@ export const parseBinaryTarget = async (
const resolved = await resolveAppBundle(canonical, options);
if (!resolved.ok) return resolved;
throwIfTargetResolutionCancelled(signal);
const { executable: path, infoPlist } = resolved.value;
const {
executable: path,
infoPlist,
bundleExecutableSelection,
} = resolved.value;
const bundle =
infoPlist === undefined ? {} : { bundleInfoPlist: infoPlist };
// A bundle directory is selected for its executable, so the executable's
@@ -226,6 +230,9 @@ export const parseBinaryTarget = async (
selectedPath: candidate,
classifiedAs,
...bundle,
...(bundleExecutableSelection === undefined
? {}
: { bundleExecutableSelection }),
},
options,
);
@@ -310,8 +317,7 @@ const readOpenedBinaryTarget = async (
readonly selectedPath: string;
/** Spelling whose name supplies format hints: the selected file, or a bundle's executable. */
readonly classifiedAs: string;
readonly bundleInfoPlist?: string;
},
} & Pick<BinaryTarget, "bundleInfoPlist" | "bundleExecutableSelection">,
options: BinaryTargetResolverOptions,
): Promise<TargetResolution> => {
const { handle, initial: metadata } = source;
@@ -322,6 +328,7 @@ const readOpenedBinaryTarget = async (
selectedPath,
classifiedAs,
bundleInfoPlist,
bundleExecutableSelection,
} = selected;
const bundle = bundleInfoPlist === undefined ? {} : { bundleInfoPlist };
// Every admitted target shares one identity; routes add their own facts.
@@ -330,6 +337,9 @@ const readOpenedBinaryTarget = async (
sourcePath,
...(callerInputPath === path ? {} : { callerInputPath }),
...bundle,
...(bundleExecutableSelection === undefined
? {}
: { bundleExecutableSelection }),
sha256: await sha256Handle(source, path, signal),
});
const hostArchitecture =
+15 -5
View File
@@ -61,16 +61,26 @@ it.skipIf(process.platform === "win32")(
const executable = join(contents, "MacOS", "Hopper");
await mkdir(join(contents, "MacOS"), { recursive: true });
await writeFile(executable, "inert fixture");
await writeFile(
selected,
"<plist><dict><key>CFBundleExecutable</key><string>Hopper</string><key>LSMinimumSystemVersion</key><string>13.0</string></dict></plist>",
);
const plistSource =
"<plist><dict><key>CFBundleExecutable</key><string>Hopper</string><key>LSMinimumSystemVersion</key><string>13.0</string></dict></plist>";
await writeFile(selected, plistSource);
await symlink(selected, plist);
const host = systemMacHopperInstallHost(root, {}, async () => "15.0");
try {
await expect(resolveAppleBundleExecutable(app)).resolves.toEqual({
ok: true,
value: { executable: await realpath(executable), infoPlist: plist },
value: {
executable: await realpath(executable),
infoPlist: plist,
bundleExecutableSelection: {
canonical_path: app,
layout: "contents",
declared_executable: "Hopper",
info_plist_sha256: createHash("sha256")
.update(plistSource)
.digest("hex"),
},
},
});
await expect(host.minimumSystemVersion(app)).resolves.toBe("13.0");
} finally {
+4
View File
@@ -73,6 +73,7 @@ const collectionCountSchema = z.strictObject({
/** Slice identity and per-collection counts without the collections themselves. */
export const machoSummarySchema = z.strictObject({
bundle_provenance: shape.bundle_provenance,
format: shape.format,
selected_architecture: shape.selected_architecture,
endian: shape.endian,
@@ -139,6 +140,9 @@ const summarizeMacho = (
0,
),
summary: {
...(report.bundle_provenance === undefined
? {}
: { bundle_provenance: report.bundle_provenance }),
format: report.format,
selected_architecture: report.selected_architecture,
endian: report.endian,
@@ -0,0 +1,39 @@
import { z } from "zod";
import type { BinaryTarget } from "../binaryTargetTypes.js";
import { digestSchema } from "../digests.js";
import { appleBundleLayoutSchema } from "./bundleResourceRoot.js";
/** Resolution-time observations, separate from the inspected executable identity. */
export const bundleExecutableProvenanceSchema = z.strictObject({
canonical_path: z.string().min(1),
layout: appleBundleLayoutSchema,
info_plist_path: z.string().min(1),
info_plist_sha256: digestSchema,
declared_executable: z.string().min(1),
version_directory: z.string().min(1).exactOptional(),
framework: z
.strictObject({
directory_name: z.string().min(1),
matches_declared_executable: z.boolean(),
})
.exactOptional(),
});
/** The plist lookup path is already carried by BinaryTarget.bundleInfoPlist. */
export type BundleExecutableSelection = Omit<
z.output<typeof bundleExecutableProvenanceSchema>,
"info_plist_path"
>;
/** Explicit files and targets without selection facts have no bundle observation. */
export const bundleExecutableProvenanceFields = (target: BinaryTarget) =>
target.bundleInfoPlist === undefined ||
target.bundleExecutableSelection === undefined
? {}
: {
bundle_provenance: {
...target.bundleExecutableSelection,
info_plist_path: target.bundleInfoPlist,
},
};
+8 -6
View File
@@ -1,16 +1,18 @@
import { z } from "zod";
export const appleBundleLayoutSchema = z.enum([
"contents",
"root",
"versioned-framework",
"flattened-framework",
]);
/** Provenance for app resources, independent of executable file identity. */
export const bundleResourceRootSchema = z.strictObject({
caller_path: z.string().min(1),
canonical_path: z.string().min(1),
info_plist_path: z.string().min(1),
layout: z.enum([
"contents",
"root",
"versioned-framework",
"flattened-framework",
]),
layout: appleBundleLayoutSchema,
executable_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
+3 -1
View File
@@ -1,6 +1,7 @@
import type { AnalysisDatabaseEngine } from "./analysisDatabase.js";
import type { DolHeader } from "./gamecubeDol.js";
import type { TargetFormatsOfKind } from "./targetFormats.js";
import type { BundleExecutableSelection } from "./apple/bundleExecutableProvenance.js";
/** Provider-neutral CPU families detected from headers or explicitly selected raw loads. */
export const BINARY_ARCHITECTURES = [
@@ -181,8 +182,9 @@ interface BinaryTargetIdentity {
readonly callerInputPath?: string;
/** Selected artifact spelling determines name-based format hints and external companions. */
readonly artifactSelectedPath?: string;
/** Info.plist of the app bundle the target was resolved from. */
/** Info.plist of the Apple bundle the target was resolved from. */
readonly bundleInfoPlist?: string;
readonly bundleExecutableSelection?: BundleExecutableSelection;
readonly sha256: string;
}
+3
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { bundleResourceRootSchema } from "../apple/bundleResourceRoot.js";
import { bundleExecutableProvenanceSchema } from "../apple/bundleExecutableProvenance.js";
import { digestSchema } from "../digests.js";
import { jsonRecordSchema } from "../jsonRecord.js";
import { jsonValueSchema } from "../jsonValue.js";
@@ -171,6 +172,7 @@ const buildMetadataSchema = z.object({
});
export const inspectMachoSchema = z.object({
bundle_provenance: bundleExecutableProvenanceSchema.exactOptional(),
format: z.enum(["mach-o", "mach-o-universal"]),
/** Exact lipo slice selected for inspection and its offset in the input container. */
selected_architecture: z.object({
@@ -218,6 +220,7 @@ export const inspectMachoSchema = z.object({
});
export const inspectSignatureSchema = z.object({
bundle_provenance: bundleExecutableProvenanceSchema.exactOptional(),
signed: z.boolean(),
identifier: z.string().nullable(),
team_identifier: z.string().nullable(),
+2
View File
@@ -108,6 +108,7 @@ import type { NativeUiObservationResult } from "../domain/native/nativeUiObserva
import { parseXmlPropertyList } from "../domain/propertyListKeys.js";
import { plistDuplicateKeyLimitations } from "../domain/apple/plistDuplicateKeys.js";
import { machoKnownCodeSignSelector } from "../domain/apple/machoArchitectureSelection.js";
import { bundleExecutableProvenanceFields } from "../domain/apple/bundleExecutableProvenance.js";
import {
demangleSwiftSchema,
inspectPlistSchema,
@@ -983,6 +984,7 @@ class NativeMacOSClient implements AnalysisClient {
const observation = () =>
inspectSignatureSchema.parse({
...parsed,
...bundleExecutableProvenanceFields(this.target),
designated_requirement: requirementText,
entitlements: entitlementValue.value,
slices: {
+5 -1
View File
@@ -1,5 +1,6 @@
import { parseFailureFromCause } from "../domain/parseFailure.js";
import { LC } from "../domain/apple/machoLoadCommandCodes.js";
import { bundleExecutableProvenanceFields } from "../domain/apple/bundleExecutableProvenance.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { EvidenceLocation } from "../domain/evidence.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
@@ -472,7 +473,10 @@ export const inspectNativeMacho = async (
limitations: [...normalized.limitations, ...locationLimitations],
});
return ok({
result: jsonValueSchema.parse(result),
result: jsonValueSchema.parse({
...result,
...bundleExecutableProvenanceFields(context.target),
}),
limitations: result.limitations,
locations: fileOffsetLocations(result, containerOffset, binary.sliceSize),
});
@@ -0,0 +1,158 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { parseEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
const plist =
'<plist version="1.0"><dict><key>CFBundleExecutable</key><string>Other</string></dict></plist>';
const expectMachoSummaryProvenance = async (
cli: TestCli,
framework: string,
root: string,
expected: unknown,
) => {
const destination = join(root, "inspection.json");
const result = await cli.run({
arguments: [
"inspect-macho",
framework,
"--detail",
"summary",
"--evidence_output",
destination,
"--json",
],
});
expect(result.exitCode, result.stderr).toBe(0);
expect(result.json).toMatchObject({
summary: {
normalized_result: { summary: { bundle_provenance: expected } },
},
});
const saved = parseEvidenceBundle(
JSON.parse(await readFile(destination, "utf8")),
);
expect(saved.records).toMatchObject([
{
operation: "inspect_macho",
normalized_result: { bundle_provenance: expected },
},
]);
};
describe.skipIf(process.platform !== "darwin")(
"selected Apple bundle executable provenance",
() => {
cliTest(
"keeps matching CLI and MCP bundle facts while inspecting the declared file",
async ({ cli, processes }) => {
const root = await createTestTempDirectory("rea-bundle-provenance-");
const framework = join(root, "Demo.framework");
const version = join(framework, "Versions", "A");
const executable = join(version, "Other");
const source = join(root, "probe.c");
await mkdir(join(version, "Resources"), { recursive: true });
await symlink("A", join(framework, "Versions", "Current"));
await writeFile(join(version, "Resources", "Info.plist"), plist);
await writeFile(source, "int rea_fixture_value(void) { return 7; }\n");
const compilation = await processes.run("/usr/bin/xcrun", [
"clang",
"-dynamiclib",
source,
"-o",
executable,
]);
expect(compilation.exitCode, compilation.stderr).toBe(0);
const digest = createHash("sha256")
.update(await readFile(executable))
.digest("hex");
const expected = {
canonical_path: framework,
layout: "versioned-framework",
info_plist_path: join(
framework,
"Versions",
"Current",
"Resources",
"Info.plist",
),
info_plist_sha256: createHash("sha256").update(plist).digest("hex"),
declared_executable: "Other",
version_directory: version,
framework: {
directory_name: "Demo",
matches_declared_executable: false,
},
};
const environment = { HOME: root, REA_LOG_LEVEL: "silent" };
const inspect = async (command: string, path: string) => {
const result = await cli.run({
arguments: [command, path, "--json"],
environment,
});
expect(result.exitCode, result.stdout + result.stderr).toBe(0);
return parseEvidence(result.json);
};
const { call } = await connectLocalToolsMcp(environment);
const opened = await call("open_binary", { path: framework });
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
for (const [command, tool] of [
["inspect-macho", "inspect_macho"],
["inspect-signature", "inspect_signature"],
] as const) {
const selected = await inspect(command, framework);
const direct = await inspect(command, executable);
expect(selected.subject).toEqual(direct.subject);
expect(selected.subject).toMatchObject({
local_path: executable,
identity: { sha256: digest },
});
expect(direct.normalized_result).not.toHaveProperty(
"bundle_provenance",
);
expect(selected.normalized_result).toHaveProperty(
"bundle_provenance",
expected,
);
const mcp = await call(tool, {});
expect(mcp.isError, JSON.stringify(mcp)).not.toBe(true);
const evidence = parseEvidence(mcp.structuredContent);
expect(evidence.subject).toEqual(selected.subject);
expect(evidence.normalized_result).toHaveProperty(
"bundle_provenance",
expected,
);
}
const summary = await call("inspect_macho", { detail: "summary" });
expect(summary.isError, JSON.stringify(summary)).not.toBe(true);
expect(parseEvidence(summary.structuredContent)).toMatchObject({
normalized_result: { summary: { bundle_provenance: expected } },
});
await expectMachoSummaryProvenance(cli, framework, root, expected);
const reopened = await call("open_binary", { path: executable });
expect(reopened.isError, JSON.stringify(reopened)).not.toBe(true);
const direct = await call("inspect_signature", {});
expect(direct.isError, JSON.stringify(direct)).not.toBe(true);
expect(
parseEvidence(direct.structuredContent).normalized_result,
).not.toHaveProperty("bundle_provenance");
expect((await call("close_binary", {})).isError).not.toBe(true);
expect(
createHash("sha256")
.update(await readFile(executable))
.digest("hex"),
).toBe(digest);
},
);
},
);
@@ -1,4 +1,5 @@
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
import {
open,
type FileHandle,
@@ -567,6 +568,14 @@ describe("binary target I/O: OpenStep app plist escapes", () => {
value: {
executable: join(programs, "Main"),
infoPlist: join(app, "Contents", "Info.plist"),
bundleExecutableSelection: {
canonical_path: app,
layout: "contents",
declared_executable: "Main",
info_plist_sha256: createHash("sha256")
.update(plistContent)
.digest("hex"),
},
},
});
},