Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(artifacts): report target applicability in session discovery (#5763)

Jeff7c6c25dda75e
diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts
index b2b6834e1..0572d3ae1 100644
--- a/src/application/BinaryTargetResolver.ts
+++ b/src/application/BinaryTargetResolver.ts
@@ -135,6 +135,7 @@ export const parseBinaryTarget = async (
return ok({
path,
sourcePath,
+ ...bundle,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "raw-binary",
@@ -174,6 +175,7 @@ export const parseBinaryTarget = async (
return ok({
path,
sourcePath,
+ ...bundle,
sha256: await sha256Handle(handle, path, metadata, signal),
kind: "executable",
format: "dos-com",
diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts
index 094977327..87e2dc711 100644
--- a/src/application/CapabilityInventory.ts
+++ b/src/application/CapabilityInventory.ts
@@ -685,6 +685,7 @@ const targetAvailability = ({
targetKind,
targetFormat,
targetOpen,
+ descriptors,
}: AvailabilityContext): Availability | null => {
if (FRIDA_OPERATION_NAMES.has(name)) return null;
if (!targetOpen && ACTIVE_TARGET_KINDS.has(kind))
@@ -692,6 +693,14 @@ const targetAvailability = ({
reason: "target_required",
remediation: "Call open_binary with a supported local target.",
};
+ const descriptor = descriptors.get(name);
+ if (
+ targetOpen &&
+ descriptor?.available === false &&
+ (descriptor.availability_code === "target_kind_unsupported" ||
+ descriptor.availability_code === "target_format_unsupported")
+ )
+ return { reason: "target_unsupported", remediation: descriptor.reason };
if (
targetKind !== undefined &&
targetKind !== "executable" &&
diff --git a/src/application/binary/BinarySessionStatus.test.ts b/src/application/binary/BinarySessionStatus.test.ts
index ba1c45144..12cac2def 100644
--- a/src/application/binary/BinarySessionStatus.test.ts
+++ b/src/application/binary/BinarySessionStatus.test.ts
@@ -1,3 +1,4 @@
+import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import { describe, expect, it } from "vitest";
import type {
@@ -124,6 +125,7 @@ const project = async (
string,
{ readonly reason: string }
> = new Map(),
+ target?: BinaryTarget,
) => {
const route: SessionProviderRoute = {
identity: providerA,
@@ -142,7 +144,7 @@ const project = async (
};
return projectedStatusSchema.parse(
await binarySessionStatus({
- target: undefined,
+ target,
route,
router,
runtimeUnavailability,
@@ -412,3 +414,33 @@ describe("binary session provider capability projection", () => {
]);
});
});
+
+it.each(["elf", "pe"] as const)(
+ "reports format rejection for %s dylib discovery",
+ async (format) => {
+ const target: BinaryTarget = {
+ kind: "executable",
+ format,
+ path: "/fixture",
+ sha256: "a".repeat(64),
+ architecture: "x86_64",
+ availableArchitectures: ["x86_64"],
+ ...(format === "pe"
+ ? { executableRole: "application" as const, managed: false }
+ : {}),
+ } as BinaryTarget;
+ const status = await project(
+ [descriptor(providerA, "trace_dylib_resolution", [])],
+ [],
+ new Map(),
+ target,
+ );
+ expect(expandCanonicalCapabilities(status.capabilities)).toMatchObject([
+ {
+ operation: "trace_dylib_resolution",
+ available: false,
+ availability_code: "target_format_unsupported",
+ },
+ ]);
+ },
+);
diff --git a/src/application/binary/BinarySessionStatus.ts b/src/application/binary/BinarySessionStatus.ts
index 104d7e101..7cc45e1f1 100644
--- a/src/application/binary/BinarySessionStatus.ts
+++ b/src/application/binary/BinarySessionStatus.ts
@@ -1,3 +1,4 @@
+import { artifactTargetRefusal } from "../../domain/apple/artifactTargetApplicability.js";
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
import type { ResolvedAppBundleResourceRoot } from "../AppBundleExecutable.js";
import { binaryTargetSummary } from "./BinaryTargetSummary.js";
@@ -62,6 +63,17 @@ export const binarySessionStatus = async ({
compareUnicodeCodePoints(left.operation, right.operation),
)
.map((descriptor) => {
+ const targetRefusal =
+ target === undefined
+ ? undefined
+ : artifactTargetRefusal(descriptor.operation, target);
+ if (targetRefusal !== undefined && descriptor.available)
+ return {
+ ...descriptor,
+ available: false as const,
+ availabilityCode: targetRefusal.code,
+ reason: targetRefusal.reason,
+ };
const unavailable = runtimeUnavailability.get(descriptor.operation);
return unavailable === undefined
? descriptor
diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts
index 2a115286b..bba244b4c 100644
--- a/src/artifacts/ArtifactProvider.ts
+++ b/src/artifacts/ArtifactProvider.ts
@@ -1,3 +1,4 @@
+import { artifactTargetRefusal } from "../domain/apple/artifactTargetApplicability.js";
import { bindArtifactFileCleanup } from "./ArtifactFileOperation.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { translateArtifactFailure } from "./ArtifactOperationFailure.js";
@@ -24,10 +25,7 @@ import {
artifactExtractionExecutionSchema,
type ArtifactAnalysisOperation,
} from "../contracts/artifactToolContracts.js";
-import {
- isMachOFormat,
- type BinaryTarget,
-} from "../domain/binaryTargetTypes.js";
+import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
@@ -215,23 +213,17 @@ class ArtifactClient implements AnalysisClient {
),
);
try {
+ const targetRefusal = artifactTargetRefusal(operation, this.target);
+ if (targetRefusal !== undefined)
+ throw this.unsupportedTarget(operation, targetRefusal.reason);
if (operation === "inspect_artifact") {
const inspected = await this.inspectArtifact(parameters, options);
return inspected;
}
if (operation === "decode_interface_builder") {
- if (
- this.target.kind !== "executable" ||
- this.target.sourcePath === undefined ||
- !this.target.sourcePath.toLowerCase().endsWith(".app")
- )
- throw this.unsupportedTarget(
- operation,
- "decode_interface_builder requires an active .app bundle target",
- );
const limits = interfaceBuilderLimitsSchema.parse(parameters);
const result = await analyzeInterfaceBuilderBundle({
- bundlePath: this.target.sourcePath,
+ bundlePath: this.target.sourcePath ?? this.target.path,
targetSha256: this.target.sha256,
limits,
...(options?.signal === undefined ? {} : { signal: options.signal }),
@@ -266,15 +258,7 @@ class ArtifactClient implements AnalysisClient {
]);
const bundlePath = standalone
? dirname(this.target.path)
- : this.target.sourcePath;
- if (
- bundlePath === undefined ||
- (!standalone && !bundlePath.toLowerCase().endsWith(".app"))
- )
- throw this.unsupportedTarget(
- operation,
- "inspect_keyed_archive requires an active plist or .app bundle",
- );
+ : (this.target.sourcePath ?? this.target.path);
const result = await inspectBundleKeyedArchive({
bundlePath,
targetSha256: this.target.sha256,
@@ -386,16 +370,7 @@ class ArtifactClient implements AnalysisClient {
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
- const bundlePath = this.target.sourcePath;
- if (
- this.target.kind !== "executable" ||
- bundlePath === undefined ||
- !bundlePath.toLowerCase().endsWith(".app")
- )
- throw this.unsupportedTarget(
- "inspect_asset_catalog",
- "inspect_asset_catalog requires an active .app bundle target",
- );
+ const bundlePath = this.target.sourcePath ?? this.target.path;
const result = await analyzeAppleAssetCatalogs({
environment: this.environment,
bundlePath,
@@ -418,11 +393,6 @@ class ArtifactClient implements AnalysisClient {
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
- if (this.target.kind !== "executable" || !isMachOFormat(this.target.format))
- throw this.unsupportedTarget(
- "trace_dylib_resolution",
- "trace_dylib_resolution requires an active Mach-O or .app bundle target",
- );
// Only a target opened from an app bundle directory carries its Info.plist;
// a regular file whose name ends in .app is a standalone image.
const bundle =
diff --git a/src/domain/apple/artifactTargetApplicability.ts b/src/domain/apple/artifactTargetApplicability.ts
new file mode 100644
index 000000000..38a9412df
--- /dev/null
+++ b/src/domain/apple/artifactTargetApplicability.ts
@@ -0,0 +1,46 @@
+import { isMachOFormat, type BinaryTarget } from "../binaryTargetTypes.js";
+
+interface ArtifactTargetRefusal {
+ readonly code: "target_kind_unsupported" | "target_format_unsupported";
+ readonly reason: string;
+}
+
+/** Target prerequisites shared by artifact execution and session discovery. */
+export const artifactTargetRefusal = (
+ operation: string,
+ target: BinaryTarget,
+): ArtifactTargetRefusal | undefined => {
+ const bundle =
+ target.kind === "executable" && target.bundleInfoPlist !== undefined;
+ const refuse = (reason: string): ArtifactTargetRefusal => ({
+ code: "target_kind_unsupported",
+ reason,
+ });
+ switch (operation) {
+ case "decode_interface_builder":
+ case "inspect_asset_catalog":
+ return bundle
+ ? undefined
+ : refuse(`${operation} requires an active .app bundle target`);
+ case "inspect_keyed_archive":
+ return bundle || (target.kind === "artifact" && target.format === "plist")
+ ? undefined
+ : refuse(
+ "inspect_keyed_archive requires an active plist or .app bundle",
+ );
+ case "trace_dylib_resolution":
+ if (target.kind !== "executable")
+ return refuse(
+ "trace_dylib_resolution requires an active Mach-O or .app bundle target",
+ );
+ return isMachOFormat(target.format)
+ ? undefined
+ : {
+ code: "target_format_unsupported",
+ reason:
+ "trace_dylib_resolution requires an active Mach-O or .app bundle target",
+ };
+ default:
+ return undefined;
+ }
+};
diff --git a/tests/boundary/mcp/artifactMcp.test.ts b/tests/boundary/mcp/artifactMcp.test.ts
index d84c13910..94f7e5150 100644
--- a/tests/boundary/mcp/artifactMcp.test.ts
+++ b/tests/boundary/mcp/artifactMcp.test.ts
@@ -1,3 +1,4 @@
+import { toolContract } from "../../../src/contracts/toolContracts.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
@@ -658,3 +659,151 @@ it("compares summary Evidence through retained complete inspection parents", asy
});
const toolEvidence = (value: unknown) => parseEvidence(value);
+
+it("discovers artifact target prerequisites and preserves typed MCP refusals", async () => {
+ const root = await createTestTempDirectory("rea-artifact-availability-mcp-");
+ const zip = new ZipWriter(new Uint8ArrayWriter());
+ await zip.add("a.txt", new TextReader("hello"));
+ await writeFile(join(root, "sample.zip"), await zip.close());
+ await writeFile(
+ join(root, "plain.plist"),
+ "<plist><dict><key>hello</key><string>world</string></dict></plist>",
+ );
+ await writeFile(
+ join(root, "keyed.plist"),
+ "<plist><dict><key>$archiver</key><string>NSKeyedArchiver</string><key>$objects</key><array><string>$null</string><string>hello</string></array><key>$top</key><dict><key>root</key><dict><key>CF$UID</key><integer>1</integer></dict></dict></dict></plist>",
+ );
+ const header = Buffer.alloc(32);
+ header.writeUInt32LE(0xfeedfacf, 0);
+ header.writeUInt32LE(0x01000007, 4);
+ header.writeUInt32LE(3, 8);
+ header.writeUInt32LE(2, 12);
+ await writeFile(join(root, "standalone"), header);
+ await writeFile(join(root, "Tool.app"), header);
+ const contents = join(root, "Fixture.app", "Contents");
+ await mkdir(join(contents, "MacOS"), { recursive: true });
+ await writeFile(join(contents, "MacOS", "Fixture"), header);
+ await writeFile(
+ join(contents, "Info.plist"),
+ "<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
+ );
+ const session = createTestBinarySession(
+ new ArtifactProvider(process.env, "darwin"),
+ );
+ const server = createServer({ kind: "session", session });
+ const client = new Client({
+ name: "artifact-availability-test",
+ version: "1",
+ });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ const operations = [
+ "decode_interface_builder",
+ "inspect_asset_catalog",
+ "inspect_keyed_archive",
+ "trace_dylib_resolution",
+ ];
+ const availability = async () => {
+ const response = await client.callTool({
+ name: "binary_session",
+ arguments: {},
+ });
+ const result = toolContract("binary_session").outputSchema.parse(
+ response.structuredContent,
+ );
+ return result.result.tool_availability.groups;
+ };
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ const before = await availability();
+ for (const name of operations)
+ expect(before.find((group) => group.names.includes(name))).toMatchObject({
+ available: false,
+ reason: "target_required",
+ });
+ for (const filename of [
+ "sample.zip",
+ "plain.plist",
+ "keyed.plist",
+ "standalone",
+ "Tool.app",
+ "Fixture.app",
+ ]) {
+ expect(
+ (
+ await client.callTool({
+ name: "open_binary",
+ arguments: { path: join(root, filename) },
+ })
+ ).isError,
+ ).not.toBe(true);
+ const groups = await availability();
+ for (const name of operations) {
+ const supported =
+ filename === "Fixture.app" ||
+ (filename.endsWith(".plist") && name === "inspect_keyed_archive") ||
+ (["standalone", "Tool.app"].includes(filename) &&
+ name === "trace_dylib_resolution");
+ const group = groups.find((entry) => entry.names.includes(name));
+ expect(group, `${filename} ${name}`).toMatchObject({
+ available: supported,
+ reason: supported ? "available" : "target_unsupported",
+ });
+ if (!supported) {
+ expect(group?.remediation).toMatch(/requires an active/);
+ const refused = await client.callTool({ name, arguments: {} });
+ expect(parseMcpToolError(refused)).toMatchObject({
+ error: { code: "unsupported_target" },
+ });
+ }
+ }
+ if (filename.endsWith(".plist")) {
+ const inspected = await client.callTool({
+ name: "inspect_keyed_archive",
+ arguments: {},
+ });
+ if (filename === "keyed.plist")
+ expect(inspected.isError).not.toBe(true);
+ else
+ expect(parseMcpToolError(inspected)).toMatchObject({
+ error: { code: "unsupported_target" },
+ });
+ }
+ await client.callTool({ name: "close_binary", arguments: {} });
+ }
+ await writeFile(
+ join(contents, "state.plist"),
+ await readFile(join(root, "keyed.plist")),
+ );
+ for (const format of ["raw-binary", "dos-com"] as const) {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: {
+ path: join(root, "Fixture.app"),
+ format,
+ ...(format === "raw-binary"
+ ? { architecture: "x86_64", entry_point: "0x0" }
+ : {}),
+ },
+ });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ const groups = await availability();
+ for (const name of operations.filter(
+ (name) => name !== "trace_dylib_resolution",
+ ))
+ expect(
+ groups.find((group) => group.names.includes(name)),
+ `${format} ${name}`,
+ ).toMatchObject({ available: true });
+ const inspected = await client.callTool({
+ name: "inspect_keyed_archive",
+ arguments: { path: "Contents/state.plist" },
+ });
+ expect(inspected.isError, JSON.stringify(inspected)).not.toBe(true);
+ await client.callTool({ name: "close_binary", arguments: {} });
+ }
+ } finally {
+ await Promise.allSettled([client.close(), server.close(), session.close()]);
+ }
+});