mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 03:33:25 +00:00
* fix(pcap): report a refused tool launch as an unavailable tool When a capture read's tool launch was refused with EPERM, pcap reported it as unreadable tool output (AnalysisProtocolError) instead of an unavailable tool. Pcap also never told "not executable" apart from "missing". Add classifyLaunchFailure in src/process as the one owner of which spawn errnos mean missing (ENOENT, ENOTDIR) and which mean present but not executable (EACCES, EPERM, ENOEXEC, EISDIR). Pcap, apktool and gdb used three different errno lists; all three now use it. * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * refactor(process): classify Java and adb launch refusals with the shared owner (#10598) The Ghidra and JADX Java probes and adb's version probe now take missing-versus-not-executable from classifyLaunchFailure instead of their own errno checks. ELOOP and ENAMETOOLONG join the owner's missing set, so adb keeps its existing classification and both Java probes now treat a non-directory path component as a missing runtime. * fix(pcap): preserve command launch attribution * test(pcap): expect an unknown failing stage when a limited capture tool exits unsuccessfully * refactor(process): classify owned command outcomes through one owner Add ProviderOutcome, read once from the supervisor's facts, and classifyProviderOutcome, the one mapping from an outcome to a typed error. Migrate pcap and the shared artifact producer command failure (TShark, sigrok). Add the rea/provider-failure-classifier lint rule with a shrink-only baseline of per-site (cause: unknown) => AnalysisError functions. * test(lint): cover baselined files in the provider-failure classifier rule * fix(apktool): report the decoder JVM's heap exhaustion as memory, not a target refusal The supervisor now watches for a managed runtime's out-of-memory report while output streams (JVM java.lang.OutOfMemoryError, V8 'JavaScript heap out of memory'), so a retention budget cannot hide it. ProviderOutcome gains a runtime-exhausted kind and classifyProviderOutcome maps it once. Apktool decode opts in and moves to the shared classifier; Ghidra's single-purpose output token becomes the JVM runtime option and its area matching reuses the shared table. * fix(process): keep the runtime's out-of-memory report on the memory error it supports * fix(pcap): attribute a limited capture's exit through the prlimit wrapper * fix(process): keep a shortened out-of-memory line marked as shortened * fix(process): identify the refused executable for every launcher shape Name the executable on errnos Node throws synchronously from spawn (ENOEXEC, ENOTDIR, ...) and read the Windows native launcher's executable-launch constraint, so pcap attributes those refusals to the selected tool or limiter instead of an unknown stage. * test(pcap): prove synchronous launch naming with ENOTDIR on every POSIX host * fix(apktool): advise the JVM limit that governs the reported memory area * fix(ghidra): read the supervisor's parsed OOM area instead of reparsing lines * fix(sqlite,capture): read V8 heap exhaustion from streamed output, not retained stderr (#10724) The SQLite worker and the Node capture decoders now declare runtime: "v8", so the supervisor observes V8's heap report as output streams. Both classifiers read the runtime-exhausted outcome instead of matching retained stderr, so a report beyond the retention budget, or one whose process then overflowed its output budget, is still reported as memory exhaustion. * refactor(evm): classify EVMole worker outcomes through the shared provider classifier (#10716) * refactor(evm): classify EVMole worker outcomes through the shared provider classifier The EVMole worker's cancellation, deadline, output budget and CPU/file-size signals now go through classifyProviderOutcome; only the prlimit launch refusal and the reserved EFBIG exit remain in its dialect. The worker is opted into V8 exhaustion scanning so a heap report names its fixed 256 MiB heap. providerOutcomeOf now reads a launch refusal only from a spawn errno, so a private-storage or carrier read errno is no longer reported as a limiter launch failure. * fix(evm): keep a stream failure's exit status and update Linux worker expectations * refactor(process): read launch refusals through the launcher identity owner * refactor(wasm): classify WABT command outcomes through the shared provider classifier (#10727) * refactor(wasm): classify WABT command outcomes through the shared provider classifier WABT's cancellation, command deadline, output budget, and inherited-limit signals now go through classifyProviderOutcome; its dialect keeps only the configuration-probe and launch-refusal unavailability and the unclassified-exit output error. A tool ended by SIGXCPU/SIGXFSZ or the memory limit is now a resource constraint instead of an output error, and a refused launch in the producer phase is reported as unavailable. The shared timeout context gains the analysis setting that selected the deadline, and the output-limit context may name its exceeded budget. * fix(wasm): keep setup guidance when a WABT version probe's output cannot be collected * refactor(providers): classify raw provider failures through one owner * refactor(process): build classified cancellations with cancelledBy and the carried caller reason * chore(lint): count runOwned's close-failure mapper from main in the classifier baseline * fix(process): carry the runtime's exhaustion report on every memory error that claims it SQLite and historical-capture memory errors recognised a streamed V8 heap report but dropped it, so a report outside retained output reached callers without its source line or omission flags. One projection, runtimeExhaustionReport, now owns that shape for the shared classifier and both consumers. Also lowers the EVMole and WABT cancellation-constructor baselines. * fix(process): keep the provider's recovery for a native-thread exhaustion report The shared classifier replaced the provider-supplied recovery with generic capacity advice whenever the JVM reported it could not create a native thread, dropping Apktool's launcher guidance and flipping retryable to true. The provider's recovery now wins; the capacity advice remains the fallback for providers that supply none. * refactor(pwntools): classify pwntools failures through the shared provider classifier (#10782) * refactor(pwntools): classify pwntools failures through the shared provider classifier pwntools' per-site classifier is replaced by pwntoolsFailureDialect for classifyProviderFailure. Command outcomes go through classifyProviderOutcome, launch refusals through launcherRefusalOf instead of a 'spawn ' syscall prefix check, the input limit through the file dialect's fileSize, and the cleanup report through commandCleanup. The shared read cancellation now carries the reader's partial observation, and resource-signal reports accept provider detail. * fix(pwntools): report a failed command's output once and expect resource_constraint for overflow The shared outcome owner already attaches the command's output as capturedOutput, so the pwntools adapter fallback no longer copies the same text into diagnostics.stdout, diagnostics.stderr and diagnostics.captured_output; diagnostics keep the exit facts. Update the overflow expectations the dialect migration missed (layout provider cleanup and over-budget rows, pwntools cleanup) to resource_constraint. * refactor(wasm): leave WABT cancellation to the shared owners WabtFailures matched any Error named AbortError as a cancellation. No WABT path produces one: reads, path checks and owned commands report cancellation as ArtifactReaderFailure or OwnedCommandFailure, which classifyProviderFailure and classifyProviderOutcome already classify with the caller's reason. The provider's two signal checks now build the cancellation with cancelledBy. Lowers the AnalysisCancelledError constructor baseline for both WABT files to zero. * fix(wasm): report a cancelled snapshot write as the caller's cancellation The private snapshot write passed the caller's signal to Node's writeFile, whose abort envelope reached the dialect's unclassified output failure once the name-based AbortError guess was removed. The write now turns the envelope carrying its own signal's reason into cancelledBy at the producer. * refactor(firmware): classify firmware failures through the shared provider classifier (#10810) Firmware producers now report their own deadline expiry: the start check, the output inventory and launcher admission throw the phase timeout where they observe the abort, and a read the phase signal cancelled reports it through the dialect's interruption. The classifier no longer rereads a cancellation's reason as a timeout. A new readCleanup hook keeps firmware's cleanup report shape. * refactor(captures): classify TShark, sigrok and pcap failures through the shared provider classifier TsharkCaptureProvider and SigrokRecordingProvider replace #failure with a dialect, and PcapProvider replaces analysisFailure and the tool-identity classifier. ArtifactAnalysisResources exposes its command context and a readCleanupFailure composer so the readCleanup hook keeps each provider's cleanup report shape. * refactor(jeb): classify JEB failures through the shared provider classifier JEB's raw MCP failures go through classifyProviderFailure with a JEB dialect; a typed attribution step reports a shared phase's failure under the REA operation. Each MCP phase deadline now reports its own interruption when it aborts, deciding a cancellation's owner from the caller's own signal instead of comparing abort reasons. A refusal carrying the JVM's OutOfMemoryError report becomes a resource constraint naming JEB's Java heap. * fix(jeb): advise the JVM limit that governs the reported memory area * refactor(ghidra): classify Ghidra failures through the shared provider classifier PSP extension inspection reports through classifyProviderFailure with a Ghidra dialect. The startup deadline decides at abort time whether the shared startup owner closed it, so Ghidra and Hopper no longer compare the abort reason with the owner's sentinel, and Ghidra's startup no longer compares a producer cancellation's reason with the deadline's. Three helpers that only construct one error kind now name that kind instead of AnalysisError. * refactor(hopper): classify original-source read failures through the shared provider classifier (#10838) * test(ghidra): pin the aborted startup deadline over a producer cancellation * refactor(kuna): classify Kuna failures through the shared provider classifier Session operations, the workspace copy and the project export report raw failures through classifyProviderFailure with Kuna dialects; the copy and export keep their cleanup report shapes through the readCleanup hook. * refactor(adb): report a pulled file's digest failure from its own type * refactor(sqlite): classify worker-reply read failures through the shared provider classifier * refactor(ghidra): classify Ghidra failures through the shared provider classifier (#10836) * refactor(ghidra): classify Ghidra failures through the shared provider classifier PSP extension inspection reports through classifyProviderFailure with a Ghidra dialect. The startup deadline decides at abort time whether the shared startup owner closed it, so Ghidra and Hopper no longer compare the abort reason with the owner's sentinel, and Ghidra's startup no longer compares a producer cancellation's reason with the deadline's. Three helpers that only construct one error kind now name that kind instead of AnalysisError. * refactor(hopper): classify original-source read failures through the shared provider classifier (#10838) * test(ghidra): pin the aborted startup deadline over a producer cancellation * refactor(kuna): classify Kuna failures through the shared provider classifier (#10843) Session operations, the workspace copy and the project export report raw failures through classifyProviderFailure with Kuna dialects; the copy and export keep their cleanup report shapes through the readCleanup hook. * chore(guards): shrink the cancellation construction baseline after merging the base * refactor(ida): classify IDA operation failures through the shared provider classifier (#10859) * refactor(ida): classify IDA operation failures through the shared provider classifier * refactor(process): let artifact-resource consumers classify through the shared provider classifier (#10867) * test(providers): pin attribution of a cleanup-failed read's typed primary
558 lines
21 KiB
TypeScript
558 lines
21 KiB
TypeScript
import {
|
|
chmod,
|
|
mkdir,
|
|
readdir,
|
|
realpath,
|
|
symlink,
|
|
unlink,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { createArtifactAnalysisResources } from "../../../src/providers/artifactResourceFailure.js";
|
|
import { join } from "node:path";
|
|
import { expect, it, onTestFinished, vi } from "vitest";
|
|
|
|
import { FirmwareProvider } from "../../../src/firmware/FirmwareProvider.js";
|
|
import { FirmwareAnalysisService } from "../../../src/application/firmware/FirmwareAnalysisService.js";
|
|
import { FirmwareFileAccess } from "../../../src/firmware/FirmwareFiles.js";
|
|
import { WakaruProvider } from "../../../src/javascript/recovery/WakaruProvider.js";
|
|
import { JavaScriptRecoveryService } from "../../../src/application/javascript/JavaScriptRecoveryService.js";
|
|
import {
|
|
spawnOwnedProviderProcess,
|
|
type ProviderProcessSupervisor,
|
|
} from "../../../src/process/ProviderProcess.js";
|
|
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
|
|
import { observeProcessStartIdentity } from "../../../src/process/ProcessOwnershipObservation.js";
|
|
import { AnalysisError } from "../../../src/domain/analysisErrorBase.js";
|
|
import { fileURLToPath } from "node:url";
|
|
import { preparePcapNativeBound } from "../../../src/pcap/PcapNativeBound.js";
|
|
import { runPcapCommand } from "../../../src/pcap/PcapCommand.js";
|
|
import { ArtifactAnalysisResources } from "../../../src/process/ArtifactAnalysisResources.js";
|
|
import { PacketCaptureService } from "../../../src/application/captures/PacketCaptureService.js";
|
|
import { SignalRecordingService } from "../../../src/application/signals/SignalRecordingService.js";
|
|
import { TsharkCaptureProvider } from "../../../src/captures/TsharkCaptureProvider.js";
|
|
import { SigrokRecordingProvider } from "../../../src/signals/SigrokRecordingProvider.js";
|
|
import { readStableArtifact } from "../../../src/artifacts/readStableArtifact.js";
|
|
import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js";
|
|
import type { LinuxResourceLimits } from "../../../src/process/LinuxResourceLimits.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
import { releaseOwnedCleanup } from "../../support/cleanupRelease.js";
|
|
|
|
// Real children and filesystem, with simulated Linux admission/limits. These
|
|
// scripts do not establish native TShark, sigrok or prlimit behavior.
|
|
it.skipIf(process.platform === "win32").each(["tshark", "sigrok"] as const)(
|
|
"executes selected %s and limiter wrappers, retaining identity failure output after success",
|
|
async (kind) => {
|
|
const directory = await createTestTempDirectory("rea-selected-producer-");
|
|
const bin = join(directory, "bin"),
|
|
libexec = join(directory, "libexec");
|
|
await mkdir(bin);
|
|
await mkdir(libexec);
|
|
const command = join(bin, kind),
|
|
limiter = join(bin, "prlimit");
|
|
const commandSource = join(libexec, "producer"),
|
|
limiterSource = join(libexec, "limiter");
|
|
const replacement = join(libexec, "replacement");
|
|
const script =
|
|
'#!/bin/sh\nselected="${0%/*}/${0##*/}"\nIFS= read -r role < "$selected.role" || exit 19\nif [ "$role" = limiter ]; then\n if [ -f "$selected.retarget" ]; then\n IFS= read -r target < "$selected.retarget"\n /bin/ln -sf "$target" "$0"\n fi\n while [ "$1" != -- ]; do shift; done\n shift\n exec "$@"\nfi\nif [ "$1" = --version ]; then\n if [ "$role" = tshark ]; then printf "TShark (Wireshark) 4.6.9\\n"; else printf "sigrok-cli 0.7.2\\nlibsigrokdecode 0.5.3\\n"; fi\nelse\n if [ "$role" = tshark ]; then printf "P\\tInternet Protocol\\tip\\n"; else printf "Supported protocol decoders:\\n uart UART\\n"; fi\nfi\n';
|
|
for (const path of [commandSource, limiterSource, replacement]) {
|
|
await writeFile(path, script);
|
|
await chmod(path, 0o755);
|
|
}
|
|
await symlink(commandSource, command);
|
|
await symlink(limiterSource, limiter);
|
|
await writeFile(`${command}.role`, `${kind}\n`);
|
|
await writeFile(`${limiter}.role`, "limiter\n");
|
|
const environment = {
|
|
...process.env,
|
|
...(kind === "tshark"
|
|
? { REA_TSHARK_COMMAND: command, REA_TSHARK_PRLIMIT_COMMAND: limiter }
|
|
: { REA_SIGROK_COMMAND: command, REA_SIGROK_PRLIMIT_COMMAND: limiter }),
|
|
};
|
|
const runtime = () =>
|
|
PrivateRuntimeRoot.create({ parent: directory, prefix: "workspace-" });
|
|
const limits = async (configured: LinuxResourceLimits) => configured;
|
|
const provider =
|
|
kind === "tshark"
|
|
? new TsharkCaptureProvider(
|
|
environment,
|
|
undefined,
|
|
runtime,
|
|
"linux",
|
|
readStableArtifact,
|
|
limits,
|
|
)
|
|
: new SigrokRecordingProvider(
|
|
environment,
|
|
undefined,
|
|
runtime,
|
|
"linux",
|
|
readStableArtifact,
|
|
limits,
|
|
);
|
|
onTestFinished(() => provider.close());
|
|
const inspect =
|
|
provider instanceof TsharkCaptureProvider
|
|
? () => new PacketCaptureService(provider).inspectFields({})
|
|
: () => new SignalRecordingService(provider).inspectDecoders({});
|
|
const first = await inspect();
|
|
if (!first.ok) throw first.error;
|
|
expect(first.value.normalized_result).toMatchObject({
|
|
tool: { configured_path: command, path: await realpath(commandSource) },
|
|
resource_limiter: {
|
|
configured_path: limiter,
|
|
path: await realpath(limiterSource),
|
|
arguments: expect.arrayContaining([command]),
|
|
},
|
|
});
|
|
// Identical bytes at another physical path must not pass the current
|
|
// invocation's identity verification, even though the producer succeeds.
|
|
await writeFile(`${limiter}.retarget`, `${replacement}\n`);
|
|
const changed = await inspect();
|
|
if (changed.ok) throw new Error("Retargeted limiter was accepted");
|
|
expect(changed.error).toMatchObject({
|
|
_tag: "AnalysisArtifactChangedError",
|
|
path: limiter,
|
|
capturedOutput: {
|
|
stdout:
|
|
kind === "tshark"
|
|
? "TShark (Wireshark) 4.6.9\n"
|
|
: "sigrok-cli 0.7.2\nlibsigrokdecode 0.5.3\n",
|
|
},
|
|
});
|
|
await unlink(`${limiter}.retarget`);
|
|
const fresh = await inspect();
|
|
if (!fresh.ok) throw fresh.error;
|
|
expect(fresh.value.normalized_result).toMatchObject({
|
|
resource_limiter: { path: await realpath(replacement) },
|
|
});
|
|
expect(first.value.normalized_result).toMatchObject({
|
|
resource_limiter: { path: await realpath(limiterSource) },
|
|
});
|
|
expect(
|
|
(await readdir(directory)).filter((name) =>
|
|
name.startsWith("workspace-"),
|
|
),
|
|
).toEqual([]);
|
|
},
|
|
);
|
|
|
|
const selectedEngineLauncher = (kind: "firmware" | "wakaru"): string => {
|
|
const producer = fileURLToPath(
|
|
new URL(
|
|
kind === "firmware"
|
|
? "../../fixtures/firmware/producer.mjs"
|
|
: "../../fixtures/javascript-recovery/producer.mjs",
|
|
import.meta.url,
|
|
),
|
|
);
|
|
const invocation = [
|
|
process.execPath,
|
|
producer,
|
|
...(kind === "firmware" ? ["binwalk"] : []),
|
|
]
|
|
.map((argument) => `'${argument.replaceAll("'", "'\\''")}'`)
|
|
.join(" ");
|
|
return `#!/bin/sh\nIFS= read -r role < "$0.role" || exit 19\nif [ -f "$0.retarget" ]; then\n IFS= read -r target < "$0.retarget"\n /bin/ln -sf "$target" "$0"\nfi\nif [ "$role" = limiter ]; then\n while [ "$1" != -- ]; do shift; done\n shift\n exec "$@"\nfi\nexec ${invocation} "$@"\n`;
|
|
};
|
|
|
|
// Own real wrapper processes and their workspaces. Linux/x64 admission and
|
|
// /proc limits are simulated; supervision always runs on the actual host.
|
|
const createSelectedEngineFixture = async (
|
|
kind: "firmware" | "wakaru",
|
|
afterLaunch?: () => void,
|
|
) => {
|
|
const directory = await createTestTempDirectory("rea-selected-command-");
|
|
const bin = join(directory, "bin"),
|
|
libexec = join(directory, "libexec");
|
|
await mkdir(bin);
|
|
await mkdir(libexec);
|
|
const command = join(bin, "engine"),
|
|
limiter = join(bin, "prlimit");
|
|
const commandSource = join(libexec, "engine"),
|
|
limiterSource = join(libexec, "limiter");
|
|
const replacement = join(libexec, "replacement");
|
|
const script = selectedEngineLauncher(kind);
|
|
for (const path of [commandSource, limiterSource, replacement])
|
|
await writeFile(path, script, { mode: 0o755 });
|
|
await symlink(commandSource, command);
|
|
await symlink(limiterSource, limiter);
|
|
await writeFile(`${command}.role`, `${kind}\n`);
|
|
await writeFile(`${limiter}.role`, "limiter\n");
|
|
const input = join(directory, kind === "firmware" ? "input.bin" : "input.js");
|
|
await writeFile(
|
|
input,
|
|
kind === "firmware" ? "fixture-input-data" : "module.exports = 42;",
|
|
);
|
|
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
|
const arch = Object.getOwnPropertyDescriptor(process, "arch");
|
|
if (platform === undefined || arch === undefined)
|
|
throw new Error("Missing host descriptors");
|
|
const restoreHost = () => {
|
|
Object.defineProperty(process, "platform", platform);
|
|
Object.defineProperty(process, "arch", arch);
|
|
};
|
|
const launches: {
|
|
cwd?: string;
|
|
pid?: number;
|
|
command: string;
|
|
environmentMarker: string | undefined;
|
|
}[] = [];
|
|
const environment = {
|
|
...process.env,
|
|
REA_BINWALK_COMMAND: command,
|
|
REA_FIRMWARE_PRLIMIT_COMMAND: limiter,
|
|
REA_WAKARU_COMMAND: command,
|
|
REA_JAVASCRIPT_PRLIMIT_COMMAND: limiter,
|
|
REA_SELECTED_ENVIRONMENT: "initial",
|
|
};
|
|
const launcher: typeof spawnOwnedProviderProcess = async (options) => {
|
|
restoreHost();
|
|
const child = await spawnOwnedProviderProcess(options);
|
|
launches.push({
|
|
command: options.command,
|
|
environmentMarker: options.hostEnvironment?.REA_SELECTED_ENVIRONMENT,
|
|
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
|
...(child.process.pid === undefined ? {} : { pid: child.process.pid }),
|
|
});
|
|
afterLaunch?.();
|
|
return child;
|
|
};
|
|
const fileSizeCeiling = vi
|
|
.spyOn(FirmwareFileAccess.prototype, "fileSizeCeiling")
|
|
.mockResolvedValue(Number.MAX_SAFE_INTEGER);
|
|
onTestFinished(() => fileSizeCeiling.mockRestore());
|
|
const service =
|
|
kind === "firmware"
|
|
? new FirmwareAnalysisService(new FirmwareProvider(environment, launcher))
|
|
: new JavaScriptRecoveryService(
|
|
new WakaruProvider(environment, launcher),
|
|
);
|
|
onTestFinished(async () => {
|
|
restoreHost();
|
|
await service.close();
|
|
for (const launch of launches) {
|
|
if (launch.pid !== undefined)
|
|
expect(await observeProcessStartIdentity(launch.pid)).toBeUndefined();
|
|
if (launch.cwd !== undefined)
|
|
await expect(readdir(launch.cwd)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
}
|
|
});
|
|
let sequence = 0;
|
|
const execute = async () => {
|
|
Object.defineProperty(process, "platform", {
|
|
...platform,
|
|
value: "linux",
|
|
});
|
|
Object.defineProperty(process, "arch", { ...arch, value: "x64" });
|
|
try {
|
|
return service instanceof FirmwareAnalysisService
|
|
? await service.execute("inspect_firmware_regions", { path: input })
|
|
: await service.recover({
|
|
path: input,
|
|
output_directory: join(directory, `output-${sequence++}`),
|
|
});
|
|
} finally {
|
|
restoreHost();
|
|
}
|
|
};
|
|
return {
|
|
bin,
|
|
command,
|
|
limiter,
|
|
commandSource,
|
|
limiterSource,
|
|
replacement,
|
|
environment,
|
|
launches,
|
|
execute,
|
|
};
|
|
};
|
|
|
|
it.skipIf(process.platform === "win32").each(["firmware", "wakaru"] as const)(
|
|
"executes selected %s wrappers and retains completed output when either alias changes",
|
|
async (kind) => {
|
|
const {
|
|
command,
|
|
limiter,
|
|
commandSource,
|
|
limiterSource,
|
|
replacement,
|
|
execute,
|
|
} = await createSelectedEngineFixture(kind);
|
|
const first = await execute();
|
|
if (!first.ok) throw first.error;
|
|
expect(first.value.normalized_result).toMatchObject({
|
|
engine:
|
|
kind === "firmware"
|
|
? { executable_path: await realpath(commandSource) }
|
|
: { executable: { path: await realpath(commandSource) } },
|
|
});
|
|
expect(first.value.raw_result).toMatchObject({
|
|
[kind === "firmware" ? "version_execution" : "version"]: {
|
|
command,
|
|
resource_limiter: limiter,
|
|
},
|
|
});
|
|
for (const [selectedPath, target] of [
|
|
[command, replacement],
|
|
[limiter, replacement],
|
|
[command, command],
|
|
[limiter, limiter],
|
|
] as const) {
|
|
await writeFile(`${selectedPath}.retarget`, `${target}\n`);
|
|
const changed = await execute();
|
|
if (changed.ok) throw new Error("Retargeted executable was accepted");
|
|
expect(changed.error).toMatchObject({
|
|
_tag: "AnalysisArtifactChangedError",
|
|
path: selectedPath,
|
|
capturedOutput: {
|
|
stdout: kind === "firmware" ? "binwalk 3.1.0\n" : "wakaru 1.14.0\n",
|
|
},
|
|
});
|
|
await unlink(`${selectedPath}.retarget`);
|
|
await unlink(selectedPath);
|
|
await symlink(
|
|
selectedPath === command ? commandSource : limiterSource,
|
|
selectedPath,
|
|
);
|
|
}
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"keeps firmware configuration consistent within an operation and accepts later updates",
|
|
async () => {
|
|
const {
|
|
bin,
|
|
command,
|
|
limiter,
|
|
commandSource,
|
|
limiterSource,
|
|
environment,
|
|
launches,
|
|
execute,
|
|
} = await createSelectedEngineFixture("firmware");
|
|
const nextCommand = join(bin, "next-engine");
|
|
const nextLimiter = join(bin, "next-prlimit");
|
|
await symlink(commandSource, nextCommand);
|
|
await symlink(limiterSource, nextLimiter);
|
|
await writeFile(`${nextCommand}.role`, "firmware\n");
|
|
await writeFile(`${nextLimiter}.role`, "limiter\n");
|
|
const originalHash = FirmwareFileAccess.prototype.hash;
|
|
const hash = vi.spyOn(FirmwareFileAccess.prototype, "hash");
|
|
onTestFinished(() => hash.mockRestore());
|
|
hash.mockImplementationOnce(async function (
|
|
this: FirmwareFileAccess,
|
|
path,
|
|
signal,
|
|
) {
|
|
const digest = await originalHash.call(this, path, signal);
|
|
environment.REA_BINWALK_COMMAND = nextCommand;
|
|
environment.REA_FIRMWARE_PRLIMIT_COMMAND = nextLimiter;
|
|
environment.REA_SELECTED_ENVIRONMENT = "updated";
|
|
return digest;
|
|
});
|
|
const first = await execute();
|
|
if (!first.ok) throw first.error;
|
|
expect(first.value.raw_result).toMatchObject({
|
|
version_execution: { command, resource_limiter: limiter },
|
|
});
|
|
expect(launches).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
command: limiter,
|
|
environmentMarker: "initial",
|
|
}),
|
|
]),
|
|
);
|
|
expect(
|
|
launches.every((launch) => launch.environmentMarker === "initial"),
|
|
).toBe(true);
|
|
const next = await execute();
|
|
if (!next.ok) throw next.error;
|
|
expect(next.value.raw_result).toMatchObject({
|
|
version_execution: {
|
|
command: nextCommand,
|
|
resource_limiter: nextLimiter,
|
|
},
|
|
});
|
|
expect(launches.at(-1)).toMatchObject({
|
|
command: nextLimiter,
|
|
environmentMarker: "updated",
|
|
});
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"keeps Wakaru configuration consistent across version and recovery launches",
|
|
async () => {
|
|
let mutateOnce = true;
|
|
const fixture = await createSelectedEngineFixture("wakaru", () => {
|
|
if (!mutateOnce) return;
|
|
mutateOnce = false;
|
|
fixture.environment.REA_WAKARU_COMMAND = nextCommand;
|
|
fixture.environment.REA_JAVASCRIPT_PRLIMIT_COMMAND = nextLimiter;
|
|
fixture.environment.REA_SELECTED_ENVIRONMENT = "updated";
|
|
});
|
|
const {
|
|
bin,
|
|
command,
|
|
limiter,
|
|
commandSource,
|
|
limiterSource,
|
|
launches,
|
|
execute,
|
|
} = fixture;
|
|
const nextCommand = join(bin, "next-engine");
|
|
const nextLimiter = join(bin, "next-prlimit");
|
|
await symlink(commandSource, nextCommand);
|
|
await symlink(limiterSource, nextLimiter);
|
|
await writeFile(`${nextCommand}.role`, "wakaru\n");
|
|
await writeFile(`${nextLimiter}.role`, "limiter\n");
|
|
const first = await execute();
|
|
if (!first.ok) throw first.error;
|
|
expect(first.value.raw_result).toMatchObject({
|
|
version: { command, resource_limiter: limiter },
|
|
});
|
|
expect(
|
|
launches.map(({ command, environmentMarker }) => ({
|
|
command,
|
|
environmentMarker,
|
|
})),
|
|
).toEqual([
|
|
{ command: limiter, environmentMarker: "initial" },
|
|
{ command: limiter, environmentMarker: "initial" },
|
|
]);
|
|
const next = await execute();
|
|
if (!next.ok) throw next.error;
|
|
expect(next.value.raw_result).toMatchObject({
|
|
version: { command: nextCommand, resource_limiter: nextLimiter },
|
|
});
|
|
expect(
|
|
launches.slice(2).map(({ command, environmentMarker }) => ({
|
|
command,
|
|
environmentMarker,
|
|
})),
|
|
).toEqual([
|
|
{ command: nextLimiter, environmentMarker: "updated" },
|
|
{ command: nextLimiter, environmentMarker: "updated" },
|
|
]);
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === "win32")(
|
|
"executes the selected PCAP limiter and retains completed output when its alias changes",
|
|
async () => {
|
|
const directory = await createTestTempDirectory(
|
|
"rea-selected-pcap-limiter-",
|
|
);
|
|
const selected = join(directory, "prlimit"),
|
|
physical = join(directory, "driver"),
|
|
replacement = join(directory, "replacement");
|
|
const script =
|
|
'#!/bin/sh\n[ -f "$0.role" ] || exit 19\nif [ -f "$0.retarget" ]; then\n IFS= read -r target < "$0.retarget"\n /bin/ln -sf "$target" "$0"\nfi\nwhile [ "$1" != -- ]; do shift; done\nshift\nexec "$@"\n';
|
|
await writeFile(physical, script, { mode: 0o755 });
|
|
await writeFile(replacement, script, { mode: 0o755 });
|
|
await symlink(physical, selected);
|
|
await writeFile(`${selected}.role`, "limiter");
|
|
const resources = createArtifactAnalysisResources(
|
|
"pcap",
|
|
"inspect_pcap_capture",
|
|
readStableArtifact,
|
|
async (configured) => configured,
|
|
{ message: "busy", details: {} },
|
|
);
|
|
onTestFinished(() => resources.close());
|
|
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
|
if (platform === undefined) throw new Error("Missing host descriptor");
|
|
let prepared: Awaited<ReturnType<typeof preparePcapNativeBound>>;
|
|
try {
|
|
Object.defineProperty(process, "platform", {
|
|
...platform,
|
|
value: "linux",
|
|
});
|
|
prepared = await preparePcapNativeBound(
|
|
{ REA_TSHARK_PRLIMIT_COMMAND: selected },
|
|
resources,
|
|
async (_selected, args) => {
|
|
const stdout =
|
|
args[0] === "--help"
|
|
? " --as[=limit] --fsize[=limit] --cpu[=limit] --core[=limit]"
|
|
: "prlimit from util-linux 2.38.1";
|
|
return {
|
|
stdout,
|
|
capturedOutput: { stdout, stderr: "", truncated: false },
|
|
};
|
|
},
|
|
);
|
|
} finally {
|
|
Object.defineProperty(process, "platform", platform);
|
|
}
|
|
let refuseCleanup = false;
|
|
let retained: ProviderProcessSupervisor | undefined;
|
|
onTestFinished(async () => {
|
|
refuseCleanup = false;
|
|
await retained?.stop();
|
|
});
|
|
const execute = () =>
|
|
runPcapCommand({
|
|
operation: "inspect_pcap_capture",
|
|
command: "/bin/echo",
|
|
arguments: ["selected limiter"],
|
|
limits: { timeoutMs: 10_000, maxOutputBytes: 1024 },
|
|
environment: process.env,
|
|
signal: undefined,
|
|
nativeBound: prepared.nativeBound,
|
|
launcher: async (options) => {
|
|
const child = await spawnOwnedProviderProcess(options);
|
|
return {
|
|
...child,
|
|
cleanup: () =>
|
|
refuseCleanup
|
|
? Promise.resolve({
|
|
cleaned: false,
|
|
reason: "controlled pending command cleanup",
|
|
})
|
|
: cleanupOwnedProcessGroup(child.ownership),
|
|
};
|
|
},
|
|
retain: (owner) => {
|
|
retained = owner;
|
|
},
|
|
});
|
|
await expect(execute()).resolves.toMatchObject({
|
|
stdout: "selected limiter\n",
|
|
});
|
|
await writeFile(`${selected}.retarget`, `${replacement}\n`);
|
|
await expect(execute()).rejects.toMatchObject({
|
|
_tag: "AnalysisArtifactChangedError",
|
|
path: selected,
|
|
capturedOutput: { stdout: "selected limiter\n" },
|
|
});
|
|
await unlink(selected);
|
|
await symlink(physical, selected);
|
|
await writeFile(`${selected}.retarget`, `${selected}\n`);
|
|
refuseCleanup = true;
|
|
const failed: unknown = await execute().catch((cause: unknown) => cause);
|
|
expect(failed).toBeInstanceOf(AnalysisError);
|
|
if (!(failed instanceof AnalysisError))
|
|
throw new Error("Expected typed cleanup failure");
|
|
expect(failed).toMatchObject({
|
|
cleanupIncomplete: true,
|
|
cleanup: { reason: "controlled pending command cleanup" },
|
|
capturedOutput: { stdout: "selected limiter\n" },
|
|
});
|
|
expect(failed.cleanupPrimary).toMatchObject({
|
|
_tag: "AnalysisArtifactChangedError",
|
|
path: selected,
|
|
});
|
|
refuseCleanup = false;
|
|
await expect(retained?.stop()).resolves.toMatchObject({
|
|
status: "verified-cleanup",
|
|
});
|
|
expect(releaseOwnedCleanup(failed).cleanupIncomplete).toBe(false);
|
|
},
|
|
);
|