Skip to content

armgit / rea

Public Imported from GitHub
0

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

fix(tests): stabilize process fixtures and malformed input coverage (#6570)

gensokyo-devcc8835c7a316
diff --git a/tests/boundary/browser/cdpScriptMetadata.test.ts b/tests/boundary/browser/cdpScriptMetadata.test.ts
index 765bfa122..5ca2de86e 100644
--- a/tests/boundary/browser/cdpScriptMetadata.test.ts
+++ b/tests/boundary/browser/cdpScriptMetadata.test.ts
@@ -228,9 +228,9 @@ describe("Inspector script exclusions", () => {
completeness: parsed?.inspection.completeness,
};
};
- const failedToParse = {
+ const invalidFailedToParse = {
method: "Debugger.scriptFailedToParse",
- params: { scriptId: "failed-script", url: "", executionContextId: 1 },
+ params: { scriptId: 42, url: "", executionContextId: 1 },
};
const missingUrl = {
method: "Debugger.scriptParsed",
@@ -239,7 +239,7 @@ describe("Inspector script exclusions", () => {
it("keeps invalid protocol scripts out of policy filtering", async () => {
const { producer, completeness } = await reconcileV8Scripts([
- failedToParse,
+ invalidFailedToParse,
missingUrl,
]);
expect(producer).toEqual({
@@ -259,7 +259,7 @@ describe("Inspector script exclusions", () => {
it("reports unsupported and invalid script exclusions separately", async () => {
const { producer, completeness } = await reconcileV8Scripts([
- failedToParse,
+ invalidFailedToParse,
{
method: "Debugger.scriptParsed",
params: {
diff --git a/tests/boundary/go/goBinaryImage.test.ts b/tests/boundary/go/goBinaryImage.test.ts
index 5df7d8244..ad1b0c827 100644
--- a/tests/boundary/go/goBinaryImage.test.ts
+++ b/tests/boundary/go/goBinaryImage.test.ts
@@ -358,6 +358,9 @@ it("distinguishes unsupported containers from malformed recognized images", () =
/truncated/i,
);
const pe = createGoBinaryFixture({ format: "pe" });
+ expect(() => readGoBinaryImage(pe.bytes.subarray(0, 144))).toThrowError(
+ /range|truncated/i,
+ );
pe.bytes.writeUInt32LE(0xfffffff0, 60);
expect(() => readGoBinaryImage(pe.bytes)).toThrowError(
/MZ Windows new-header candidate is unresolved/i,
diff --git a/tests/boundary/process/cleanLinuxHopperRuntime.test.ts b/tests/boundary/process/cleanLinuxHopperRuntime.test.ts
index 410d713e4..90e0bb6a2 100644
--- a/tests/boundary/process/cleanLinuxHopperRuntime.test.ts
+++ b/tests/boundary/process/cleanLinuxHopperRuntime.test.ts
@@ -10,6 +10,7 @@ import {
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
+import { createInterface } from "node:readline";
import { promisify } from "node:util";
import { expect, it } from "vitest";
@@ -17,6 +18,10 @@ import { expect, it } from "vitest";
import { assertCleanLinuxHopperRuntime } from "../../../scripts/lib/clean-linux-hopper-runtime.mjs";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import {
+ prepareRenamedNodeLauncher,
+ retainedRuntimeNodeCode,
+} from "../../fixtures/retainedRuntimeNode.js";
const execFileAsync = promisify(execFile);
@@ -56,10 +61,14 @@ finally:
],
{ timeout: 10_000 },
);
+ if (parent.child.stdout === null)
+ throw new Error("Fixture parent has no readiness pipe");
+ const lines = createInterface({ input: parent.child.stdout });
const ready = new Promise<number>((resolve, reject) => {
- parent.child.stdout?.once("data", (data: Buffer) =>
- resolve(Number(data.toString().trim())),
- );
+ lines.once("line", (line) => {
+ lines.close();
+ resolve(Number(line.trim()));
+ });
parent.catch(reject);
});
let zombiePid: number | undefined;
@@ -190,11 +199,15 @@ finally:
timeout: 40_000,
},
);
+ if (reaper.child.stdout === null)
+ throw new Error("Fixture reaper has no readiness pipe");
+ const lines = createInterface({ input: reaper.child.stdout });
const ready = new Promise<{ pid: number; parentPid: number }>(
(resolve, reject) => {
- reaper.child.stdout?.once("data", (data: Buffer) => {
+ lines.once("line", (line) => {
+ lines.close();
try {
- resolve(JSON.parse(data.toString()));
+ resolve(JSON.parse(line));
} catch (error) {
reject(error);
}
@@ -270,8 +283,6 @@ it.runIf(process.platform === "linux").each([
"classifies a reparented %s without signaling it",
async (mode, pythonOptions, retained) => {
const runId = randomUUID();
- const childCode =
- "process.title = 'Xvfb'; setInterval(() => {}, 1000); process.send('ready');";
const directory = await createTestTempDirectory("rea-clean-runtime-test-");
const procRoot = join(directory, "proc");
await mkdir(procRoot);
@@ -280,11 +291,10 @@ it.runIf(process.platform === "linux").each([
const helper = join(directory, "hopper-demo-x11.py");
const alternateMode = mode === "alternate launcher";
const pythonMode = pythonOptions !== null;
- if (alternateMode) {
- await copyFile("/usr/bin/sleep", launcher);
- await chmod(launcher, 0o700);
- await symlink(launcher, alternate);
- }
+ const childCode = retainedRuntimeNodeCode(
+ alternateMode ? undefined : "Xvfb",
+ );
+ if (alternateMode) await prepareRenamedNodeLauncher(launcher, alternate);
if (pythonMode) {
await writeFile(
helper,
@@ -303,16 +313,12 @@ it.runIf(process.platform === "linux").each([
: pythonMode
? "/usr/bin/python3"
: process.execPath;
- const arguments_ = alternateMode
- ? ["30"]
- : pythonMode
- ? [...pythonOptions, helper]
- : ["-e", childCode];
- const stdio = alternateMode
- ? "ignore"
- : pythonMode
- ? ["ignore", "pipe", "ignore"]
- : ["ignore", "ignore", "ignore", "ipc"];
+ const arguments_ = pythonMode
+ ? [...pythonOptions, helper]
+ : ["-e", childCode];
+ const stdio = pythonMode
+ ? ["ignore", "pipe", "ignore"]
+ : ["ignore", "ignore", "ignore", "ipc"];
const parentCode = `
const { spawn } = require('node:child_process');
const child = spawn(${JSON.stringify(command)}, ${JSON.stringify(arguments_)}, {
@@ -325,7 +331,7 @@ it.runIf(process.platform === "linux").each([
child.stdout?.destroy();
child.unref();
};
- ${pythonMode ? "child.stdout.once('data', ready);" : `child.once(${JSON.stringify(alternateMode ? "spawn" : "message")}, ready);`}
+ ${pythonMode ? "require('node:readline').createInterface({ input: child.stdout }).once('line', ready);" : "child.once('message', ready);"}
`;
const { reaper, ready } = launchReapedOrphan(runId, parentCode);
let orphanPid: number | undefined;
diff --git a/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts b/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
index c661fcc44..a084f5a18 100644
--- a/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
+++ b/tests/boundary/providers/adb/adbInputSnapshotOwnership.test.ts
@@ -40,6 +40,7 @@ const fixture = async () => {
const root = await createTestTempDirectory("rea-adb-input-owner-");
const binary = join(root, "adb");
const source = join(root, "payload.bin");
+ const devicePath = "/data/local/tmp/payload.bin";
const bytes = Buffer.from("immutable payload");
await writeFile(source, bytes);
const digest = createHash("sha256").update(bytes).digest("hex");
@@ -56,27 +57,44 @@ const fixture = async () => {
return output(
`Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`,
);
- return output("");
+ throw new Error(`Unexpected ADB fixture command: ${JSON.stringify(args)}`);
});
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
- if (args[2] === "push") {
+ if (args[2] === "shell" && args[3] === "test" && args[5] === devicePath) {
+ if (args[4] === "-d")
+ throw Object.assign(new Error("Selected destination is a file"), {
+ code: 1,
+ stdout: "",
+ stderr: "",
+ signal: null,
+ killed: false,
+ });
+ if (args[4] === "-e")
+ return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
+ }
+ if (args[2] === "push" && args[4] === devicePath) {
snapshotPath = args[3]!;
consumedBytes = await readFile(snapshotPath);
if (consumedBytes.byteLength === 0)
throw new Error("adb received an empty local snapshot");
+ return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
}
- if (args[3] === "sha256sum") {
+ if (
+ args[2] === "shell" &&
+ args[3] === "sha256sum" &&
+ args[4] === devicePath
+ ) {
if (consumedBytes === undefined)
throw new Error("checksum requested before a push was consumed");
const consumedDigest = createHash("sha256")
.update(consumedBytes)
.digest("hex");
return {
- stdout: Buffer.from(`${consumedDigest} /data/local/tmp/payload.bin\n`),
+ stdout: Buffer.from(`${consumedDigest} ${devicePath}\n`),
stderr: Buffer.alloc(0),
};
}
- return { stdout: Buffer.alloc(0), stderr: Buffer.alloc(0) };
+ throw new Error(`Unexpected ADB fixture command: ${JSON.stringify(args)}`);
});
const provider = new AdbProvider({ environment: { REA_ADB_PATH: binary } });
onTestFinished(() => provider.close());
@@ -91,7 +109,7 @@ const fixture = async () => {
input: {
serial: "device",
local_path: source,
- device_path: "/data/local/tmp/payload.bin",
+ device_path: devicePath,
overwrite: true,
},
},
diff --git a/tests/fixtures/retainedRuntimeNode.ts b/tests/fixtures/retainedRuntimeNode.ts
new file mode 100644
index 000000000..6bbec4011
--- /dev/null
+++ b/tests/fixtures/retainedRuntimeNode.ts
@@ -0,0 +1,16 @@
+import { constants } from "node:fs";
+import { chmod, copyFile, symlink } from "node:fs/promises";
+
+/** A controlled Node child announces readiness and expires even if its PID is never received. */
+export const retainedRuntimeNodeCode = (displayName?: string): string =>
+ `${displayName === undefined ? "" : `process.title = ${JSON.stringify(displayName)}; `}setTimeout(() => process.exit(0), 30_000); process.send('ready');`;
+
+/** Give the fixture a distinct executable identity without relying on host multicall utilities. */
+export const prepareRenamedNodeLauncher = async (
+ launcher: string,
+ alternate: string,
+): Promise<void> => {
+ await copyFile(process.execPath, launcher, constants.COPYFILE_FICLONE);
+ await chmod(launcher, 0o700);
+ await symlink(launcher, alternate);
+};
diff --git a/tests/process-global/cleanLinuxHopperRuntime.test.ts b/tests/process-global/cleanLinuxHopperRuntime.test.ts
index 00f02d6ec..0f4ef0bda 100644
--- a/tests/process-global/cleanLinuxHopperRuntime.test.ts
+++ b/tests/process-global/cleanLinuxHopperRuntime.test.ts
@@ -1,13 +1,6 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
-import {
- chmod,
- copyFile,
- mkdir,
- readFile,
- symlink,
- unlink,
-} from "node:fs/promises";
+import { mkdir, readFile, symlink, unlink } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -17,6 +10,10 @@ import { assertCleanLinuxHopperRuntime } from "../../scripts/lib/clean-linux-hop
import { completeVerifierRun } from "../../scripts/lib/verifier-run.mjs";
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
+import {
+ prepareRenamedNodeLauncher,
+ retainedRuntimeNodeCode,
+} from "../fixtures/retainedRuntimeNode.js";
const execFileAsync = promisify(execFile);
@@ -26,19 +23,16 @@ it
"rejects a reparented %s without signaling it",
async (mode) => {
const runId = randomUUID();
- const childCode =
- "process.title = 'Xvfb'; setInterval(() => {}, 1000); process.send('ready');";
const directory = await createTestTempDirectory("rea-clean-runtime-test-");
const launcher = join(directory, "Hopper");
const alternate = join(directory, "Hopper-alternate");
const procRoot = join(directory, "proc");
await mkdir(procRoot);
const alternateMode = mode === "alternate launcher";
- if (alternateMode) {
- await copyFile("/usr/bin/sleep", launcher);
- await chmod(launcher, 0o700);
- await symlink(launcher, alternate);
- }
+ const childCode = retainedRuntimeNodeCode(
+ alternateMode ? undefined : "Xvfb",
+ );
+ if (alternateMode) await prepareRenamedNodeLauncher(launcher, alternate);
// A rejection must come from the fixture we are about to launch. An
// existing Xvfb would otherwise mask a broken executable-identity check.
// The copied launcher has a unique file identity and has not run yet.
@@ -49,14 +43,14 @@ it
procRoot,
);
const command = alternateMode ? alternate : process.execPath;
- const arguments_ = alternateMode ? ["30"] : ["-e", childCode];
+ const arguments_ = ["-e", childCode];
const parentCode = `
const { spawn } = require('node:child_process');
const child = spawn(${JSON.stringify(command)}, ${JSON.stringify(arguments_)}, {
- detached: true, stdio: ${JSON.stringify(alternateMode ? "ignore" : ["ignore", "ignore", "ignore", "ipc"])}
+ detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"]
});
child.once('error', () => process.exit(1));
- child.once(${JSON.stringify(alternateMode ? "spawn" : "message")}, () => {
+ child.once('message', () => {
process.stdout.write(JSON.stringify({ pid: child.pid, parentPid: process.pid }));
if (child.connected) child.disconnect();
child.unref();