feat(android): integrate static APK analysis with headless JADX (#738)
* feat(android): integrate static APK analysis with headless JADX * test(android): include APK tools in explicit effects audit
This commit is contained in:
@@ -0,0 +1,322 @@
|
||||
import { expect, it as test } from "vitest";
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { AndroidAnalysisService } from "../../../src/application/AndroidAnalysisService.js";
|
||||
import { JadxProvider } from "../../../src/android/JadxProvider.js";
|
||||
import { androidResultSchemas } from "../../../src/domain/androidAnalysis.js";
|
||||
import {
|
||||
createJadxProtocolFixture as setup,
|
||||
verifyJadxFixtureCleanup as verifyCleanup,
|
||||
} from "../../fixtures/android/jadx.js";
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
it("retains APK identity, original input, raw producer data and normalized observations", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
expect(outcome.ok).toBe(true);
|
||||
if (!outcome.ok) throw outcome.error;
|
||||
const result = androidResultSchemas.inspect_android_package.parse(
|
||||
outcome.value.normalized_result,
|
||||
);
|
||||
expect(result.package_name).toBe("fixture");
|
||||
expect(result.engine.source_revision).toBeNull();
|
||||
expect(outcome.value.subject?.local_path).toBe(apk);
|
||||
expect(outcome.value.parameters).toEqual({ path: apk });
|
||||
expect(outcome.value.raw_result).toMatchObject({
|
||||
calls: expect.arrayContaining([
|
||||
expect.objectContaining({ operation: "get_android_manifest" }),
|
||||
]),
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("fetches all class pages rather than silently retaining the first upstream page", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const outcome = await service.execute("search_android_classes", {
|
||||
path: apk,
|
||||
query: "",
|
||||
});
|
||||
if (!outcome.ok) throw outcome.error;
|
||||
const result = androidResultSchemas.search_android_classes.parse(
|
||||
outcome.value.normalized_result,
|
||||
);
|
||||
expect(result.total_classes).toBe(401);
|
||||
expect(result.matches).toHaveLength(401);
|
||||
expect(result.matches.at(-1)).toBe("fixture.Class399");
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("exposes overload candidates and executes only an explicitly selected ambiguous method", async () => {
|
||||
const { service, apk, launches } = await setup();
|
||||
const input = {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
method_name: "choose",
|
||||
};
|
||||
const ambiguous = await service.execute("inspect_android_method", input);
|
||||
expect(ambiguous).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [
|
||||
{
|
||||
path: ["overload_index"],
|
||||
message: expect.stringContaining("1: choose(int)"),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const selected = await service.execute("inspect_android_method", {
|
||||
...input,
|
||||
overload_index: 1,
|
||||
});
|
||||
if (!selected.ok) throw selected.error;
|
||||
const result = androidResultSchemas.inspect_android_method.parse(
|
||||
selected.value.normalized_result,
|
||||
);
|
||||
expect(result.method).toMatchObject({
|
||||
overload_index: 1,
|
||||
reported_signature: "choose(int): void",
|
||||
dex_descriptor: null,
|
||||
});
|
||||
expect(result.source.text).toContain("overload 1");
|
||||
const references = await service.execute("trace_android_references", input);
|
||||
expect(references).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("first same-name"),
|
||||
},
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"wrong-apk",
|
||||
"empty-page",
|
||||
"summary-error",
|
||||
"wrong-method",
|
||||
"body-error",
|
||||
"partial-xrefs",
|
||||
])(
|
||||
"rejects producer failure %s rather than claiming complete analysis",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const operation =
|
||||
mode === "wrong-apk"
|
||||
? "inspect_android_package"
|
||||
: mode === "empty-page"
|
||||
? "search_android_classes"
|
||||
: mode === "partial-xrefs"
|
||||
? "trace_android_references"
|
||||
: "inspect_android_method";
|
||||
const outcome = await service.execute(operation, {
|
||||
path: apk,
|
||||
...(operation === "search_android_classes"
|
||||
? { query: "" }
|
||||
: operation === "inspect_android_package"
|
||||
? {}
|
||||
: { class_name: "fixture.Target", method_name: "onCreate" }),
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects fuzzy class resolution and unsupported upstream versions", async () => {
|
||||
for (const mode of ["wrong-class", "version"]) {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_class", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag:
|
||||
mode === "version"
|
||||
? "AnalysisCapabilityUnavailableError"
|
||||
: "AnalysisInputError",
|
||||
},
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["truncated", "smali"])(
|
||||
"retains %s source coverage instead of presenting it as successful complete Java",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
method_name: "onCreate",
|
||||
});
|
||||
if (!outcome.ok) throw outcome.error;
|
||||
const result = androidResultSchemas.inspect_android_method.parse(
|
||||
outcome.value.normalized_result,
|
||||
);
|
||||
expect(result.source.status).toBe(
|
||||
mode === "truncated" ? "partial" : "complete",
|
||||
);
|
||||
expect(result.representation).toBe(mode === "smali" ? "smali" : "java");
|
||||
if (mode === "truncated")
|
||||
expect(result.source.reported_total_bytes).toBe(100);
|
||||
else expect(result.fell_back).toBe(true);
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
|
||||
it("cancels active and queued requests, cleans ownership and never launches a queued cancelled request", async () => {
|
||||
const { service, apk, launches } = await setup("stall");
|
||||
const activeController = new AbortController();
|
||||
const active = service.execute(
|
||||
"inspect_android_package",
|
||||
{ path: apk },
|
||||
{ signal: activeController.signal },
|
||||
);
|
||||
await expect.poll(() => launches.length).toBe(1);
|
||||
const queuedController = new AbortController();
|
||||
const queued = service.execute(
|
||||
"inspect_android_package",
|
||||
{ path: apk },
|
||||
{ signal: queuedController.signal },
|
||||
);
|
||||
queuedController.abort();
|
||||
expect(await queued).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
expect(launches).toHaveLength(1);
|
||||
activeController.abort();
|
||||
expect(await active).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("reports missing explicit tools without trying to install or launch them", async () => {
|
||||
const { apk } = await setup();
|
||||
const provider = new JadxProvider({}, () => {
|
||||
throw new Error("must not launch");
|
||||
});
|
||||
const outcome = await new AndroidAnalysisService(provider).execute(
|
||||
"inspect_android_package",
|
||||
{ path: apk },
|
||||
);
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("REA_JADX_MCP_JAR"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["tool-error", "frame-overflow"])(
|
||||
"preserves the actual failed provider constraint for %s",
|
||||
async (mode) => {
|
||||
const { service, apk, launches } = await setup(mode);
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
if (outcome.ok) throw new Error("Expected a provider failure");
|
||||
if (mode === "tool-error")
|
||||
expect(outcome.error).toMatchObject({
|
||||
_tag: "ProviderAdapterError",
|
||||
diagnostics: {
|
||||
reason: "manifest decoder rejected malformed binary XML",
|
||||
},
|
||||
});
|
||||
else
|
||||
expect(outcome.error).toMatchObject({
|
||||
_tag: "AnalysisOutputError",
|
||||
reason: expect.stringContaining("MCP frame exceeds"),
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects bytes changed after target admission without launching an engine", async () => {
|
||||
const { provider, apk, launches } = await setup();
|
||||
const target = await parseBinaryTarget(apk);
|
||||
if (!target.ok) throw target.error;
|
||||
await writeFile(
|
||||
apk,
|
||||
Buffer.concat([
|
||||
await readFile(apk),
|
||||
Buffer.from("changed after admission"),
|
||||
]),
|
||||
);
|
||||
const outcome = await provider.execute(target.value, {
|
||||
operation: "inspect_android_package",
|
||||
input: { path: apk },
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [{ message: expect.stringContaining("bytes changed") }],
|
||||
},
|
||||
});
|
||||
expect(launches).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("retains an uncertain workspace and blocks later launches after cleanup cannot be verified", async () => {
|
||||
const { service, apk, launches } = await setup("cleanup-failure");
|
||||
const outcome = await service.execute("inspect_android_package", {
|
||||
path: apk,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
const workspace = launches[0]?.cwd;
|
||||
if (workspace === undefined) throw new Error("Expected acquired workspace");
|
||||
await expect(access(workspace)).resolves.toBeUndefined();
|
||||
expect(
|
||||
await service.execute("inspect_android_package", { path: apk }),
|
||||
).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
|
||||
expect(launches).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not attribute upstream smali containing all overloads to the selected method", async () => {
|
||||
const { service, apk, launches } = await setup("overloaded-smali");
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
method_name: "choose",
|
||||
overload_index: 1,
|
||||
});
|
||||
expect(outcome).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("joins all same-name overloads"),
|
||||
},
|
||||
});
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
|
||||
it("reports missing native/abstract method source without claiming an empty implementation", async () => {
|
||||
const { service, apk, launches } = await setup("no-body");
|
||||
const outcome = await service.execute("inspect_android_method", {
|
||||
path: apk,
|
||||
class_name: "fixture.Target",
|
||||
method_name: "onCreate",
|
||||
});
|
||||
if (!outcome.ok) throw outcome.error;
|
||||
const result = androidResultSchemas.inspect_android_method.parse(
|
||||
outcome.value.normalized_result,
|
||||
);
|
||||
expect(result.body_status).toBe("not_available");
|
||||
expect(result.source.text).toContain("no decompiled body");
|
||||
await verifyCleanup(launches);
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
parseJadxEnvelope,
|
||||
parseJadxJson,
|
||||
normalizeJadxText,
|
||||
} from "../../../src/android/JadxProtocol.js";
|
||||
import { androidInputSchemas } from "../../../src/domain/androidAnalysis.js";
|
||||
|
||||
it("validates provider text envelopes and rejects unsupported content rather than dropping it", () => {
|
||||
expect(
|
||||
parseJadxEnvelope(
|
||||
{ content: [{ type: "text", text: "reported error" }], isError: true },
|
||||
"inspect_android_package",
|
||||
),
|
||||
).toEqual({ text: "reported error", failed: true });
|
||||
for (const response of [
|
||||
{ content: [] },
|
||||
{ content: [{ type: "image", data: "AA==", mimeType: "image/png" }] },
|
||||
{
|
||||
content: [
|
||||
{ type: "text", text: "first" },
|
||||
{ type: "text", text: "second" },
|
||||
],
|
||||
},
|
||||
])
|
||||
expect(() =>
|
||||
parseJadxEnvelope(response, "inspect_android_package"),
|
||||
).toThrowError("unsupported MCP content envelope");
|
||||
expect(() =>
|
||||
parseJadxJson("{malformed", "inspect_android_package"),
|
||||
).toThrowError("malformed JSON text");
|
||||
});
|
||||
|
||||
it("retains UTF-8 source and recognizes only the producer's terminal truncation marker", () => {
|
||||
expect(normalizeJadxText("日本語")).toEqual({
|
||||
text: "日本語",
|
||||
status: "complete",
|
||||
reported_total_bytes: null,
|
||||
});
|
||||
const text = "日本語\n\n... [truncated: exceeds 9 bytes, total 100 bytes]";
|
||||
expect(normalizeJadxText(text)).toEqual({
|
||||
text,
|
||||
status: "partial",
|
||||
reported_total_bytes: 100,
|
||||
});
|
||||
expect(normalizeJadxText(text + "\nmore actual source").status).toBe(
|
||||
"complete",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects invalid APK selectors and accepts an explicit zero overload without a confirmation flag", () => {
|
||||
const input = {
|
||||
path: "/fixture.apk",
|
||||
class_name: "fixture.Target",
|
||||
method_name: "choose",
|
||||
};
|
||||
expect(
|
||||
androidInputSchemas.inspect_android_method.safeParse({
|
||||
...input,
|
||||
overload_index: 0,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
androidInputSchemas.inspect_android_method.safeParse({
|
||||
...input,
|
||||
overload_index: -1,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
androidInputSchemas.inspect_android_method.safeParse({
|
||||
...input,
|
||||
overload_index: 0.5,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
androidInputSchemas.inspect_android_method.safeParse({
|
||||
...input,
|
||||
approved: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
androidInputSchemas.search_android_classes.safeParse({
|
||||
path: "/fixture.apk",
|
||||
query: "",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
withCommandCancellation,
|
||||
type CommandCancellationHost,
|
||||
} from "../../../src/cli/commandCancellation.js";
|
||||
|
||||
it.each([
|
||||
["SIGINT", 130],
|
||||
["SIGTERM", 143],
|
||||
] as const)(
|
||||
"awaits cleanup after %s and removes its listeners",
|
||||
async (event, expectedExit) => {
|
||||
const events = new EventEmitter();
|
||||
const host: CommandCancellationHost = {
|
||||
on: events.on.bind(events),
|
||||
off: events.off.bind(events),
|
||||
};
|
||||
let cleaned = false;
|
||||
const operation = withCommandCancellation(async (signal) => {
|
||||
await new Promise<void>((resolve) =>
|
||||
signal.addEventListener("abort", () => resolve(), { once: true }),
|
||||
);
|
||||
cleaned = true;
|
||||
return "cancelled after cleanup";
|
||||
}, host);
|
||||
expect(host.exitCode).toBeUndefined();
|
||||
events.emit(event);
|
||||
expect(await operation).toBe("cancelled after cleanup");
|
||||
expect(cleaned).toBe(true);
|
||||
expect(host.exitCode).toBe(expectedExit);
|
||||
expect(events.listenerCount("SIGINT")).toBe(0);
|
||||
expect(events.listenerCount("SIGTERM")).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves the exit code alone on success and removes listeners when execution throws", async () => {
|
||||
const events = new EventEmitter();
|
||||
const host: CommandCancellationHost = {
|
||||
on: events.on.bind(events),
|
||||
off: events.off.bind(events),
|
||||
exitCode: 0,
|
||||
};
|
||||
expect(await withCommandCancellation(async () => "success", host)).toBe(
|
||||
"success",
|
||||
);
|
||||
expect(host.exitCode).toBe(0);
|
||||
await expect(
|
||||
withCommandCancellation(async () => {
|
||||
throw new Error("fixture failure");
|
||||
}, host),
|
||||
).rejects.toThrow("fixture failure");
|
||||
expect(events.listenerCount("SIGINT")).toBe(0);
|
||||
expect(events.listenerCount("SIGTERM")).toBe(0);
|
||||
});
|
||||
@@ -22,6 +22,7 @@ import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/brow
|
||||
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
|
||||
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
|
||||
import { createCli } from "../../../src/cli.js";
|
||||
import { JADX_PROVIDER_IDENTITY } from "../../../src/android/JadxRelease.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
@@ -71,6 +72,7 @@ describe("canonical product catalog", () => {
|
||||
expect(catalog.providers.map(({ id }) => id).sort()).toEqual(
|
||||
[
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
JADX_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { expect, it as test, onTestFinished } from "vitest";
|
||||
import { access } from "node:fs/promises";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "../../../src/contracts/androidToolContracts.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createJadxProtocolFixture,
|
||||
verifyJadxFixtureCleanup,
|
||||
} from "../../fixtures/android/jadx.js";
|
||||
|
||||
const it = test.skipIf(process.platform === "win32");
|
||||
|
||||
it("publishes and executes all APK contracts with inline Evidence and no active binary", async () => {
|
||||
const { provider, apk, launches } = await createJadxProtocolFixture();
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("APK analysis must not acquire a deep binary provider");
|
||||
});
|
||||
const server = createServer(session, session, { androidAnalysis: provider });
|
||||
const client = new Client({
|
||||
name: "android-contract-regression",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const advertised = await client.listTools();
|
||||
for (const contract of ANDROID_TOOL_CONTRACTS) {
|
||||
const wire = advertised.tools.find((tool) => tool.name === contract.name);
|
||||
expect(wire?.annotations).toMatchObject(contract.annotations);
|
||||
expect(contract.effects).toMatchObject({
|
||||
mutatesTarget: false,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
accessesNetwork: false,
|
||||
});
|
||||
const input = {
|
||||
path: apk,
|
||||
...(contract.name === "search_android_classes"
|
||||
? { query: "Target" }
|
||||
: {}),
|
||||
...(contract.name === "inspect_android_class" ||
|
||||
contract.name === "inspect_android_method" ||
|
||||
contract.name === "trace_android_references"
|
||||
? { class_name: "fixture.Target" }
|
||||
: {}),
|
||||
...(contract.name === "inspect_android_method"
|
||||
? { method_name: "onCreate" }
|
||||
: {}),
|
||||
};
|
||||
const response = await client.callTool({
|
||||
name: contract.name,
|
||||
arguments: input,
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const result = contract.outputSchema.parse(response.structuredContent);
|
||||
const evidence = parseEvidence(result.evidence);
|
||||
expect(result.result).toEqual(evidence.normalized_result);
|
||||
expect(result.evidence_id).toBe(evidence.evidence_id);
|
||||
expect(evidence.operation).toBe(contract.name);
|
||||
expect(evidence.raw_result).not.toBeNull();
|
||||
}
|
||||
expect(launches).toHaveLength(5);
|
||||
await verifyJadxFixtureCleanup(launches);
|
||||
});
|
||||
|
||||
it("cleans an active engine when the MCP client disconnects", async () => {
|
||||
const { provider, apk, launches } = await createJadxProtocolFixture("stall");
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Unexpected native provider acquisition");
|
||||
});
|
||||
const server = createServer(session, session, { androidAnalysis: provider });
|
||||
const client = new Client({
|
||||
name: "android-disconnect-regression",
|
||||
version: "1",
|
||||
});
|
||||
onTestFinished(async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const pending = client
|
||||
.callTool({ name: "inspect_android_package", arguments: { path: apk } })
|
||||
.catch(() => undefined);
|
||||
await expect.poll(() => launches.length).toBe(1);
|
||||
await client.close();
|
||||
await pending;
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const workspace = launches[0]?.cwd;
|
||||
if (workspace === undefined) return false;
|
||||
try {
|
||||
await access(workspace);
|
||||
return false;
|
||||
} catch (cause) {
|
||||
return (
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT"
|
||||
);
|
||||
}
|
||||
})
|
||||
.toBe(true);
|
||||
await verifyJadxFixtureCleanup(launches);
|
||||
});
|
||||
Vendored
+135
@@ -0,0 +1,135 @@
|
||||
import { McpServer } from "@modelcontextprotocol/server";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
||||
import { z } from "zod";
|
||||
|
||||
// An actual child MCP server exercising the production stdio/process seam.
|
||||
// It is a protocol fixture, not evidence of JADX decompiler support.
|
||||
const mode = process.env.REA_FAKE_JADX_MODE ?? "normal";
|
||||
const server = new McpServer({
|
||||
name: "jadx-headless-mcp",
|
||||
version: mode === "version" ? "99.0.0" : "0.7.1",
|
||||
});
|
||||
const classes = [
|
||||
"fixture.Target",
|
||||
...Array.from({ length: 400 }, (_, index) => `fixture.Class${index}`),
|
||||
];
|
||||
const methods = [
|
||||
{
|
||||
name: "onCreate",
|
||||
signature: "onCreate(Bundle): void",
|
||||
is_constructor: false,
|
||||
def_pos: 0,
|
||||
},
|
||||
{
|
||||
name: "choose",
|
||||
signature: "choose(String): void",
|
||||
is_constructor: false,
|
||||
def_pos: 0,
|
||||
},
|
||||
{
|
||||
name: "choose",
|
||||
signature: "choose(int): void",
|
||||
is_constructor: false,
|
||||
def_pos: 0,
|
||||
},
|
||||
];
|
||||
const text = (value) => ({ content: [{ type: "text", text: value }] });
|
||||
const json = (value) => text(JSON.stringify(value));
|
||||
const register = (name, handler) =>
|
||||
server.registerTool(name, { inputSchema: z.looseObject({}) }, handler);
|
||||
register("load_apk", async ({ path }) => {
|
||||
if (mode === "stall") await new Promise(() => {});
|
||||
return json({
|
||||
state: "LOADED",
|
||||
apk_path: mode === "wrong-apk" ? "/different.apk" : path,
|
||||
class_count: classes.length,
|
||||
resource_count: 1,
|
||||
threads: 1,
|
||||
resources: "full",
|
||||
});
|
||||
});
|
||||
register("get_app_info", () =>
|
||||
json({
|
||||
package: "fixture",
|
||||
version_name: "1",
|
||||
version_code: "1",
|
||||
min_sdk: "26",
|
||||
target_sdk: "33",
|
||||
permissions: ["android.permission.INTERNET"],
|
||||
}),
|
||||
);
|
||||
register("get_android_manifest", () => {
|
||||
if (mode === "tool-error")
|
||||
return {
|
||||
...text("manifest decoder rejected malformed binary XML"),
|
||||
isError: true,
|
||||
};
|
||||
if (mode === "frame-overflow") return text("x".repeat(9 * 1024 * 1024));
|
||||
return text('<manifest package="fixture"/>');
|
||||
});
|
||||
register("list_classes", ({ offset, limit }) =>
|
||||
json({
|
||||
total: classes.length,
|
||||
offset,
|
||||
limit,
|
||||
items: mode === "empty-page" ? [] : classes.slice(offset, offset + limit),
|
||||
}),
|
||||
);
|
||||
register("get_class_summary", () =>
|
||||
json({
|
||||
full_name: mode === "wrong-class" ? "fixture.Other" : "fixture.Target",
|
||||
name: "Target",
|
||||
method_count: mode === "summary-error" ? -1 : methods.length,
|
||||
field_count: 0,
|
||||
inner_class_count: 0,
|
||||
methods: mode === "summary-error" ? [] : methods,
|
||||
fields: [],
|
||||
inner_classes: [],
|
||||
...(mode === "summary-error" ? { error: "summary timed out" } : {}),
|
||||
}),
|
||||
);
|
||||
register("get_method_body", ({ method_name, overload_index }) =>
|
||||
json({
|
||||
class_name: "fixture.Target",
|
||||
method_name,
|
||||
full_name: `fixture.Target.${method_name}`,
|
||||
overload_index:
|
||||
mode === "wrong-method" ? overload_index + 1 : overload_index,
|
||||
overload_count: method_name === "choose" ? 2 : 1,
|
||||
mode: mode === "smali" || mode === "overloaded-smali" ? "smali" : "java",
|
||||
fell_back: mode === "smali" || mode === "overloaded-smali",
|
||||
markers:
|
||||
mode === "smali" || mode === "overloaded-smali"
|
||||
? ["Method not decompiled"]
|
||||
: [],
|
||||
body:
|
||||
mode === "no-body"
|
||||
? "// method exists but has no decompiled body (native/abstract)"
|
||||
: mode === "body-error"
|
||||
? "// ERROR: decompile timed out or failed"
|
||||
: mode === "truncated"
|
||||
? "void onCreate(){}\n\n... [truncated: exceeds 18 bytes, total 100 bytes]"
|
||||
: `void ${method_name}() { /* overload ${overload_index} */ }`,
|
||||
}),
|
||||
);
|
||||
for (const name of ["get_xrefs_to_class", "get_xrefs_to_method"])
|
||||
register(name, ({ class_name, method_name }) =>
|
||||
json({
|
||||
target:
|
||||
method_name === undefined ? class_name : `${class_name}.${method_name}`,
|
||||
total: mode === "partial-xrefs" ? 2 : 1,
|
||||
count: 1,
|
||||
resolve_line: false,
|
||||
items: [
|
||||
{
|
||||
kind: "method",
|
||||
name: "caller",
|
||||
full_name: "fixture.Other.caller",
|
||||
containing_class: "fixture.Other",
|
||||
top_class: "fixture.Other",
|
||||
def_pos: 42,
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
await server.connect(new StdioServerTransport());
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
import { access, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, onTestFinished } from "vitest";
|
||||
import { AndroidAnalysisService } from "../../../src/application/AndroidAnalysisService.js";
|
||||
import { JadxProvider } from "../../../src/android/JadxProvider.js";
|
||||
import {
|
||||
ProviderProcessSupervisor,
|
||||
spawnOwnedProviderProcess,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
||||
import { writeOrderedZip } from "../artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../temporaryDirectory.js";
|
||||
|
||||
const fixture = fileURLToPath(new URL("./jadx-mcp.mjs", import.meta.url));
|
||||
|
||||
/** Real owned subprocess running a synthetic MCP producer, with no module mocks. */
|
||||
export const createJadxProtocolFixture = async (mode = "normal") => {
|
||||
const root = await createTestTempDirectory("rea-android-boundary-");
|
||||
const apk = join(root, "fixture.apk");
|
||||
const jar = join(root, "fixture.jar");
|
||||
await writeOrderedZip(apk, ["AndroidManifest.xml", "classes.dex"]);
|
||||
await writeFile(jar, "synthetic engine bytes; not a Java archive");
|
||||
const launches: {
|
||||
runId: string;
|
||||
cwd: string | undefined;
|
||||
pid: number | undefined;
|
||||
}[] = [];
|
||||
const provider = new JadxProvider(
|
||||
{ ...process.env, REA_JADX_MCP_JAR: jar },
|
||||
async (options) => {
|
||||
const spawned = await spawnOwnedProviderProcess({
|
||||
...options,
|
||||
command: process.execPath,
|
||||
arguments: [fixture],
|
||||
expectedCommand: process.execPath,
|
||||
env: { ...options.env, REA_FAKE_JADX_MODE: mode },
|
||||
});
|
||||
launches.push({
|
||||
runId: options.runId,
|
||||
cwd: options.cwd,
|
||||
pid: spawned.process.pid,
|
||||
});
|
||||
if (mode === "cleanup-failure") {
|
||||
onTestFinished(async () => {
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup: () => cleanupOwnedProcessGroup(spawned.ownership),
|
||||
});
|
||||
expect((await supervisor.stop()).status).not.toBe("incomplete");
|
||||
if (options.cwd !== undefined)
|
||||
await rm(options.cwd, { recursive: true, force: true });
|
||||
});
|
||||
return {
|
||||
...spawned,
|
||||
cleanup: async () => ({
|
||||
cleaned: false,
|
||||
reason: "injected ownership verification failure",
|
||||
}),
|
||||
};
|
||||
}
|
||||
return spawned;
|
||||
},
|
||||
);
|
||||
return {
|
||||
service: new AndroidAnalysisService(provider),
|
||||
provider,
|
||||
apk,
|
||||
jar,
|
||||
launches,
|
||||
};
|
||||
};
|
||||
|
||||
/** Verify only this fixture's acquired group and workspace, without scanning unrelated host environments. */
|
||||
export const verifyJadxFixtureCleanup = async (
|
||||
launches: Awaited<ReturnType<typeof createJadxProtocolFixture>>["launches"],
|
||||
): Promise<void> => {
|
||||
for (const launch of launches) {
|
||||
const pid = launch.pid;
|
||||
if (pid !== undefined)
|
||||
expect(() => process.kill(-pid, 0)).toThrowError(
|
||||
expect.objectContaining({ code: "ESRCH" }),
|
||||
);
|
||||
if (launch.cwd !== undefined)
|
||||
await expect(access(launch.cwd)).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user