Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(native): bind signature observations to registered target versions (#1099)
morlutoc789af04b76c
diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.tsindex 666ccd7eb..d48066790 100644--- a/src/native/NativeMacOSProvider.ts+++ b/src/native/NativeMacOSProvider.ts@@ -54,6 +54,11 @@ import {type NativeCommandCapture,type NativeCommandRunner,} from "./CommandRunner.js";+import {+ withSignatureTarget,+ verifySignatureTarget,+ type SignatureTargetBinding,+} from "./SignatureTargetBinding.js";import { parseCodeSignature } from "./parsers/codesign.js";import { parseDemangledSymbols } from "./parsers/demangle.js";import { parseLipoArchitectures } from "./parsers/lipo.js";@@ -318,38 +323,46 @@ class NativeMacOSClient implements AnalysisClient {async #inspectSignature(signal?: AbortSignal,): Promise<Result<NativeObservation, AnalysisError>> {- const display = await this.#run(- "inspect_signature",- "codesign",- ["-d", "--verbose=4", this.target.path],- { signal, acceptNonZero: true },+ return withSignatureTarget(+ this.target,+ (binding) => this.#inspectBoundSignature(binding, signal),+ signal,+ );+ }++ async #inspectBoundSignature(+ binding: SignatureTargetBinding,+ signal?: AbortSignal,+ ): Promise<Result<NativeObservation, AnalysisError>> {+ const display = await this.#captureSignature(+ binding,+ ["-d", "--verbose=4"],+ signal,);if (!display.ok) return display;const unsigned = isNonzeroUnsignedObservation(display.value);const displayFailure = codeSignCaptureFailure(display.value);if (displayFailure !== null) return err(displayFailure);- const requirements = await this.#run(- "inspect_signature",- "codesign",- ["-d", "-r-", this.target.path],- { signal, acceptNonZero: true },+ const requirements = await this.#captureSignature(+ binding,+ ["-d", "-r-"],+ signal,);if (!requirements.ok) return requirements;const requirementsFailure = codeSignCaptureFailure(requirements.value);if (requirementsFailure !== null) return err(requirementsFailure);- const entitlements = await this.#run(- "inspect_signature",- "codesign",- ["-d", "--entitlements", ":-", this.target.path],- { signal, acceptNonZero: true },+ const entitlements = await this.#captureSignature(+ binding,+ ["-d", "--entitlements", ":-"],+ signal,);if (!entitlements.ok) return entitlements;const entitlementsFailure = codeSignCaptureFailure(entitlements.value);if (entitlementsFailure !== null) return err(entitlementsFailure);// codesign echoes the resolved executable path in its diagnostics.const parsed = parseCodeSignature(display.value.stderr, unsigned, [- this.target.path,- ...(await canonicalPath(this.target.path)),+ binding.snapshotPath,+ ...(await canonicalPath(binding.snapshotPath)),]);// The requirement is printed to stdout; stderr echoes the path.const requirementText =@@ -359,6 +372,7 @@ class NativeMacOSClient implements AnalysisClient {const captures = [display.value, requirements.value, entitlements.value];const limitations = [...parsed.limitations,+ "Inspected a digest-verified Mach-O byte snapshot; filesystem-bound signing context and trust validation are not examined.",...(entitlementValue.omittedPrototypeKeys === 0? []: [@@ -371,9 +385,12 @@ class NativeMacOSClient implements AnalysisClient {isNonzeroUnsignedObservation(entitlements.value));if (mixedSigning) {const slices = await this.#inspectMixedSignatureSlices(+ binding,parsed.format,- requirements.value.exitCode !== 0,- entitlements.value.exitCode !== 0,+ {+ requirements: requirements.value.exitCode,+ entitlements: entitlements.value.exitCode,+ },signal,);if (!slices.ok) return slices;@@ -381,8 +398,10 @@ class NativeMacOSClient implements AnalysisClient {limitations.push(...slices.value.limitations);}const provenance = captures.map((capture) =>- invocation(capture, this.target.path),+ invocation(capture, binding.snapshotPath),);+ const version = await verifySignatureTarget(this.target, binding, signal);+ if (!version.ok) return version;const result = inspectSignatureSchema.parse({...parsed,designated_requirement: requirementText,@@ -399,20 +418,22 @@ class NativeMacOSClient implements AnalysisClient {}async #inspectMixedSignatureSlices(+ binding: SignatureTargetBinding,format: string | null,- requirementsUnavailable: boolean,- entitlementsUnavailable: boolean,+ aggregateExits: Readonly<{+ requirements: number | null;+ entitlements: number | null;+ }>,signal?: AbortSignal,): Promise<Result<MixedSignatureSlices, AnalysisError>> {const captures: NativeCommandCapture[] = [];const unsigned: string[] = [];const unclassified: string[] = [];for (const architecture of codeSignArchitectures(format, this.target)) {- const slice = await this.#run(- "inspect_signature",- "codesign",- ["-d", "-a", architecture, "--verbose=4", this.target.path],- { signal, acceptNonZero: true },+ const slice = await this.#captureSignature(+ binding,+ ["-d", "-a", architecture, "--verbose=4"],+ signal,);if (!slice.ok) return slice;captures.push(slice.value);@@ -430,17 +451,53 @@ class NativeMacOSClient implements AnalysisClient {limitations.push(`Signature state could not be classified for Mach-O slices: ${unclassified.join(", ")}.`,);- if (requirementsUnavailable)+ if (aggregateExits.requirements !== 0)limitations.push("The aggregate designated requirement is unavailable because Mach-O slices have mixed signing states.",);- if (entitlementsUnavailable)+ if (aggregateExits.entitlements !== 0)limitations.push("The aggregate entitlements are unavailable because Mach-O slices have mixed signing states.",);return ok({ captures, limitations });}+ async #captureSignature(+ binding: SignatureTargetBinding,+ args: readonly string[],+ signal?: AbortSignal,+ ): Promise<Result<NativeCommandCapture, AnalysisError>> {+ const before = await verifySignatureTarget(this.target, binding, signal);+ if (!before.ok) return before;+ let capture: Result<NativeCommandCapture, AnalysisError>;+ try {+ capture = await this.#run(+ "inspect_signature",+ "codesign",+ [...args, binding.snapshotPath],+ {+ signal,+ acceptNonZero: true,+ },+ );+ } catch (cause: unknown) {+ capture = err(+ new ProviderAdapterError(IDENTITY.id, "inspect_signature", {+ cause,+ diagnostics: {+ phase: "codesign-capture",+ path: this.target.path,+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ }),+ );+ }+ // Verify failed captures too: a disappearing target is not a codesign+ // execution failure, and later captures must never use another version.+ const after = await verifySignatureTarget(this.target, binding, signal);+ return after.ok ? capture : after;+ }+async #inspectPlist(parameters: Readonly<Record<string, JsonValue>>,signal?: AbortSignal,diff --git a/src/native/SignatureTargetBinding.ts b/src/native/SignatureTargetBinding.tsnew file mode 100644index 000000000..e0f52e1f9--- /dev/null+++ b/src/native/SignatureTargetBinding.ts@@ -0,0 +1,272 @@+import { createHash } from "node:crypto";+import { constants, type BigIntStats } from "node:fs";+import { lstat, mkdtemp, open, rm, type FileHandle } from "node:fs/promises";+import { tmpdir } from "node:os";+import { basename, join } from "node:path";+import type { BinaryTarget } from "../domain/binaryTarget.js";+import { AnalysisError } from "../domain/analysisErrorBase.js";+import {+ AnalysisAccessDeniedError,+ AnalysisArtifactChangedError,+ AnalysisCancelledError,+ AnalysisResourceConstraintError,+} from "../domain/analysisErrorCore.js";+import { ProviderAdapterError } from "../domain/providerAdapterError.js";+import { err, ok, type Result } from "../domain/result.js";+import { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";++/** Binding of commands to the selected executable's registered content/version. */+export interface SignatureTargetBinding {+ readonly identity: string;+ readonly snapshotPath: string;+}++const identity = (stat: BigIntStats): string =>+ [stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].join(":");++const changedTarget = (target: BinaryTarget, reason: string) =>+ err(+ new AnalysisArtifactChangedError("inspect_signature", target.path, reason),+ );++const signatureReadFailure = (+ target: BinaryTarget,+ cause: unknown,+): AnalysisError => {+ if (cause instanceof AnalysisError) return cause;+ const code =+ cause instanceof Error && "code" in cause ? cause.code : undefined;+ if (code === "EACCES" || code === "EPERM")+ return new AnalysisAccessDeniedError(+ "inspect_signature",+ target.path,+ code,+ { cause },+ );+ if (code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP")+ return new AnalysisArtifactChangedError(+ "inspect_signature",+ target.path,+ `Registered signature target is no longer readable (${code}): ${target.path}`,+ { cause },+ );+ return new ProviderAdapterError(+ NATIVE_MACOS_PROVIDER_IDENTITY.id,+ "inspect_signature",+ {+ cause,+ diagnostics: {+ path: target.path,+ phase: "target-version-binding",+ system_code: typeof code === "string" ? code : null,+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ },+ );+};++/** Inspect a digest-verified private copy, releasing it on every exit path. */+export const withSignatureTarget = async <T>(+ target: BinaryTarget,+ inspect: (+ binding: SignatureTargetBinding,+ ) => Promise<Result<T, AnalysisError>>,+ signal?: AbortSignal,+): Promise<Result<T, AnalysisError>> => {+ let directory: string;+ try {+ signal?.throwIfAborted();+ directory = await mkdtemp(join(tmpdir(), "rea-signature-"));+ } catch (cause: unknown) {+ return err(+ signal?.aborted+ ? new AnalysisCancelledError("inspect_signature")+ : snapshotFailure(target, "create", cause),+ );+ }+ let result: Result<T, AnalysisError>;+ let cleanup: Result<void, AnalysisError>;+ try {+ const binding = await bindSignatureTarget(+ target,+ join(directory, basename(target.path)),+ signal,+ );+ result = binding.ok ? await inspect(binding.value) : binding;+ } finally {+ try {+ await rm(directory, { recursive: true, force: true });+ cleanup = ok(undefined);+ } catch (cause: unknown) {+ cleanup = err(snapshotFailure(target, "cleanup", cause));+ }+ }+ // Cleanup cannot replace the operation's original actionable failure.+ return result.ok && !cleanup.ok ? cleanup : result;+};++const snapshotFailure = (+ target: BinaryTarget,+ phase: string,+ cause: unknown,+): AnalysisError =>+ new ProviderAdapterError(+ NATIVE_MACOS_PROVIDER_IDENTITY.id,+ "inspect_signature",+ {+ cause,+ diagnostics: {+ path: target.path,+ phase: `signature-snapshot-${phase}`,+ reason: cause instanceof Error ? cause.message : String(cause),+ },+ },+ );++const snapshotIO = async <T>(+ target: BinaryTarget,+ phase: string,+ operation: () => Promise<T>,+): Promise<T> => {+ try {+ return await operation();+ } catch (cause: unknown) {+ throw snapshotFailure(target, phase, cause);+ }+};++const copySignatureBytes = async (+ target: BinaryTarget,+ source: { readonly file: FileHandle; readonly stat: BigIntStats },+ snapshot: FileHandle,+ signal?: AbortSignal,+): Promise<string> => {+ const size = Number(source.stat.size);+ if (!Number.isSafeInteger(size))+ throw new AnalysisResourceConstraintError(+ "inspect_signature",+ "file-size",+ `Signature target size is not exactly representable: ${target.path}`,+ null,+ );+ const hash = createHash("sha256");+ const chunk = Buffer.alloc(64 * 1024);+ let position = 0;+ while (position < size) {+ signal?.throwIfAborted();+ const { bytesRead } = await source.file.read(+ chunk,+ 0,+ Math.min(chunk.length, size - position),+ position,+ );+ signal?.throwIfAborted();+ if (bytesRead === 0)+ throw new AnalysisArtifactChangedError(+ "inspect_signature",+ target.path,+ `Signature target was truncated while hashing: ${target.path}`,+ );+ const bytes = chunk.subarray(0, bytesRead);+ hash.update(bytes);+ // writeFile retries short writes; memory remains bounded to this chunk.+ await snapshotIO(target, "write", () => snapshot.writeFile(bytes));+ position += bytesRead;+ }+ return hash.digest("hex");+};++/** Hash and copy the same descriptor bytes, without reopening the mutable path. */+const bindSignatureTarget = async (+ target: BinaryTarget,+ snapshotPath: string,+ signal?: AbortSignal,+): Promise<Result<SignatureTargetBinding, AnalysisError>> => {+ try {+ signal?.throwIfAborted();+ const before = await lstat(target.path, { bigint: true });+ signal?.throwIfAborted();+ if (!before.isFile() || before.isSymbolicLink())+ return changedTarget(+ target,+ `Signature target is no longer a regular file: ${target.path}`,+ );+ const file = await open(+ target.path,+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,+ );+ try {+ const opened = await file.stat({ bigint: true });+ signal?.throwIfAborted();+ if (identity(opened) !== identity(before))+ return changedTarget(+ target,+ `Signature target changed before open: ${target.path}`,+ );+ const snapshot = await snapshotIO(target, "create-file", () =>+ open(snapshotPath, "wx", 0o600),+ );+ try {+ const observed = await copySignatureBytes(+ target,+ { file, stat: opened },+ snapshot,+ signal,+ );+ if (observed !== target.sha256)+ return changedTarget(+ target,+ `Signature target digest changed: ${target.path}; expected ${target.sha256}, observed ${observed}`,+ );+ const after = await file.stat({ bigint: true });+ const current = await lstat(target.path, { bigint: true });+ signal?.throwIfAborted();+ if (+ identity(after) !== identity(opened) ||+ identity(current) !== identity(opened)+ )+ return changedTarget(+ target,+ `Signature target changed while establishing its version: ${target.path}`,+ );+ await snapshotIO(target, "seal", () => snapshot.chmod(0o400));+ return ok({ identity: identity(opened), snapshotPath });+ } finally {+ await snapshotIO(target, "close", () => snapshot.close());+ }+ } finally {+ await file.close();+ }+ } catch (cause: unknown) {+ return err(+ signal?.aborted+ ? new AnalysisCancelledError("inspect_signature")+ : signatureReadFailure(target, cause),+ );+ }+};++/** Reject target drift across signature command captures. */+export const verifySignatureTarget = async (+ target: BinaryTarget,+ binding: SignatureTargetBinding,+ signal?: AbortSignal,+): Promise<Result<void, AnalysisError>> => {+ try {+ signal?.throwIfAborted();+ const current = await lstat(target.path, { bigint: true });+ signal?.throwIfAborted();+ return current.isFile() && identity(current) === binding.identity+ ? ok(undefined)+ : changedTarget(+ target,+ `Signature target changed during inspection: ${target.path}`,+ );+ } catch (cause: unknown) {+ return err(+ signal?.aborted+ ? new AnalysisCancelledError("inspect_signature")+ : signatureReadFailure(target, cause),+ );+ }+};diff --git a/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts b/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.tsnew file mode 100644index 000000000..f7701838a--- /dev/null+++ b/tests/boundary/mcp/nativeSignatureTargetBindingMcp.test.ts@@ -0,0 +1,62 @@+import { writeFile } from "node:fs/promises";+import { join } from "node:path";+import { Client, InMemoryTransport } from "@modelcontextprotocol/client";+import { expect, it } from "vitest";+import { NativeMacOSProvider } from "../../../src/native/NativeMacOSProvider.js";+import {+ machoImage,+ rpathCommand,+} from "../../../src/artifacts/apple/MachoImage.fixture.js";+import { createServer } from "../../../src/server/createServer.js";+import { createTestBinarySession } from "../../fixtures/binarySession.js";+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";+import { NativeFixtureRunner } from "../../fixtures/nativeCommands.js";++it("rejects changed signature targets through MCP and accepts reopening the new version", async () => {+ const path = join(+ await createTestTempDirectory("rea-signature-binding-mcp-"),+ "program",+ );+ await writeFile(path, machoImage({}));+ const session = createTestBinarySession(+ new NativeMacOSProvider(new NativeFixtureRunner(), "darwin"),+ );+ const server = createServer(session, session);+ const client = new Client({ name: "signature-binding-test", version: "1" });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ try {+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ const open = () =>+ client.callTool({ name: "open_binary", arguments: { path } });+ expect((await open()).isError).not.toBe(true);+ await writeFile(+ path,+ machoImage({ commands: [rpathCommand("new-version")] }),+ );+ const changed = await client.callTool({+ name: "inspect_signature",+ arguments: {},+ });+ expect(changed.isError).toBe(true);+ expect(changed.structuredContent).toMatchObject({+ error: { code: "artifact_changed", details: { path } },+ });+ expect((await open()).isError).not.toBe(true);+ const inspected = await client.callTool({+ name: "inspect_signature",+ arguments: {},+ });+ expect(+ inspected.isError,+ JSON.stringify(inspected.structuredContent),+ ).not.toBe(true);+ expect(inspected.structuredContent).toMatchObject({+ result: { signed: true, identifier: "com.example.fixture" },+ });+ } finally {+ await client.close();+ await server.close();+ }+});diff --git a/tests/boundary/providers/native/nativeInventory.golden.test.ts b/tests/boundary/providers/native/nativeInventory.golden.test.tsindex 5a70d58b7..d931c6d5d 100644--- a/tests/boundary/providers/native/nativeInventory.golden.test.ts+++ b/tests/boundary/providers/native/nativeInventory.golden.test.ts@@ -1,4 +1,11 @@+import { writeFile } from "node:fs/promises";+import { join } from "node:path";import { expect, it } from "vitest";+import {+ CPU,+ fatImage,+ machoImage,+} from "../../../../src/artifacts/apple/MachoImage.fixture.js";import { err, ok } from "../../../../src/domain/result.js";import {NativeCommandFailure,@@ -13,7 +20,28 @@ import {NativeFixtureRunner as FixtureRunner,nativeFixture as fixture,nativeMachoTarget as machoTarget,+ nativeMachoTargetForFile,} from "../../../fixtures/nativeCommands.js";+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";++const signatureTarget = async (+ signedArchitecture: "arm64" | "arm64e" = "arm64",+) => {+ const path = join(+ await createTestTempDirectory("rea-native-inventory-"),+ "fixture",+ );+ await writeFile(+ path,+ fatImage(+ [CPU.x86_64, CPU[signedArchitecture]].map((cpu) => ({+ cpu,+ bytes: machoImage({ cpu }),+ })),+ ),+ );+ return nativeMachoTargetForFile(path);+};it("distinguishes a codesign execution failure from an observed unsigned artifact", async () => {for (const kind of ["missing", "unsigned"] as const) {@@ -25,7 +53,7 @@ it("distinguishes a codesign execution failure from an observed unsigned artifac1,),"darwin",- ).createClient(machoTarget("/private/fixture"));+ ).createClient(await signatureTarget());const execution = await client.execute("inspect_signature", {});if (kind === "missing")expect(execution).toMatchObject({@@ -44,7 +72,7 @@ it("reports unsigned slices when a universal Mach-O has mixed signatures", asyncconst signedFixture = await fixture("codesign.txt");const unsigned = await fixture("dyld-inventory/codesign-unsigned.txt");const entitlements = await fixture("entitlements.xml");- for (const signedArchitecture of ["arm64", "arm64e"]) {+ for (const signedArchitecture of ["arm64", "arm64e"] as const) {const signed = signedFixture.replace(/^Format=.*$/mu,`Format=Mach-O universal (x86_64 ${signedArchitecture})`,@@ -52,7 +80,7 @@ it("reports unsigned slices when a universal Mach-O has mixed signatures", asyncconst client = new NativeMacOSProvider(signatureRunner({ signed, unsigned, entitlements }),"darwin",- ).createClient(machoTarget("/private/fixture"));+ ).createClient(await signatureTarget(signedArchitecture));const execution = await client.execute("inspect_signature", {});@@ -98,7 +126,7 @@ it("rejects nonzero supplemental codesign output that is not an unsigned observaentitlements,}),"darwin",- ).createClient(machoTarget("/private/fixture"));+ ).createClient(await signatureTarget());const execution = await client.execute("inspect_signature", {});diff --git a/tests/boundary/providers/native/nativeProvider.test.ts b/tests/boundary/providers/native/nativeProvider.test.tsindex 68eeee7b3..9bed9342f 100644--- a/tests/boundary/providers/native/nativeProvider.test.ts+++ b/tests/boundary/providers/native/nativeProvider.test.ts@@ -19,6 +19,7 @@ import {NativeFixtureRunner as FixtureRunner,nativeFixture as fixture,nativeMachoTarget as machoTarget,+ nativeMachoTargetForFile,} from "../../../fixtures/nativeCommands.js";let directory: string | undefined;@@ -242,7 +243,7 @@ describe("native macOS provider inspection", () => {const client = new NativeMacOSProvider(new FixtureRunner(),"darwin",- ).createClient(machoTarget(executable, app));+ ).createClient(await nativeMachoTargetForFile(executable, app));const architectures = await client.execute("list_architectures", {});expect(architectures.ok && architectures.value.result).toMatchObject({@@ -318,10 +319,13 @@ class PrototypeEntitlementsRunner extends FixtureRunner {describe("native signature entitlements", () => {it("reports entitlement entries keyed __proto__ that the result omits", async () => {+ directory = await createTestTempDirectory("rea-signature-entitlements-");+ const executable = join(directory, "fixture");+ await writeFile(executable, "fixture");const client = new NativeMacOSProvider(new PrototypeEntitlementsRunner(),"darwin",- ).createClient(machoTarget("/private/fixture"));+ ).createClient(await nativeMachoTargetForFile(executable));const signature = await client.execute("inspect_signature", {});diff --git a/tests/boundary/providers/native/nativeSignatureTargetBinding.test.ts b/tests/boundary/providers/native/nativeSignatureTargetBinding.test.tsnew file mode 100644index 000000000..e1e75225d--- /dev/null+++ b/tests/boundary/providers/native/nativeSignatureTargetBinding.test.ts@@ -0,0 +1,434 @@+import { execFile } from "node:child_process";+import { promisify } from "node:util";+import {+ chmod,+ copyFile,+ lstat,+ mkdir,+ readFile,+ rename,+ rm,+ symlink,+ writeFile,+} from "node:fs/promises";+import { dirname, join } from "node:path";+import { describe, expect, it } from "vitest";+import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";+import {+ withSignatureTarget,+ verifySignatureTarget,+} from "../../../../src/native/SignatureTargetBinding.js";+import {+ NativeCommandFailure,+ XcrunCommandRunner,+ type NativeCommandRunner,+} from "../../../../src/native/CommandRunner.js";+import { inspectSignatureSchema } from "../../../../src/domain/native/nativeInspection.js";+import { err } from "../../../../src/domain/result.js";+import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";+import {+ NativeFixtureRunner,+ nativeMachoTargetForFile,+} from "../../../fixtures/nativeCommands.js";+import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";++const CONTENT = "registered executable bytes";+const fixture = async () => {+ const directory = await createTestTempDirectory("rea-signature-binding-");+ const path = join(directory, "program");+ await writeFile(path, CONTENT);+ return {+ directory,+ path,+ target: await nativeMachoTargetForFile(path),+ };+};++class Captures extends NativeFixtureRunner {+ calls = 0;+ constructor(+ private readonly onCapture?: (args: readonly string[]) => Promise<void>,+ ) {+ super();+ }+ override async run(tool: string, args: readonly string[]) {+ this.calls += 1;+ await this.onCapture?.(args);+ return super.run(tool, args);+ }+}++describe("native signature target identity", () => {+ it("inspects an unchanged registered executable", async () => {+ const { target } = await fixture();+ const result = await new NativeMacOSProvider(new Captures(), "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok && result.value.result).toMatchObject({+ signed: true,+ identifier: "com.example.fixture",+ });+ });++ it.each(["changed", "missing", "directory", "symlink"] as const)(+ "rejects a %s target before commands run",+ async (replacement) => {+ const { path, target } = await fixture();+ if (replacement === "changed") await writeFile(path, "replacement bytes");+ else {+ await rm(path);+ if (replacement === "directory") await mkdir(path);+ if (replacement === "symlink") {+ await symlink(join(path, "missing"), path);+ }+ }+ const runner = new Captures();+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected target-change failure");+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "artifact_changed",+ details: { path },+ });+ expect(runner.calls).toBe(0);+ },+ );++ it.each(["replace", "remove", "rewrite"] as const)(+ "rejects %s after capturing signature metadata",+ async (change) => {+ const { path, target } = await fixture();+ const runner = new Captures(async (args) => {+ if (!args.includes("--entitlements")) return;+ if (change === "remove") await rm(path);+ else if (change === "rewrite") await writeFile(path, CONTENT);+ else {+ const replacement = `${path}.replacement`;+ await writeFile(replacement, CONTENT);+ await rename(replacement, path);+ }+ });+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected target-change failure");+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "artifact_changed",+ details: { path },+ });+ },+ );++ it.skipIf(process.getuid?.() === 0)(+ "preserves read permission denial before commands",+ async () => {+ const { path, target } = await fixture();+ await chmod(path, 0);+ const runner = new Captures();+ try {+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected access denial");+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "access_denied",+ details: { path },+ });+ expect(runner.calls).toBe(0);+ } finally {+ await chmod(path, 0o600);+ }+ },+ );++ it.skipIf(process.getuid?.() === 0)(+ "preserves permission denial during final version lookup",+ async () => {+ const { directory, path, target } = await fixture();+ const runner = new Captures(async (args) => {+ if (args.includes("--entitlements")) await chmod(directory, 0);+ });+ try {+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok).toBe(false);+ if (result.ok) throw new Error("Expected access denial");+ expect(projectAnalysisError(result.error)).toMatchObject({+ code: "access_denied",+ details: { path },+ });+ } finally {+ await chmod(directory, 0o700);+ }+ },+ );+});++it.each([+ ["display", "result"],+ ["requirements", "result"],+ ["entitlements", "result"],+ ["slice", "result"],+ ["display", "throw"],+ ["requirements", "diagnostic"],+] as const)(+ "reports a removed target before the %s capture's %s failure can hide it",+ async (stage, failure) => {+ const { path, target } = await fixture();+ const replay = new NativeFixtureRunner();+ const unsigned = new NativeFixtureRunner(+ { codesign: "code object is not signed at all\n" },+ 1,+ );+ let failed = false;+ const runner: NativeCommandRunner = {+ async run(tool, args) {+ const slice = args.includes("-a");+ const selected =+ stage === "slice"+ ? slice+ : stage === "requirements"+ ? args.includes("-r-")+ : stage === "entitlements"+ ? args.includes("--entitlements")+ : !args.includes("-r-") &&+ !args.includes("--entitlements") &&+ !slice;+ if (selected) {+ failed = true;+ await rm(path);+ if (failure === "throw")+ throw new Error("codesign target disappeared");+ if (failure === "diagnostic")+ return new NativeFixtureRunner(+ { codesign: "invalid or unsupported format\n" },+ 1,+ ).run(tool, args);+ return err(new NativeCommandFailure(tool, "nonzero-exit", 1));+ }+ if (stage === "slice" && args.includes("-r-"))+ return unsigned.run(tool, args);+ return replay.run(tool, args);+ },+ };+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(failed).toBe(true);+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisArtifactChangedError" },+ });+ },+);++it("rejects an intermediate replacement before a later capture can restore the original inode", async () => {+ const { path, target } = await fixture();+ const original = `${path}.original`;+ const runner = new Captures(async (args) => {+ if (args.includes("-r-")) {+ await rename(path, original);+ await writeFile(path, "different executable");+ } else if (args.includes("--entitlements")) {+ await rm(path);+ await rename(original, path);+ }+ });+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisArtifactChangedError" },+ });+});++it("returns typed cancellation during target acquisition before commands run", async () => {+ const { path } = await fixture();+ await writeFile(path, Buffer.alloc(4 * 1024 * 1024, 42));+ const target = await nativeMachoTargetForFile(path);+ const controller = new AbortController();+ const runner = new Captures();+ const pending = new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {}, { signal: controller.signal });+ controller.abort();+ const result = await pending;+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisCancelledError" },+ });+ expect(!result.ok && projectAnalysisError(result.error).code).toBe(+ "cancelled",+ );+ expect(runner.calls).toBe(0);+});++it("returns typed cancellation at binding entry and final verification", async () => {+ const { target } = await fixture();+ const signal = AbortSignal.abort();+ await expect(+ withSignatureTarget(+ target,+ async () => {+ throw new Error("Cancelled acquisition must not invoke inspection");+ },+ signal,+ ),+ ).resolves.toMatchObject({+ ok: false,+ error: { _tag: "AnalysisCancelledError" },+ });+ await withSignatureTarget(target, async (binding) => {+ const result = await verifySignatureTarget(target, binding, signal);+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisCancelledError" },+ });+ return result;+ });+});++it("preserves cancellation after a capture instead of classifying it as invalid output", async () => {+ const { target } = await fixture();+ const controller = new AbortController();+ const runner = new Captures(async () => {+ controller.abort();+ });+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {}, { signal: controller.signal });+ expect(result).toMatchObject({+ ok: false,+ error: { _tag: "AnalysisCancelledError" },+ });+});++it.each(["success", "failure", "cancellation", "throw"] as const)(+ "releases the verified snapshot after %s",+ async (outcome) => {+ const { target } = await fixture();+ const controller = new AbortController();+ let snapshotPath: string | undefined;+ const runner: NativeCommandRunner = {+ async run(tool, args) {+ snapshotPath = args.at(-1);+ if (snapshotPath === undefined)+ throw new Error("Missing command target");+ expect(snapshotPath).not.toBe(target.path);+ expect(await readFile(snapshotPath, "utf8")).toBe(CONTENT);+ if (outcome === "throw") throw new Error("Unexpected native failure");+ if (outcome === "failure")+ return err(new NativeCommandFailure(tool, "io"));+ if (outcome === "cancellation") controller.abort();+ return new NativeFixtureRunner().run(tool, args);+ },+ };+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {}, { signal: controller.signal });+ expect(result.ok).toBe(outcome === "success");+ if (snapshotPath === undefined)+ throw new Error("Expected snapshot capture");+ await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({+ code: "ENOENT",+ });+ },+);++it("copies and hashes the same bytes across multiple snapshot chunks", async () => {+ const { path } = await fixture();+ const bytes = Buffer.alloc(128 * 1024 + 13, 42);+ await writeFile(path, bytes);+ const target = await nativeMachoTargetForFile(path);+ await withSignatureTarget(target, async (binding) => {+ expect(await readFile(binding.snapshotPath)).toEqual(bytes);+ return verifySignatureTarget(target, binding);+ });+});++it("cleans the private snapshot when inspection throws", async () => {+ const { target } = await fixture();+ let snapshotPath: string | undefined;+ await expect(+ withSignatureTarget(target, async (binding) => {+ snapshotPath = binding.snapshotPath;+ throw new Error("Invalid parsed output");+ }),+ ).rejects.toThrow("Invalid parsed output");+ if (snapshotPath === undefined) throw new Error("Expected snapshot");+ await expect(lstat(dirname(snapshotPath))).rejects.toMatchObject({+ code: "ENOENT",+ });+});++it.skipIf(process.platform !== "darwin")(+ "keeps real codesign bound to registered bytes during an ancestor directory swap",+ async () => {+ const root = await createTestTempDirectory("rea-signature-swap-");+ const selected = join(root, "selected");+ const replacement = join(root, "replacement");+ const saved = join(root, "saved");+ await mkdir(selected);+ await mkdir(replacement);+ const path = join(selected, "program");+ const replacementPath = join(replacement, "program");+ const run = promisify(execFile);+ for (const [program, identifier] of [+ [path, "rea.original"],+ [replacementPath, "rea.replacement"],+ ] as const) {+ await copyFile("/usr/bin/true", program);+ await run("/usr/bin/codesign", [+ "-s",+ "-",+ "-f",+ "--identifier",+ identifier,+ program,+ ]);+ }+ const target = await nativeMachoTargetForFile(path);+ const real = new XcrunCommandRunner();+ let capturedPath: string | undefined;+ const runner: NativeCommandRunner = {+ async run(tool, args, options) {+ capturedPath = args.at(-1);+ await rename(selected, saved);+ await rename(replacement, selected);+ try {+ expect(await readFile(path)).not.toEqual(+ await readFile(join(saved, "program")),+ );+ return await real.run(tool, args, options);+ } finally {+ await rename(selected, replacement);+ await rename(saved, selected);+ }+ },+ };+ const result = await new NativeMacOSProvider(runner, "darwin")+ .createClient(target)+ .execute("inspect_signature", {});+ expect(result.ok && result.value.result).toMatchObject({+ signed: true,+ identifier: "rea.original",+ });+ if (!result.ok) throw result.error;+ expect(+ inspectSignatureSchema+ .parse(result.value.result)+ .provenance.map(({ command }) => command.at(-1)),+ ).toEqual(["$ARTIFACT", "$ARTIFACT", "$ARTIFACT"]);+ if (capturedPath === undefined)+ throw new Error("Expected codesign invocation");+ await expect(lstat(dirname(capturedPath))).rejects.toMatchObject({+ code: "ENOENT",+ });+ },+);diff --git a/tests/fixtures/nativeCommands.ts b/tests/fixtures/nativeCommands.tsindex b4dcf2dde..760f45614 100644--- a/tests/fixtures/nativeCommands.ts+++ b/tests/fixtures/nativeCommands.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { readFile } from "node:fs/promises";import type { BinaryTarget } from "../../src/domain/binaryTarget.js";import { ok } from "../../src/domain/result.js";@@ -96,7 +97,10 @@ const capture = (export const nativeMachoTarget = (path: string,sourcePath?: string,-): BinaryTarget => ({+): BinaryTarget & {+ readonly kind: "executable";+ readonly format: "mach-o";+} => ({path,...(sourcePath === undefined ? {} : { sourcePath }),sha256: "0".repeat(64),@@ -106,6 +110,17 @@ export const nativeMachoTarget = (availableArchitectures: ["x86_64", "arm64"],});+/** Register the actual bytes of a filesystem-backed native test target. */+export const nativeMachoTargetForFile = async (+ path: string,+ sourcePath?: string,+): Promise<ReturnType<typeof nativeMachoTarget>> => ({+ ...nativeMachoTarget(path, sourcePath),+ sha256: createHash("sha256")+ .update(await readFile(path))+ .digest("hex"),+});+/** Load one captured native tool output. */export const nativeFixture = (name: string): Promise<string> =>readFile(new URL(`./native-macos/${name}`, import.meta.url), "utf8");