Files
rea/src/browser/modules/NativeModuleResolver.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

449 lines
16 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from "vitest";
import {
NativeModuleResolver,
type ModuleResolverLauncher,
} from "./NativeModuleResolver.js";
import { webModuleResolutionObservationSchema } from "../../domain/webModuleTrace.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { completedModuleResolverLauncher } from "../../../tests/fixtures/webModuleTrace.js";
const input = {
importerUrl: "https://app.test/main.js",
importMap: null,
specifiers: ["./dep.js"],
};
describe("native module resolver cleanup ownership", () => {
it.each([false, true])(
"awaits owned cleanup when acquisition is cancelled (cleanup fails: %s)",
async (cleanupFails) => {
const controller = new AbortController();
let closed = false;
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
() => {
controller.abort();
return Promise.resolve({
version: () => "fixture",
newContext: () => {
throw new Error("must not acquire context");
},
close: () => {
closed = true;
if (cleanupFails)
return Promise.reject(new Error("fixture cleanup refusal"));
return Promise.resolve();
},
});
},
);
const result = await provider.resolve(input, {
signal: controller.signal,
});
expect(closed).toBe(true);
if (result.ok) throw new Error("expected cancelled result");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe(
cleanupFails ? "cleanup_incomplete" : "cancelled",
);
if (cleanupFails) {
expect(projected.details).toMatchObject({
diagnostics: { primary_error: { code: "cancelled" } },
});
}
},
);
it("returns cleanup_incomplete when owned cleanup fails after an engine error", async () => {
let launches = 0;
let closes = 0;
let cleanupAllowed = false;
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
() => {
launches += 1;
return Promise.resolve({
version: () => "fixture",
newContext: () =>
Promise.reject(new Error("fixture context failure")),
close: async () => {
closes += 1;
if (!cleanupAllowed)
throw new Error("fixture owned cleanup refusal");
},
});
},
);
const result = await provider.resolve(input);
if (result.ok) throw new Error("expected cleanup failure");
expect(projectAnalysisError(result.error).code).toBe("cleanup_incomplete");
expect(result.error.cleanupIncomplete).toBe(true);
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: {
primary_error: {
details: {
diagnostics: { error_message: "fixture context failure" },
},
},
cleanup_error: {
details: { diagnostics: { reason: "fixture owned cleanup refusal" } },
},
},
});
const blocked = await provider.resolve(input);
expect(blocked.ok).toBe(false);
if (!blocked.ok) expect(blocked.error.cleanupIncomplete).toBe(true);
expect(launches).toBe(1);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
cleanupAllowed = true;
await provider.close();
await provider.close();
expect(closes).toBe(4);
expect(launches).toBe(1);
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
if (!blocked.ok) expect(blocked.error.cleanupIncomplete).toBe(false);
});
});
describe("native module resolver shutdown admission", () => {
it("awaits acquisition and cleanup while refusing queued work during shutdown", async () => {
let acquired: () => void = () => {
throw new Error("acquisition gate missing");
};
const acquiring = new Promise<void>((resolve) => {
acquired = resolve;
});
let release: () => void = () => {
throw new Error("release gate missing");
};
const released = new Promise<void>((resolve) => {
release = resolve;
});
let launches = 0;
let closes = 0;
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
async () => {
launches += 1;
acquired();
await released;
return {
version: () => "fixture",
newContext: () =>
Promise.reject(new Error("fixture context failure")),
close: async () => {
closes += 1;
},
};
},
);
const first = provider.resolve(input);
await acquiring;
const queued = provider.resolve(input);
const closing = provider.close();
let closed = false;
void closing.then(() => {
closed = true;
});
await Promise.resolve();
expect(closed).toBe(false);
release();
await first;
const blocked = await queued;
expect(blocked.ok).toBe(false);
if (!blocked.ok) {
expect(blocked.error.cleanupIncomplete).toBe(false);
expect(blocked.error.cleanupResources).toEqual([]);
expect(projectAnalysisError(blocked.error).code).toBe(
"capability_unavailable",
);
}
await closing;
expect(closed).toBe(true);
expect([launches, closes]).toEqual([1, 1]);
const afterClose = await provider.resolve(input);
expect(afterClose.ok).toBe(false);
if (!afterClose.ok) {
expect(afterClose.error.cleanupIncomplete).toBe(false);
expect(afterClose.error.cleanupResources).toEqual([]);
expect(projectAnalysisError(afterClose.error).code).toBe(
"capability_unavailable",
);
}
});
});
describe("optional native resolution acquisition", () => {
it("does not load the browser engine when the selected operation lacks its configuration", async () => {
const provider = new NativeModuleResolver({}, () => {
throw new Error("must not launch");
});
const result = await provider.resolve(input);
expect(result.ok).toBe(false);
if (!result.ok)
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
message: expect.stringContaining("REA_BROWSER_EXECUTABLE"),
});
});
it.each(["relative/chromium", ""])(
"retains an invalid selected browser path %j without launching",
async (executable) => {
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: executable },
() => {
throw new Error("must not launch");
},
);
const result = await provider.resolve(input);
if (result.ok) throw new Error("expected configuration refusal");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "capability_unavailable",
details: {
reason: "invalid_browser_executable",
diagnostics: { executable },
},
});
},
);
it("does not acquire a browser after caller cancellation", async () => {
const controller = new AbortController();
const reason = { request: "opaque admission cancellation" };
controller.abort(reason);
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
() => {
throw new Error("must not launch");
},
);
const result = await provider.resolve(input, { signal: controller.signal });
if (result.ok) throw new Error("expected cancellation");
expect(result.error._tag).toBe("AnalysisCancelledError");
expect(result.error.cause).toBe(reason);
});
it("retains the selected executable and actual startup diagnostic", async () => {
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/missing/browser" },
() => Promise.reject(new Error("spawn EACCES fixture")),
);
const result = await provider.resolve(input);
if (result.ok) throw new Error("expected startup failure");
expect(projectAnalysisError(result.error).details).toMatchObject({
diagnostics: {
executable: "/missing/browser",
error_message: "spawn EACCES fixture",
},
});
});
});
describe("native resolution Chromium sandbox", () => {
it.each([
{ environment: {}, sandbox: true },
{ environment: { REA_BROWSER_NO_SANDBOX: "false" }, sandbox: true },
{ environment: { REA_BROWSER_NO_SANDBOX: "true" }, sandbox: false },
])(
"launches Chromium with sandbox $sandbox for $environment",
async ({ environment, sandbox }) => {
let launchOptions: Parameters<ModuleResolverLauncher>[0] | undefined;
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser", ...environment },
(options) => {
launchOptions = options;
return Promise.reject(new Error("launch boundary reached"));
},
"linux",
);
const result = await provider.resolve(input);
if (result.ok) throw new Error("expected startup failure");
expect(launchOptions?.chromiumSandbox).toBe(sandbox);
expect(launchOptions?.args).not.toContain("--no-sandbox");
expect(result.error).toMatchObject({
remediationAction: sandbox
? expect.stringContaining("REA_BROWSER_NO_SANDBOX=true")
: undefined,
});
},
);
it("keeps the default recovery for engine failures after a sandboxed launch", async () => {
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
() =>
Promise.resolve({
version: () => "fixture",
newContext: () =>
Promise.reject(new Error("fixture context failure")),
close: () => Promise.resolve(),
}),
"linux",
);
const result = await provider.resolve(input);
if (result.ok) throw new Error("expected engine failure");
expect(result.error).toMatchObject({
remediationAction: undefined,
diagnostics: { error_message: "fixture context failure" },
});
});
});
describe("completed native resolution finalization", () => {
it.each([false, true])(
"retains the completed batch when final close is cancelled (close fails: %s)",
async (cleanupFails) => {
const controller = new AbortController();
const reason = { request: "cancelled during final browser close" };
let allowClose = !cleanupFails;
let closes = 0;
const report = {
importer_url: input.importerUrl,
entries: [
{
specifier: "./dep.js",
resolution: { state: "resolved", url: "https://app.test/dep.js" },
},
],
};
const launcher = completedModuleResolverLauncher(input, async () => {
closes += 1;
controller.abort(reason);
if (!allowClose) throw new Error("controlled close refusal");
});
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
launcher,
);
const result = await provider.resolve(input, {
signal: controller.signal,
});
if (result.ok) throw new Error("expected cancelled finalization");
expect(projectAnalysisError(result.error).code).toBe(
cleanupFails ? "cleanup_incomplete" : "cancelled",
);
expect((result.error.cleanupPrimary ?? result.error).cause).toBe(reason);
expect(
webModuleResolutionObservationSchema.parse(
result.error.partialObservation,
),
).toMatchObject({
kind: "web-module-resolution",
request: input,
batch: {
engine: { version: "controlled-browser" },
resolutions: report.entries.map((entry) => entry.resolution),
rawResult: { native_report: report, executable_path: "/browser" },
},
});
if (cleanupFails) {
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
expect(result.error.cleanupIncomplete).toBe(true);
allowClose = true;
}
await provider.close();
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupResources).toEqual([]);
expect(projectAnalysisError(result.error).code).toBe("cancelled");
expect(closes).toBe(cleanupFails ? 3 : 1);
},
);
});
it.each([
{ stage: "launch", reason: null },
{ stage: "launch", reason: new Error("opaque cancellation reason") },
{ stage: "context", reason: null },
{ stage: "context", reason: new Error("opaque cancellation reason") },
])(
"preserves an independent $stage rejection when cancellation arrives before catch: $reason",
async ({ stage, reason }) => {
const controller = new AbortController();
const physicalFailure = new Error("controlled SDK EIO");
let closes = 0;
const reject = () => {
const rejected = Promise.reject(physicalFailure);
queueMicrotask(() => controller.abort(reason));
return rejected;
};
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
() =>
stage === "launch"
? reject()
: Promise.resolve({
version: () => "controlled-browser",
newContext: reject,
close: async () => {
closes += 1;
},
}),
);
const result = await provider.resolve(input, { signal: controller.signal });
if (result.ok) throw new Error("expected independent rejection");
expect(result.error).toMatchObject({
_tag: "ProviderAdapterError",
cause: physicalFailure,
});
expect(projectAnalysisError(result.error).code).not.toBe("cancelled");
expect(result.error.secondaryFailures).toContainEqual(
expect.objectContaining({
_tag: "AnalysisCancelledError",
cause: reason,
}),
);
await provider.close();
expect(closes).toBe(stage === "launch" ? 0 : 1);
},
);
it.each(["caller", "deadline"] as const)(
"attributes an in-flight SDK rejection to the owned %s stop",
async (control) => {
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "performance"] });
try {
const controller = new AbortController();
const reason = { request: "cancel active browser operation" };
let started!: () => void;
const active = new Promise<void>((resolve) => {
started = resolve;
});
let rejectCall!: (cause: unknown) => void;
let closes = 0;
const provider = new NativeModuleResolver(
{ REA_BROWSER_EXECUTABLE: "/browser" },
async () => ({
version: () => "controlled-browser",
newContext: () => {
started();
return new Promise((_resolve, reject) => {
rejectCall = reject;
});
},
close: async () => {
closes += 1;
rejectCall(new Error("controlled SDK target closed"));
},
}),
);
const pending = provider.resolve(input, { signal: controller.signal });
await active;
if (control === "caller") controller.abort(reason);
else await vi.advanceTimersByTimeAsync(20001);
const result = await pending;
if (result.ok) throw new Error("expected interrupted active call");
expect(projectAnalysisError(result.error).code).toBe(
control === "caller" ? "cancelled" : "provider_timeout",
);
if (control === "caller") expect(result.error.cause).toBe(reason);
expect(result.error.partialObservation).toBeUndefined();
await provider.close();
expect(closes).toBe(1);
} finally {
vi.useRealTimers();
}
},
);