Files
reverse-engineering-anything/tests/boundary/pcap/pcapCommand.test.ts
T
morluto cb49383269 refactor(browser): take the host in Chromium, Electron and capture adapters (#11130)
* refactor(browser): take the host in Chromium, Electron and capture adapters

chromiumSandboxEnabled and safeElectronEnvironment take a required platform. The scenario browser, native module resolver, Electron provider and capture cleanup, mitmproxy adapter and web script artifacts take an optional platform seam (default HOST_PLATFORM); Electron fuses read the host architecture from HOST_PLATFORM. Their tests inject the platform instead of redefining process.platform. src/browser no longer reads process.platform or process.arch.

* refactor(pcap): take the host platform in the packet tools, native bound and batch launch (#11141)

* refactor(pcap): take the host platform in the packet tools, native bound and batch launch

* test(pcap): cover the selected host in batch launch and capture-host support

* refactor(apktool): take the host platform in launcher selection, version probe and decode (#11164)

* refactor(apktool): take the host platform in launcher selection, version probe and decode

* test(apktool): cover the provider's selected host in launcher selection

* refactor(hopper): give the launcher the provider's host platform

* refactor(native): inject the host into the pwntools decoders and native capability defaults (#11173)

* refactor(native): inject the host into the pwntools decoders and native capability defaults

* fix(native): give composed pwntools services the capability host and drop empty test hooks

* refactor(adb): take the host platform in binary selection and pulled file names (#11176)

* refactor(adb): take the host platform in binary selection and pulled file names

* refactor(cli): pass the resolved host platform through rea mcp add (#11179)

* refactor(cli): pass the resolved host platform through rea mcp add

* refactor(composition): default composition entry points to HOST_PLATFORM and pass it to Hopper and IDA (#11183)

* refactor(kuna): require the host platform in admission and installation, and give it to the session client (#11186)

* refactor(kuna): require the host platform in admission and installation, and give it to the session client

* fix(kuna): pass the host platform from the JavaScript installation callers

verify-real-kuna, both native oracle helpers and the command-lifetime child script call inspectKunaInstallation from dist, where TypeScript cannot see the now-required platform. They passed undefined and got unsupported_host on supported hosts.

* refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM (#11203)

* refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM

createServer read process.platform and process.arch live for its capability services, and registerSessionTools read process.platform for process capture. A host option (default HOST_PLATFORM) now selects both, and composition passes the capability host to the sigrok provider and the EVM provider (execution gate, limiter probe and environment rules), as it does for pwntools.

hostRestrictedAvailabilityMcp selects its host through the option instead of redefining process.platform and process.arch, and moves to the MCP boundary lane since it no longer touches process-global state. evmCleanupRetry passes SIMULATED_LINUX_X64 to the provider instead of 52 property redefinitions; the fixture moves to tests/fixtures/simulatedHost.ts.

* refactor(desktop): require the host platform in build computer and secret folder paths (#11210)

* refactor(desktop): require the host platform in build computer and secret folder paths

buildComputerArchiveDirectory, defaultBuildComputerArchive, resolveBuildComputerEnvironment and buildSecretsDirectory defaulted to process.platform. Every caller but DesktopBuildComputers' secret folder already passed the platform; it now passes HOST_PLATFORM.platform, which it reads for the build environment.

* refactor(filesystem): default caller paths and ChangeTime settling to HOST_PLATFORM (#11212)

appendCallerPath, absoluteCallerPath and the ChangeTime settle seams defaulted to a live process.platform read. Their defaults now come from HOST_PLATFORM: the 59 callers that omit the platform join or settle paths they open on this host, and callers describing another host's layout already pass it.

The webScriptExport case that redefined process.platform to reach the Windows settle budget moves to its own file, which selects Windows by mocking HostPlatform.

* fix(server): report process capture availability for the server's host

sessionAvailabilityPolicy imported platform from node:process, so with a selected host binary_session reported capture_process_scenario from the running host while planning and capture used the selected one. It takes the platform from createServer and registerSessionTools. hostRestrictedAvailabilityMcp checks discovery against a dry-run plan on win32 and linux hosts.

* build(guards): count platform and arch imports from node:process and node:os as ambient host reads

sessionAvailabilityPolicy's named import of platform from node:process escaped the ambient-host-platform guard. The guards now also match named platform/arch imports from node:process or node:os and os.platform()/os.arch(). The one other site, DesktopApplicationCapture's os.arch(), records the capturing host and now reads HOST_PLATFORM.architecture.

* refactor(config): take the host platform in parseConfig and give debugger managers the capability host (#11237)

* refactor(config): take the host platform in parseConfig and give debugger managers the capability host

parseConfig read process.platform for the default Hopper launcher; it takes the platform (default HOST_PLATFORM). GdbSessionManager and RizinDebugSessionManager default their platform to HOST_PLATFORM, and composition passes the capability host that already decides their availability. GDB's /proc descriptor check reads HOST_PLATFORM explicitly: it inspects this host's /proc whatever host the manager models.

* refactor(firmware): give the firmware and Wakaru providers the capability host (#11239)

* refactor(firmware): give the firmware and Wakaru providers the capability host

resolveFirmwareCommand and resolveWakaruCommand read process.platform (and process.arch) for their host gate. They take the platform or host as a parameter; FirmwareProvider and WakaruProvider take a host (default HOST_PLATFORM) for the gate and their environment snapshots, and composition passes the capability host that already decides their availability. The JavaScript analysis source transfer defaults to HOST_PLATFORM.

artifactSelectedCommand passes SIMULATED_LINUX_X64 to both providers instead of redefining process.platform and process.arch, and the Wakaru limiter configuration cases now run on any POSIX host.

* refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM (#11240)

* refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM

TsharkCaptureProvider and CutterBridgeClient defaulted their platform to process.platform. Both default to HOST_PLATFORM now, and composition passes the capability host to the packet capture service, which already decides its availability.

* refactor(platform): read HOST_PLATFORM explicitly in host-only path checks (#11241)

* refactor(platform): read HOST_PLATFORM explicitly in host-only path checks

Electron's readlink target split, IDA's host path comparison, the inspector's reported runtime path, the server identity check and WABT's executable names all describe paths on the running host. They read HOST_PLATFORM instead of process.platform.

* test(native): select the native UI verifier's host through HostPlatform (#11242)

verify-native-ui.mjs reads its macOS requirement from HOST_PLATFORM, and its action test resolves the script's HostPlatform import to a simulated darwin host instead of redefining process.platform in the child preload. Simulating linux there fails the macOS requirement, so the redirect is effective.

* test(mcp): check that composition forwards the selected host to execution

hostRestrictedAvailabilityMcp ran execution only on darwin, where the runner's own host also refuses. The new case calls the firmware, Wakaru, tshark, sigrok and EVM tools under a darwin and a linux x64 host and requires different outcomes, so dropping a provider's host forwarding fails on any runner (checked by removing the firmware forwarding).

* fix(composition): give the pcap, Apktool and ADB providers the capability host

createServer's selected host decided pcap capture discovery, but the default pcap, Apktool and ADB factories built their providers with HOST_PLATFORM. The factories take the platform (default HOST_PLATFORM) and capabilityServices passes its context platform, so availability and execution follow one host.

* test: import moved resources owners in host-platform fixtures

* refactor(config): drop the unused host parameter from parseConfig
2026-11-16 04:27:07 +08:00

551 lines
19 KiB
TypeScript

import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js";
import { join } from "node:path";
import { writeFile } from "node:fs/promises";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import type { AnalysisError } from "../../../src/domain/analysisErrorBase.js";
import { expect, it, onTestFinished, test, vi } from "vitest";
import { runPcapCommand } from "../../../src/pcap/PcapCommand.js";
import { Deadline } from "../../../src/domain/deadline.js";
import * as ownership from "../../../src/process/ProcessOwnershipObservation.js";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import type { ProviderProcessSupervisor } from "../../../src/process/ProviderProcess.js";
import {
AnalysisCancelledError,
AnalysisProtocolError,
AnalysisUnsupportedTargetError,
} from "../../../src/domain/analysisErrorCore.js";
const posixIt = test.skipIf(process.platform === "win32");
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
import { OwnedCommandFailure } from "../../../src/process/OwnedCommand.js";
import { selectArtifactCommandPath } from "../../../src/process/ArtifactCommandPath.js";
it.skipIf(process.platform !== "darwin")(
"preserves opaque cancellation during native ownership preparation without acquiring caller resources",
async () => {
const controller = new AbortController();
const reason = new ProviderCleanupError("caller", ["foreign-resource"], {});
const prepare = vi
.spyOn(ownership.systemProcessOwnershipHost, "prepare")
.mockImplementationOnce(async () => {
controller.abort(reason);
});
onTestFinished(() => prepare.mockRestore());
const launcher = vi.fn(async () => {
throw new Error("Cancelled preparation must not launch the tool");
});
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_client",
command: process.execPath,
arguments: ["--version"],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: controller.signal,
launcher,
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError)) throw failure;
expect(failure.cause).toBe(reason);
expect(failure.cleanupIncomplete).toBe(false);
expect(failure.cleanupResources).toEqual([]);
expect(reason.cleanupIncomplete).toBe(true);
expect(launcher).not.toHaveBeenCalled();
},
);
it("preserves a failed producer when cancellation arrives during its final cleanup", async () => {
const controller = new AbortController();
const reason = { request: "cancel during cleanup" };
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command: process.execPath,
arguments: [
"-e",
'process.stderr.write("authored producer failure"); process.exitCode = 7',
],
inputPath: "/authored-capture.pcap",
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: controller.signal,
launcher: async (spawn) => {
const launched = await spawnOwnedProviderProcess(spawn);
const cleanup =
launched.cleanup ??
(() => cleanupOwnedProcessGroup(launched.ownership));
return {
...launched,
cleanup: async () => {
const result = await cleanup();
controller.abort(reason);
return result;
},
};
},
retain: (owner) =>
onTestFinished(async () => {
expect((await owner.stop()).status).not.toBe("incomplete");
}),
}).catch((cause: unknown) => cause);
expect(controller.signal.aborted).toBe(true);
expect(failure).toBeInstanceOf(AnalysisProtocolError);
if (!(failure instanceof AnalysisProtocolError)) throw failure;
expect(failure.cause).toBeInstanceOf(OwnedCommandFailure);
expect((failure.cause as OwnedCommandFailure).reason).toBe("process");
expect(failure.capturedOutput).toMatchObject({
stderr: "authored producer failure",
exit_code: 7,
});
});
it.each([
null,
"opaque caller cancellation",
new ProviderCleanupError("caller", ["caller-owned-resource"], {
reason: "unrelated cleanup",
}),
])(
"preserves the exact active command cancellation reason %s",
async (reason) => {
const controller = new AbortController();
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_client",
command: process.execPath,
arguments: [
"-e",
'process.stdout.write("ready"); setInterval(() => {}, 1000)',
],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: controller.signal,
launcher: async (spawn) => {
const launched = await spawnOwnedProviderProcess(spawn);
launched.process.stdout?.once("data", () => controller.abort(reason));
return launched;
},
retain: (owner) =>
onTestFinished(async () => {
expect((await owner.stop()).status).not.toBe("incomplete");
}),
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(AnalysisCancelledError);
if (!(failure instanceof AnalysisCancelledError)) throw failure;
expect(failure.cause).toBe(reason);
expect(failure.cleanupIncomplete).toBe(false);
expect(failure.cleanupResources).toEqual([]);
if (reason instanceof ProviderCleanupError)
expect(reason.cleanupIncomplete).toBe(true);
},
);
it.skipIf(process.platform !== "darwin")(
"does not spend the tool execution deadline preparing native ownership",
async () => {
const original = ownership.prepareProcessOwnershipInspection;
let entered!: () => void;
let release!: () => void;
const preparing = new Promise<void>((resolve) => {
entered = resolve;
});
const gate = new Promise<void>((resolve) => {
release = resolve;
});
let first = true;
const prepare = vi
.spyOn(ownership, "prepareProcessOwnershipInspection")
.mockImplementation(async (signal) => {
await original(signal);
if (first) {
first = false;
entered();
await gate;
}
});
const timeoutMs = 4321;
const deadlines = vi.spyOn(Deadline, "after");
const commandDeadlines = () =>
deadlines.mock.calls.filter(
([milliseconds]) => milliseconds === timeoutMs,
);
onTestFinished(() => {
deadlines.mockRestore();
prepare.mockRestore();
release();
});
const pending = runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_client",
command: process.execPath,
arguments: ["--version"],
limits: { timeoutMs, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
retain: (owner) => {
onTestFinished(async () => {
expect((await owner.stop()).status).not.toBe("incomplete");
});
},
}).then(
(value) => ({ ok: true as const, value }),
(error: unknown) => ({ ok: false as const, error }),
);
await preparing;
// Observe before release; assert after the command is joined so a failed
// check never leaves it running past the test.
const armedWhilePreparing = commandDeadlines();
release();
const result = await pending;
// The command deadline is armed only once preparation has finished.
expect(armedWhilePreparing).toEqual([]);
if (!result.ok) throw result.error;
expect(result.value.stdout.trim()).toBe(process.version);
expect(commandDeadlines()).toHaveLength(1);
},
);
it("returns complete stdout while retaining unresolved process cleanup", async () => {
let retained:
| {
readonly resources: readonly string[];
readonly reason: string;
readonly owner: ProviderProcessSupervisor;
}
| undefined;
let mayClean = false;
const output = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command: process.execPath,
arguments: ["-e", 'process.stdout.write("complete producer output")'],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
launcher: async (spawn) => {
const launched = await spawnOwnedProviderProcess(spawn);
const cleanup =
launched.cleanup ??
(() => cleanupOwnedProcessGroup(launched.ownership));
return {
...launched,
cleanup: async () => {
const stopped = await cleanup();
if (!mayClean) throw new Error("injected cleanup uncertainty");
return stopped;
},
};
},
retain: (owner, resources, reason) => {
retained = { owner, resources, reason };
},
});
expect(output.stdout).toBe("complete producer output");
expect(output.cleanup).toMatchObject({
reason: "injected cleanup uncertainty",
capturedOutput: {
stdout: "complete producer output",
stderr: "",
truncated: false,
},
});
expect(retained?.resources).toContain(
`process-group:${retained?.owner.launch.ownership?.processGroupId}`,
);
expect(retained?.reason).toBe("injected cleanup uncertainty");
if (retained === undefined) throw new Error("Cleanup owner was not retained");
mayClean = true;
expect((await retained.owner.stop()).status).not.toBe("incomplete");
});
it.each([
["EPERM", "exists but could not be executed"],
["EACCES", "exists but could not be executed"],
["ENOENT", "was not found"],
])(
"reports a %s launch refusal while reading a capture as an unavailable tool",
async (code, wording) => {
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command: "/selected/tshark",
arguments: ["-r", "/authored-capture.pcap"],
inputPath: "/authored-capture.pcap",
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
launcher: async () => {
throw Object.assign(new Error(`spawn /selected/tshark ${code}`), {
code,
syscall: "spawn /selected/tshark",
path: "/selected/tshark",
});
},
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining(`${wording} (${code})`),
});
},
);
posixIt(
"names the selected tool on a launch refusal Node throws synchronously",
async () => {
// Node throws ENOTDIR synchronously with a bare `spawn` syscall rather
// than emitting `spawn <path>`. A path through a regular file refuses
// the same way on every POSIX host; ENOEXEC does not, because Linux
// libc may retry a headerless file through /bin/sh.
const directory = await createTestTempDirectory("rea-pcap-enotdir-");
const file = join(directory, "not-a-directory");
await writeFile(file, "");
const command = join(file, "tshark");
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_client",
command,
arguments: ["--version"],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
launcher: spawnOwnedProviderProcess,
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining("was not found (ENOTDIR)"),
});
},
);
it("reports the Windows native launcher's refusal of the selected tool as an unavailable tool", async () => {
const command = "C:\\Wireshark\\tshark.exe";
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command,
arguments: ["-r", "/authored-capture.pcap"],
inputPath: "/authored-capture.pcap",
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
launcher: async () => {
// The native addon names the refused executable without Node's
// `syscall` and `path` fields.
throw Object.assign(new Error("refused"), {
code: "ENOENT",
constraint: "Create process atomically inside owned Job Object failed",
requestedPath: command,
win32Code: 2,
});
},
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining("was not found (ENOENT)"),
});
});
it("attributes a refused limiter spawn to the limiter, not Wireshark", async () => {
const limiter = await selectArtifactCommandPath(process.execPath);
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command: "/selected/tshark",
arguments: [],
inputPath: "/authored-capture.pcap",
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
nativeBound: { limiter: { command: limiter, arguments: [] } },
launcher: async () => {
throw Object.assign(new Error("refused"), {
code: "EPERM",
syscall: `spawn ${limiter.invocationPath}`,
path: limiter.invocationPath,
});
},
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining(
`capture limiter ${limiter.invocationPath}`,
),
remediationAction: expect.stringContaining("REA_TSHARK_PRLIMIT_COMMAND"),
});
});
/**
* A stand-in for util-linux prlimit: it either refuses with prlimit's own
* err(3) diagnostics or replaces itself with the selected tool.
*/
const prlimitStandIn = async () => {
const root = await createTestTempDirectory("rea-pcap-prlimit-");
const prlimit = join(root, "prlimit");
await writeFile(
prlimit,
`#!/bin/sh
while [ "\${1#--}" != "$1" ]; do
if [ "$1" = "--refuse" ]; then
printf 'prlimit: failed to set the AS resource limit: Operation not permitted\\n' >&2; exit 1
fi
shift
done
if [ ! -e "$1" ]; then printf 'prlimit: failed to execute %s: No such file or directory\\n' "$1" >&2; exit 127; fi
if [ ! -x "$1" ]; then printf 'prlimit: failed to execute %s: Permission denied\\n' "$1" >&2; exit 126; fi
exec "$@"
`,
{ mode: 0o755 },
);
const capinfos = join(root, "capinfos");
await writeFile(
capinfos,
"#!/bin/sh\nprintf 'capinfos: The file is not a capture file\\n' >&2; exit 1\n",
{ mode: 0o755 },
);
const notExecutable = join(root, "tshark-not-executable");
await writeFile(notExecutable, "#!/bin/sh\nexit 0\n", { mode: 0o644 });
return {
limiter: await selectArtifactCommandPath(prlimit),
capinfos,
notExecutable,
missing: join(root, "missing-tshark"),
};
};
const runLimited = async (
limiter: Awaited<ReturnType<typeof prlimitStandIn>>["limiter"],
command: string,
limiterArguments: string[] = ["--as=1073741824"],
) =>
runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_capture",
command,
arguments: [],
inputPath: "/authored-capture.pcap",
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
nativeBound: { limiter: { command: limiter, arguments: limiterArguments } },
retain: (owner) =>
onTestFinished(async () => {
await owner.stop();
}),
}).catch((cause: unknown) => cause);
posixIt(
"attributes a limited tool's own exit to the tool through prlimit",
async () => {
const { limiter, capinfos } = await prlimitStandIn();
const failure = await runLimited(limiter, capinfos);
expect(failure).toBeInstanceOf(AnalysisUnsupportedTargetError);
expect(projectAnalysisError(failure as AnalysisError)).toMatchObject({
code: "unsupported_target",
});
},
);
posixIt("attributes prlimit's failed exec to the selected tool", async () => {
const { limiter, missing, notExecutable } = await prlimitStandIn();
for (const [command, wording] of [
[missing, "was not found"],
[notExecutable, "exists but could not be executed"],
] as const) {
const failure = await runLimited(limiter, command);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining(`Selected tool ${command} ${wording}`),
});
expect(failure).not.toMatchObject({
remediationAction: expect.stringContaining("REA_TSHARK_PRLIMIT_COMMAND"),
});
}
});
posixIt("attributes prlimit's own refusal to the limiter", async () => {
const { limiter, capinfos } = await prlimitStandIn();
const failure = await runLimited(limiter, capinfos, ["--refuse"]);
expect(failure).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
message: expect.stringContaining(
`capture limiter ${limiter.invocationPath} failed before starting`,
),
remediationAction: expect.stringContaining("REA_TSHARK_PRLIMIT_COMMAND"),
});
});
it("does not attribute an errno without spawn identity to the selected tool", async () => {
const failure = await runPcapCommand({
platform: HOST_PLATFORM.platform,
operation: "inspect_pcap_client",
command: "/selected/tshark",
arguments: ["--version"],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: {},
signal: undefined,
launcher: async () => {
throw Object.assign(new Error("ownership setup denied"), {
code: "EPERM",
});
},
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(AnalysisProtocolError);
if (!(failure instanceof AnalysisProtocolError)) throw failure;
expect(failure.message).toContain("failing stage is unknown");
});
it.each([
["win32", "C:\\Windows\\System32\\cmd.exe", true],
["linux", "C:\\Tools\\tshark.cmd", false],
] as const)(
"launches a batch tool through cmd.exe only for a Windows host (%s)",
async (platform, expectedCommand, verbatim) => {
const launches: {
readonly command: string;
readonly windowsVerbatimArguments: boolean | undefined;
}[] = [];
await runPcapCommand({
platform,
operation: "inspect_pcap_client",
command: "C:\\Tools\\tshark.cmd",
arguments: ["--version"],
limits: { timeoutMs: 5000, maxOutputBytes: 1024 },
environment: { SYSTEMROOT: "C:\\Windows" },
signal: undefined,
launcher: async (spawn) => {
launches.push({
command: spawn.command,
windowsVerbatimArguments: spawn.windowsVerbatimArguments,
});
throw new Error("recorded launch");
},
retain: () => {
throw new Error("No provider resources were acquired");
},
}).catch(() => undefined);
expect(launches).toEqual([
{ command: expectedCommand, windowsVerbatimArguments: verbatim },
]);
},
);