fix(ci): reconcile Git ownership and preserve portable checks
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { buffer } from "node:stream/consumers";
|
||||
|
||||
import { createPackage } from "@electron/asar";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import { AsarArtifactReader } from "../../src/artifacts/AsarArtifactReader.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it("serializes concurrent ASAR snapshot preparation and cleans its single owned root", async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-snapshot-owner-");
|
||||
vi.stubEnv("TMPDIR", root);
|
||||
vi.stubEnv("TMP", root);
|
||||
vi.stubEnv("TEMP", root);
|
||||
|
||||
const source = join(root, "source");
|
||||
const archive = join(root, "app.asar");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "main.js"), "module.exports = 42;\n");
|
||||
await createPackage(source, archive);
|
||||
|
||||
const reader = new AsarArtifactReader(archive);
|
||||
const iterator = reader.entries()[Symbol.asyncIterator]();
|
||||
try {
|
||||
const expectedDigest = createHash("sha256")
|
||||
.update(await readFile(archive))
|
||||
.digest("hex");
|
||||
const openingContainer = reader.openContainer();
|
||||
const readingEntry = iterator.next();
|
||||
const preparingSnapshot = reader.prepareContainer(expectedDigest);
|
||||
const [snapshot, firstEntry] = await Promise.all([
|
||||
openingContainer,
|
||||
readingEntry,
|
||||
preparingSnapshot,
|
||||
]);
|
||||
if (firstEntry.done) throw new Error("Expected an ASAR member");
|
||||
expect(await buffer(snapshot)).toEqual(await readFile(archive));
|
||||
|
||||
const mismatch = reader.prepareContainer("0".repeat(64));
|
||||
const matching = reader.prepareContainer(expectedDigest);
|
||||
await expect(mismatch).rejects.toMatchObject({ reason: "integrity" });
|
||||
await expect(matching).resolves.toBeUndefined();
|
||||
|
||||
const snapshotRoots = async (): Promise<string[]> =>
|
||||
(await readdir(root)).filter((name) =>
|
||||
name.startsWith("rea-asar-snapshot-"),
|
||||
);
|
||||
expect(await snapshotRoots()).toHaveLength(1);
|
||||
await reader.close();
|
||||
expect(await snapshotRoots()).toEqual([]);
|
||||
} finally {
|
||||
try {
|
||||
await iterator.return?.();
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import { createCli } from "../../src/cli.js";
|
||||
import { CLI_COMMANDS } from "../../src/cliCommandNames.js";
|
||||
import * as composition from "../../src/composition/binaryDiagnostics.js";
|
||||
import { BinaryLayoutService } from "../../src/application/binaryDiagnostics/BinaryLayoutService.js";
|
||||
import { RecordedCrashService } from "../../src/application/binaryDiagnostics/RecordedCrashService.js";
|
||||
import { AnalysisOutputError } from "../../src/domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../src/domain/result.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../../src/domain/analysisErrorCleanup.js";
|
||||
|
||||
const exitCode = process.exitCode;
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
process.exitCode = exitCode;
|
||||
});
|
||||
|
||||
it.each(["layout", "recorded"] as const)(
|
||||
"projects the final owned outcome through the public CLI: %s",
|
||||
async (scenario) => {
|
||||
const primary = new AnalysisOutputError(
|
||||
"inspect_binary_layout",
|
||||
"fixture decoder output overflow",
|
||||
{
|
||||
capturedOutput: {
|
||||
stdout: "partial original output",
|
||||
stderr: "warning",
|
||||
truncated: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
const cleanup = new ProviderCleanupError(
|
||||
"fixture-decoder",
|
||||
["owned-process", "/retained/runtime"],
|
||||
{ reason: "fixture process inspection still denied" },
|
||||
);
|
||||
const inspectAndClose = vi.fn(async () =>
|
||||
err(
|
||||
analysisErrorWithCleanupFailure(
|
||||
primary,
|
||||
cleanup,
|
||||
"inspect_binary_layout",
|
||||
),
|
||||
),
|
||||
);
|
||||
const identity = {
|
||||
id: "fixture-decoder",
|
||||
name: "Fixture decoder",
|
||||
version: "1",
|
||||
};
|
||||
if (scenario === "layout")
|
||||
vi.spyOn(composition, "createBinaryLayoutService").mockReturnValue(
|
||||
new BinaryLayoutService({
|
||||
identity,
|
||||
inspect: () => {
|
||||
throw new Error("CLI must request a terminal inspection");
|
||||
},
|
||||
inspectAndClose,
|
||||
}),
|
||||
);
|
||||
else
|
||||
vi.spyOn(composition, "createRecordedCrashService").mockReturnValue(
|
||||
new RecordedCrashService({
|
||||
identity,
|
||||
inspect: () => {
|
||||
throw new Error("CLI must request a terminal inspection");
|
||||
},
|
||||
inspectAndClose,
|
||||
}),
|
||||
);
|
||||
|
||||
const cli = createCli({});
|
||||
let stdout = "";
|
||||
await cli.serve(
|
||||
[
|
||||
scenario === "layout"
|
||||
? CLI_COMMANDS.inspectBinaryLayout
|
||||
: CLI_COMMANDS.inspectRecordedCrash,
|
||||
"/selected/fixture.elf",
|
||||
"--json",
|
||||
],
|
||||
{
|
||||
env: {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => undefined,
|
||||
},
|
||||
);
|
||||
const output: unknown = JSON.parse(stdout);
|
||||
expect(output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
cleanup: "incomplete",
|
||||
resources: ["owned-process", "/retained/runtime"],
|
||||
captured_output: {
|
||||
stdout: "partial original output",
|
||||
stderr: "warning",
|
||||
truncated: true,
|
||||
},
|
||||
diagnostics: {
|
||||
primary_error: { code: "unreadable_output" },
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(inspectAndClose).toHaveBeenCalledOnce();
|
||||
expect(process.exitCode).toBe(1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,302 @@
|
||||
import { Cli } from "incur";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import type { BrowserScenarioCapturePort } from "../../src/application/BrowserScenarioCapturePort.js";
|
||||
import { createBrowserScenarioEvidence } from "../../src/application/BrowserScenarioEvidence.js";
|
||||
import type { BrowserScenarioSessionPort } from "../../src/browser/BrowserScenarioSessionPort.js";
|
||||
import { PlaywrightBrowserScenarioProvider } from "../../src/browser/PlaywrightBrowserScenarioProvider.js";
|
||||
import { PlaywrightScenarioBrowserCleanupOwner } from "../../src/browser/PlaywrightScenarioBrowser.js";
|
||||
import { registerBrowserScenarioCommands } from "../../src/cliBrowserScenarioCommands.js";
|
||||
import { sanitizeBrowserUrl } from "../../src/domain/browserObservation.js";
|
||||
import {
|
||||
browserScenarioSchema,
|
||||
type BrowserScenario,
|
||||
} from "../../src/domain/browserScenario.js";
|
||||
import type { BrowserScenarioAction } from "../../src/domain/browserScenarioValues.js";
|
||||
import { browserStepArtifactsSchema } from "../../src/domain/browserScenarioCaptureValues.js";
|
||||
import { silentLogger } from "../../src/logger.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../../src/domain/analysisErrorCore.js";
|
||||
import { BrowserObservationError } from "../../src/domain/browserObservationError.js";
|
||||
import { parseEvidence } from "../../src/domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../src/domain/result.js";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
provider: undefined as BrowserScenarioCapturePort | undefined,
|
||||
}));
|
||||
vi.mock("../../src/composition/browserScenario.js", () => ({
|
||||
createBrowserScenarioProvider: () => state.provider,
|
||||
}));
|
||||
|
||||
const scenario = browserScenarioSchema.parse({
|
||||
browser: { mode: "launch", executable_path: "/fixture/chromium" },
|
||||
start_url: { url: "https://app.example.test/" },
|
||||
actions: [{ step_id: "wait", action: "wait_for_timeout", duration_ms: 1 }],
|
||||
storage: {},
|
||||
capture: { after_each_step: ["url"], at_end: [], events: [] },
|
||||
});
|
||||
|
||||
// Controlled session failures exercise the real provider and cleanup owner;
|
||||
// this fixture opens no browser process or profile directory.
|
||||
class RetrySession implements BrowserScenarioSessionPort {
|
||||
readonly mode = "launch";
|
||||
readonly processOwnership = "provider-owned";
|
||||
readonly product = "Fixture Chromium";
|
||||
readonly version = "1";
|
||||
readonly initialUrl = "https://app.example.test/";
|
||||
closeBrowserCalls = 0;
|
||||
profileRemovalCalls = 0;
|
||||
readonly cleanup = new PlaywrightScenarioBrowserCleanupOwner({
|
||||
closeBrowser: async () => {
|
||||
this.closeBrowserCalls += 1;
|
||||
if (this.closeBrowserCalls <= this.closeFailures)
|
||||
throw new Error(`injected close failure ${this.closeBrowserCalls}`);
|
||||
},
|
||||
removeProfile: async () => {
|
||||
expect(this.cleanup.browserClosed).toBe(true);
|
||||
this.profileRemovalCalls += 1;
|
||||
},
|
||||
});
|
||||
|
||||
constructor(private readonly closeFailures = 1) {}
|
||||
|
||||
currentUrl() {
|
||||
return this.initialUrl;
|
||||
}
|
||||
sanitizeUrl(value: string) {
|
||||
return sanitizeBrowserUrl(value);
|
||||
}
|
||||
setStep(_index: number) {}
|
||||
nextEventSequence() {
|
||||
return 1;
|
||||
}
|
||||
lastEventSequence() {
|
||||
return 0;
|
||||
}
|
||||
events() {
|
||||
return { retained: 0, dropped: 0, items: [] };
|
||||
}
|
||||
async perform(_action: BrowserScenarioAction) {}
|
||||
async capture(
|
||||
requested: ReadonlySet<
|
||||
BrowserScenario["capture"]["after_each_step"][number]
|
||||
>,
|
||||
) {
|
||||
const artifact = (
|
||||
kind: BrowserScenario["capture"]["after_each_step"][number],
|
||||
) =>
|
||||
!requested.has(kind)
|
||||
? { state: "not_requested" }
|
||||
: kind === "url"
|
||||
? { state: "captured", value: this.sanitizeUrl(this.initialUrl) }
|
||||
: { state: "missing", reason: "fixture unavailable" };
|
||||
return browserStepArtifactsSchema.parse({
|
||||
screenshot: artifact("screenshot"),
|
||||
dom: artifact("dom"),
|
||||
accessibility: artifact("accessibility"),
|
||||
url: artifact("url"),
|
||||
history: artifact("history"),
|
||||
storage: artifact("storage"),
|
||||
});
|
||||
}
|
||||
async close() {
|
||||
await this.cleanup.close();
|
||||
return "terminated-owned-process" as const;
|
||||
}
|
||||
redactError(error: unknown) {
|
||||
return error instanceof Error ? error.message : "fixture failure";
|
||||
}
|
||||
}
|
||||
|
||||
const serveScenario = async () => {
|
||||
const cli = Cli.create("browser-cleanup-test", { sync: false });
|
||||
registerBrowserScenarioCommands(cli, silentLogger, {});
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
await cli.serve(
|
||||
["capture-browser-scenario", JSON.stringify(scenario), "--json"],
|
||||
{
|
||||
env: {},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
},
|
||||
);
|
||||
return {
|
||||
output: jsonObjectSchema.parse(JSON.parse(stdout)),
|
||||
exitCode,
|
||||
processExitCode: process.exitCode,
|
||||
};
|
||||
};
|
||||
|
||||
it("retries retained browser cleanup before the one-shot CLI releases its provider", async () => {
|
||||
const savedExitCode = process.exitCode;
|
||||
const session = new RetrySession();
|
||||
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
|
||||
const close = vi.spyOn(provider, "close");
|
||||
state.provider = provider;
|
||||
try {
|
||||
const result = await serveScenario();
|
||||
expect(result.processExitCode).toBe(1);
|
||||
expect(result.output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
category: "execution_failure",
|
||||
details: {
|
||||
cleanup: "incomplete",
|
||||
resources: ["browser_transport", "browser_profile"],
|
||||
partial_observation: {
|
||||
capture: { browser: { cleanup: "incomplete" } },
|
||||
},
|
||||
},
|
||||
});
|
||||
const details = jsonObjectSchema.parse(result.output.details);
|
||||
const partial = jsonObjectSchema.parse(details.partial_observation);
|
||||
expect(jsonObjectSchema.parse(partial.capture).steps).toHaveLength(2);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(session.closeBrowserCalls).toBe(2);
|
||||
expect(session.profileRemovalCalls).toBe(1);
|
||||
} finally {
|
||||
// The red baseline must also release this controlled owner.
|
||||
await provider.close();
|
||||
state.provider = undefined;
|
||||
process.exitCode = savedExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves the initial partial observation when the provider cleanup retry also fails", async () => {
|
||||
const savedExitCode = process.exitCode;
|
||||
const session = new RetrySession(2);
|
||||
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
|
||||
const close = vi.spyOn(provider, "close");
|
||||
state.provider = provider;
|
||||
try {
|
||||
const result = await serveScenario();
|
||||
expect(result.output).toMatchObject({ code: "cleanup_incomplete" });
|
||||
expect(JSON.stringify(result.output)).toContain("injected close failure 1");
|
||||
expect(JSON.stringify(result.output)).not.toContain(
|
||||
"injected close failure 2",
|
||||
);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(session.closeBrowserCalls).toBe(2);
|
||||
expect(session.profileRemovalCalls).toBe(0);
|
||||
// Retained ownership remains retryable after the command's failed retry.
|
||||
await provider.close();
|
||||
expect(session.closeBrowserCalls).toBe(3);
|
||||
expect(session.profileRemovalCalls).toBe(1);
|
||||
} finally {
|
||||
await provider.close();
|
||||
state.provider = undefined;
|
||||
process.exitCode = savedExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it("retains completed Evidence when provider shutdown fails after a successful capture", async () => {
|
||||
const savedExitCode = process.exitCode;
|
||||
const provider = new PlaywrightBrowserScenarioProvider(
|
||||
async () => new RetrySession(0),
|
||||
);
|
||||
const captured = await provider.captureScenario(scenario);
|
||||
if (!captured.ok) throw captured.error;
|
||||
const evidence = createBrowserScenarioEvidence(
|
||||
scenario,
|
||||
captured.value,
|
||||
provider.identity(),
|
||||
);
|
||||
const close = vi.fn().mockRejectedValue(
|
||||
new BrowserObservationError("capture_browser_scenario", "cleanup_failed", {
|
||||
cleanup: {
|
||||
reason: "injected shutdown failure",
|
||||
resources: ["browser_profile"],
|
||||
},
|
||||
}),
|
||||
);
|
||||
state.provider = {
|
||||
identity: () => provider.identity(),
|
||||
captureScenario: async () => ok(captured.value),
|
||||
close,
|
||||
};
|
||||
try {
|
||||
const result = await serveScenario();
|
||||
expect(result.processExitCode).toBe(1);
|
||||
expect(result.output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { resources: ["browser_profile"] },
|
||||
});
|
||||
const details = jsonObjectSchema.parse(result.output.details);
|
||||
expect(parseEvidence(details.partial_observation)).toEqual(evidence);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await provider.close();
|
||||
state.provider = undefined;
|
||||
process.exitCode = savedExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves cancellation diagnostics while retrying retained cleanup", async () => {
|
||||
const savedExitCode = process.exitCode;
|
||||
const session = new RetrySession();
|
||||
vi.spyOn(session, "capture").mockRejectedValue(
|
||||
new AnalysisCancelledError("capture_browser_scenario"),
|
||||
);
|
||||
const provider = new PlaywrightBrowserScenarioProvider(async () => session);
|
||||
state.provider = provider;
|
||||
try {
|
||||
const result = await serveScenario();
|
||||
expect(result.output).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
category: "execution_failure",
|
||||
details: {
|
||||
cleanup: "incomplete",
|
||||
diagnostics: {
|
||||
primary_error: { code: "cancelled", category: "cancelled" },
|
||||
},
|
||||
partial_observation: { kind: "browser-scenario-observation" },
|
||||
},
|
||||
});
|
||||
expect(session.closeBrowserCalls).toBe(2);
|
||||
expect(session.profileRemovalCalls).toBe(1);
|
||||
} finally {
|
||||
await provider.close();
|
||||
state.provider = undefined;
|
||||
process.exitCode = savedExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves a thrown capture error when provider shutdown also rejects", async () => {
|
||||
const savedExitCode = process.exitCode;
|
||||
const provider = new PlaywrightBrowserScenarioProvider(
|
||||
async () => new RetrySession(0),
|
||||
);
|
||||
const primary = new AnalysisTimeoutError("capture_browser_scenario", 123);
|
||||
const close = vi
|
||||
.fn()
|
||||
.mockRejectedValue(new Error("secondary shutdown failure"));
|
||||
state.provider = {
|
||||
identity: () => provider.identity(),
|
||||
captureScenario: async () => {
|
||||
throw primary;
|
||||
},
|
||||
close,
|
||||
};
|
||||
try {
|
||||
const result = await serveScenario();
|
||||
expect(result.output).toMatchObject({
|
||||
code: "provider_timeout",
|
||||
category: "timeout",
|
||||
});
|
||||
expect(JSON.stringify(result.output)).not.toContain(
|
||||
"secondary shutdown failure",
|
||||
);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await provider.close();
|
||||
state.provider = undefined;
|
||||
process.exitCode = savedExitCode;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { chmod, copyFile, readFile, symlink, unlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { assertCleanLinuxHopperRuntime } from "../../scripts/lib/clean-linux-hopper-runtime.mjs";
|
||||
import { completeVerifierRun } from "../../scripts/lib/verifier-run.mjs";
|
||||
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
it
|
||||
.runIf(process.platform === "linux")
|
||||
.each(["demo helper", "alternate launcher"])(
|
||||
"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 alternateMode = mode === "alternate launcher";
|
||||
if (alternateMode) {
|
||||
await copyFile("/usr/bin/sleep", launcher);
|
||||
await chmod(launcher, 0o700);
|
||||
await symlink(launcher, alternate);
|
||||
}
|
||||
const command = alternateMode ? alternate : process.execPath;
|
||||
const arguments_ = alternateMode ? ["30"] : ["-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"])}
|
||||
});
|
||||
child.once('error', () => process.exit(1));
|
||||
child.once(${JSON.stringify(alternateMode ? "spawn" : "message")}, () => {
|
||||
process.stdout.write(JSON.stringify({ pid: child.pid, parentPid: process.pid }));
|
||||
if (child.connected) child.disconnect();
|
||||
child.unref();
|
||||
});
|
||||
`;
|
||||
const parent = execFileAsync(process.execPath, ["-e", parentCode], {
|
||||
env: { ...process.env, REA_PROCESS_RUN_ID: runId },
|
||||
timeout: 10_000,
|
||||
});
|
||||
const parentPid = parent.child.pid;
|
||||
if (parentPid === undefined)
|
||||
throw new Error("Fixture parent did not spawn");
|
||||
let orphanPid: number | undefined;
|
||||
try {
|
||||
const { stdout } = await parent;
|
||||
const { pid } = JSON.parse(stdout) as { pid: number };
|
||||
orphanPid = pid;
|
||||
const { stdout: coordinates } = await execFileAsync("ps", [
|
||||
"-p",
|
||||
String(pid),
|
||||
"-o",
|
||||
"ppid=,pgid=",
|
||||
]);
|
||||
const [currentParent, group] = coordinates
|
||||
.trim()
|
||||
.split(/\s+/u)
|
||||
.map(Number);
|
||||
expect(currentParent).not.toBe(parentPid);
|
||||
expect(group).toBe(pid);
|
||||
|
||||
const lineage = await completeVerifierRun({
|
||||
run_id: runId,
|
||||
verifier_pid: process.pid,
|
||||
parent_pid: process.ppid,
|
||||
});
|
||||
expect(lineage.process_lineage.status).toBe("verified");
|
||||
if (lineage.process_lineage.status === "verified")
|
||||
expect(
|
||||
lineage.process_lineage.descendants.some((p) => p.pid === pid),
|
||||
).toBe(false);
|
||||
|
||||
if (alternateMode) {
|
||||
const commandLine = await readFile(
|
||||
`/proc/${String(pid)}/cmdline`,
|
||||
"utf8",
|
||||
);
|
||||
expect(commandLine.split("\0")[0]).toBe(alternate);
|
||||
await unlink(alternate);
|
||||
}
|
||||
await expect(
|
||||
assertCleanLinuxHopperRuntime(alternateMode ? [launcher] : []),
|
||||
).rejects.toThrow("Clean Linux runner retained a Hopper demo process");
|
||||
// Observation must not terminate the fixture, even though it resembles Xvfb.
|
||||
const { stdout: alive } = await execFileAsync("ps", [
|
||||
"-p",
|
||||
String(pid),
|
||||
"-o",
|
||||
"stat=",
|
||||
]);
|
||||
expect(alive.trim()).not.toMatch(/^Z/u);
|
||||
} finally {
|
||||
if (orphanPid !== undefined) {
|
||||
const cleanup = await cleanupOwnedProcessGroup({
|
||||
runId,
|
||||
leaderPid: orphanPid,
|
||||
processGroupId: orphanPid,
|
||||
});
|
||||
expect(cleanup.cleaned, JSON.stringify(cleanup)).toBe(true);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -86,6 +86,7 @@ it("keeps independent server budgets for successful results and oversized errors
|
||||
message: diagnostic,
|
||||
},
|
||||
]),
|
||||
false,
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
it,
|
||||
onTestFinished,
|
||||
} from "vitest";
|
||||
|
||||
import { PwntoolsLayoutProvider } from "../../src/native/pwntools/PwntoolsLayoutProvider.js";
|
||||
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
|
||||
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
|
||||
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
|
||||
import { stopProviderProcessFixture } from "../fixtures/providerProcess.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../support/workspace/workspaceFixture.js";
|
||||
|
||||
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
||||
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
const supportedHost = process.platform !== "win32";
|
||||
|
||||
beforeAll(() =>
|
||||
supportedHost ? prepareProcessOwnershipInspection() : undefined,
|
||||
);
|
||||
|
||||
// Only the decoder's availability gate is simulated. The module-owned process
|
||||
// inspector was created and prepared for the real host before these overrides;
|
||||
// every fixture launch, output stream, cleanup signal and filesystem is real.
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
Object.defineProperty(process, "arch", { value: "x64" });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (platform !== undefined)
|
||||
Object.defineProperty(process, "platform", platform);
|
||||
if (architecture !== undefined)
|
||||
Object.defineProperty(process, "arch", architecture);
|
||||
});
|
||||
|
||||
const fixture = async () => {
|
||||
const workspace = await createTestWorkspace("rea-pwntools-cleanup-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = join(workspace.root, "selected.elf");
|
||||
await writeFile(path, "source-owned-seam-bytes");
|
||||
return { workspace, path };
|
||||
};
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"retains live worker files, refuses another launch, and retries cleanup on close",
|
||||
async () => {
|
||||
const { workspace, path } = await fixture();
|
||||
let ownedPath = "";
|
||||
let pid: number | undefined;
|
||||
let launches = 0;
|
||||
let cleanupAllowed = false;
|
||||
let releaseFixture: (() => Promise<void>) | undefined;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (input) => {
|
||||
launches++;
|
||||
ownedPath = input.cwd ?? "";
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...input,
|
||||
arguments: [
|
||||
"-e",
|
||||
'process.stdout.write("x".repeat(1048577)); setInterval(() => undefined, 1000)',
|
||||
],
|
||||
});
|
||||
pid = launched.process.pid;
|
||||
releaseFixture = () => stopProviderProcessFixture(launched.process);
|
||||
return {
|
||||
...launched,
|
||||
cleanup: () =>
|
||||
cleanupAllowed
|
||||
? cleanupOwnedProcessGroup(launched.ownership)
|
||||
: Promise.resolve({
|
||||
cleaned: false as const,
|
||||
reason: "fixture process inspection denied",
|
||||
}),
|
||||
};
|
||||
},
|
||||
() =>
|
||||
PrivateRuntimeRoot.create({ parent: workspace.root, prefix: "owned-" }),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
await releaseFixture?.();
|
||||
});
|
||||
|
||||
const result = await provider.inspect({ path });
|
||||
if (result.ok)
|
||||
throw new Error("Expected output overflow and failed cleanup");
|
||||
expect(result.error).toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "unreadable_output",
|
||||
details: { captured_output: { truncated: true } },
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
});
|
||||
if (pid === undefined)
|
||||
throw new Error("The fixture did not acquire a process");
|
||||
const workerPid = pid;
|
||||
expect(() => process.kill(workerPid, 0)).not.toThrow();
|
||||
expect(await readFile(join(ownedPath, "object.snapshot"), "utf8")).toBe(
|
||||
"source-owned-seam-bytes",
|
||||
);
|
||||
const refused = await provider.inspect({ path });
|
||||
if (refused.ok)
|
||||
throw new Error("Unreleased ownership must block another launch");
|
||||
expect(refused.error.cleanupResources).toContain(ownedPath);
|
||||
expect(launches).toBe(1);
|
||||
await expect(provider.close()).rejects.toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
});
|
||||
await expect(access(ownedPath)).resolves.toBeUndefined();
|
||||
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
expect(() => process.kill(workerPid, 0)).toThrow();
|
||||
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"retains a failed root removal and retries it before acquiring another decoder",
|
||||
async () => {
|
||||
const { workspace, path } = await fixture();
|
||||
let releases = 0;
|
||||
let launches = 0;
|
||||
let removalAllowed = false;
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
parent: workspace.root,
|
||||
prefix: "owned-",
|
||||
});
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (input) => {
|
||||
launches++;
|
||||
return spawnOwnedProviderProcess({
|
||||
...input,
|
||||
arguments: [
|
||||
"-e",
|
||||
'process.stdout.write("retained diagnostic"); process.exitCode = 2',
|
||||
],
|
||||
});
|
||||
},
|
||||
async () => ({
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
releases++;
|
||||
if (!removalAllowed) throw new Error("fixture root removal denied");
|
||||
await root.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
removalAllowed = true;
|
||||
await provider.close();
|
||||
await root.close();
|
||||
});
|
||||
const result = await provider.inspect({ path });
|
||||
if (result.ok)
|
||||
throw new Error("Expected command and root-removal failures");
|
||||
expect(result.error).toMatchObject({
|
||||
cleanupIncomplete: true,
|
||||
diagnostics: {
|
||||
primary_error: {
|
||||
code: "execution_failure",
|
||||
details: { diagnostics: { stdout: "retained diagnostic" } },
|
||||
},
|
||||
cleanup_error: { code: "cleanup_incomplete" },
|
||||
},
|
||||
});
|
||||
const refused = await provider.inspect({ path });
|
||||
if (refused.ok)
|
||||
throw new Error("Retained root cleanup must precede a new launch");
|
||||
expect(refused.error.cleanupResources).toEqual([root.path]);
|
||||
expect(launches).toBe(1);
|
||||
expect(releases).toBe(2);
|
||||
removalAllowed = true;
|
||||
await provider.close();
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"cancels queued inspections promptly and drains the running inspection when closing",
|
||||
async () => {
|
||||
const { workspace, path } = await fixture();
|
||||
let release: (() => void) | undefined;
|
||||
let entered: (() => void) | undefined;
|
||||
const gate = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const started = new Promise<void>((resolve) => {
|
||||
entered = resolve;
|
||||
});
|
||||
let launches = 0;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (input) => {
|
||||
launches++;
|
||||
entered?.();
|
||||
await gate;
|
||||
return spawnOwnedProviderProcess({
|
||||
...input,
|
||||
arguments: ["-e", "process.exit(2)"],
|
||||
});
|
||||
},
|
||||
() =>
|
||||
PrivateRuntimeRoot.create({ parent: workspace.root, prefix: "owned-" }),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
release?.();
|
||||
await provider.close();
|
||||
});
|
||||
const first = provider.inspect({ path });
|
||||
await started;
|
||||
const controller = new AbortController();
|
||||
const cancelled = provider.inspect({ path }, { signal: controller.signal });
|
||||
controller.abort();
|
||||
await expect(cancelled).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
const queued = provider.inspect({ path });
|
||||
const closing = provider.close();
|
||||
const late = provider.inspect({ path });
|
||||
release?.();
|
||||
const [firstResult, queuedResult, lateResult] = await Promise.all([
|
||||
first,
|
||||
queued,
|
||||
late,
|
||||
]);
|
||||
if (firstResult.ok) throw new Error("The fixture exits with failure");
|
||||
expect(firstResult.error).not.toMatchObject({ cleanupIncomplete: true });
|
||||
expect(queuedResult).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
cleanupIncomplete: false,
|
||||
},
|
||||
});
|
||||
expect(lateResult).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
cleanupIncomplete: false,
|
||||
},
|
||||
});
|
||||
await closing;
|
||||
expect(launches).toBe(1);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,308 @@
|
||||
import { z } from "zod";
|
||||
import { access, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
it,
|
||||
onTestFinished,
|
||||
vi,
|
||||
} from "vitest";
|
||||
|
||||
import { BinaryLayoutService } from "../../src/application/binaryDiagnostics/BinaryLayoutService.js";
|
||||
import { createCli } from "../../src/cli.js";
|
||||
import * as composition from "../../src/composition/binaryDiagnostics.js";
|
||||
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
|
||||
import { PwntoolsLayoutProvider } from "../../src/native/pwntools/PwntoolsLayoutProvider.js";
|
||||
import type { PwntoolsLauncher } from "../../src/native/pwntools/PwntoolsDecoder.js";
|
||||
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../src/native/pwntools/PwntoolsRelease.js";
|
||||
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
|
||||
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
|
||||
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
|
||||
import { binaryLayoutFixture } from "../fixtures/binaryDiagnostics/layout.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../support/workspace/workspaceFixture.js";
|
||||
|
||||
const supportedHost = process.platform !== "win32";
|
||||
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
||||
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
const exitCode = process.exitCode;
|
||||
|
||||
beforeAll(() =>
|
||||
supportedHost ? prepareProcessOwnershipInspection() : undefined,
|
||||
);
|
||||
beforeEach(() => {
|
||||
// Prepare the real host inspector first; only decoder availability is simulated.
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
Object.defineProperty(process, "arch", { value: "x64" });
|
||||
});
|
||||
afterEach(() => {
|
||||
if (platform !== undefined)
|
||||
Object.defineProperty(process, "platform", platform);
|
||||
if (architecture !== undefined)
|
||||
Object.defineProperty(process, "arch", architecture);
|
||||
process.exitCode = exitCode;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const fixture = async (outcome: "decoded" | "failed" = "decoded") => {
|
||||
const workspace = await createTestWorkspace("rea-pwntools-finalization-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("selected.elf");
|
||||
await writeFile(path, Buffer.alloc(128));
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
parent: workspace.root,
|
||||
prefix: "owned-",
|
||||
});
|
||||
const {
|
||||
artifact: _artifact,
|
||||
diagnostics: _diagnostics,
|
||||
...payload
|
||||
} = binaryLayoutFixture(path);
|
||||
const launch: PwntoolsLauncher = async (input) => {
|
||||
const request = z
|
||||
.object({ reply_path: z.string() })
|
||||
.parse(
|
||||
JSON.parse(await readFile(join(root.path, "request.json"), "utf8")),
|
||||
);
|
||||
return spawnOwnedProviderProcess({
|
||||
...input,
|
||||
arguments: [
|
||||
"-e",
|
||||
outcome === "decoded"
|
||||
? 'require("node:fs").writeFileSync(process.argv[1], process.argv[2]); process.stdout.write("decoder output")'
|
||||
: 'process.stdout.write("decoder output"); process.exitCode = 2',
|
||||
request.reply_path,
|
||||
JSON.stringify({
|
||||
ok: true,
|
||||
profile: PWNTOOLS_PROVIDER_IDENTITY.version,
|
||||
value: payload,
|
||||
}),
|
||||
],
|
||||
});
|
||||
};
|
||||
return { path, root, launch };
|
||||
};
|
||||
|
||||
const runCli = async (
|
||||
provider: PwntoolsLayoutProvider,
|
||||
path: string,
|
||||
): Promise<unknown> => {
|
||||
vi.spyOn(composition, "createBinaryLayoutService").mockReturnValue(
|
||||
new BinaryLayoutService(provider),
|
||||
);
|
||||
let stdout = "";
|
||||
await createCli({}).serve(["inspect-binary-layout", path, "--json"], {
|
||||
env: {},
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: () => undefined,
|
||||
});
|
||||
return JSON.parse(stdout);
|
||||
};
|
||||
|
||||
it.runIf(supportedHost).each(["decoded", "failed"] as const)(
|
||||
"returns the original %s outcome after a successful runtime-removal retry through the CLI",
|
||||
async (outcome) => {
|
||||
const { path, root, launch } = await fixture(outcome);
|
||||
let removals = 0;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
launch,
|
||||
async () => ({
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (++removals === 1) throw new Error("transient removal failure");
|
||||
await root.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onTestFinished(() => provider.close());
|
||||
const output = await runCli(provider, path);
|
||||
if (outcome === "decoded") {
|
||||
expect(output).toMatchObject({
|
||||
normalized_result: {
|
||||
artifact: { path },
|
||||
diagnostics: { stdout: "decoder output", truncated: false },
|
||||
},
|
||||
});
|
||||
expect(process.exitCode ?? 0).toBe(0);
|
||||
} else {
|
||||
expect(output).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
exit_code: 2,
|
||||
captured_output: { stdout: "decoder output" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(output).not.toHaveProperty("details.cleanup");
|
||||
expect(process.exitCode).toBe(1);
|
||||
}
|
||||
expect(removals).toBe(2);
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"recovers a completed worker reply after terminal process cleanup succeeds",
|
||||
async () => {
|
||||
const { path, root, launch } = await fixture();
|
||||
let stops = 0;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (input) => {
|
||||
const launched = await launch(input);
|
||||
return {
|
||||
...launched,
|
||||
cleanup: () =>
|
||||
++stops < 3
|
||||
? Promise.resolve({
|
||||
cleaned: false as const,
|
||||
reason: "transient process inspection failure",
|
||||
})
|
||||
: cleanupOwnedProcessGroup(launched.ownership),
|
||||
};
|
||||
},
|
||||
async () => root,
|
||||
);
|
||||
onTestFinished(() => provider.close());
|
||||
expect(await runCli(provider, path)).toMatchObject({
|
||||
normalized_result: { artifact: { path } },
|
||||
});
|
||||
expect(process.exitCode ?? 0).toBe(0);
|
||||
expect(stops).toBe(3);
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"reports only the runtime still owned after process retirement",
|
||||
async () => {
|
||||
const { path, root, launch } = await fixture("failed");
|
||||
let stops = 0;
|
||||
let removalAllowed = false;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
async (input) => {
|
||||
const launched = await launch(input);
|
||||
return {
|
||||
...launched,
|
||||
cleanup: () =>
|
||||
++stops === 1
|
||||
? Promise.resolve({
|
||||
cleaned: false as const,
|
||||
reason: "transient process inspection failure",
|
||||
})
|
||||
: cleanupOwnedProcessGroup(launched.ownership),
|
||||
};
|
||||
},
|
||||
async () => ({
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!removalAllowed) throw new Error("runtime removal denied");
|
||||
await root.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
removalAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
expect(await runCli(provider, path)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
resources: [root.path],
|
||||
diagnostics: {
|
||||
primary_error: { code: "execution_failure" },
|
||||
cleanup_error: {
|
||||
code: "cleanup_incomplete",
|
||||
details: { resources: [root.path] },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(stops).toBe(2);
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"preserves the validated report when runtime removal remains denied",
|
||||
async () => {
|
||||
const { path, root, launch } = await fixture();
|
||||
let removalAllowed = false;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
launch,
|
||||
async () => ({
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (!removalAllowed) throw new Error("runtime removal denied");
|
||||
await root.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
removalAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
expect(await runCli(provider, path)).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
resources: [root.path],
|
||||
partial_observation: {
|
||||
artifact: { path },
|
||||
diagnostics: { stdout: "decoder output", truncated: false },
|
||||
sections: binaryLayoutFixture(path).sections,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(process.exitCode).toBe(1);
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"preserves cancellation during successful final cleanup",
|
||||
async () => {
|
||||
const { path, root, launch } = await fixture();
|
||||
const controller = new AbortController();
|
||||
let removals = 0;
|
||||
const provider = new PwntoolsLayoutProvider(
|
||||
{ REA_PWNTOOLS_PYTHON: process.execPath },
|
||||
launch,
|
||||
async () => ({
|
||||
path: root.path,
|
||||
close: async () => {
|
||||
if (++removals === 1) {
|
||||
controller.abort();
|
||||
throw new Error("transient removal failure");
|
||||
}
|
||||
await root.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
onTestFinished(() => provider.close());
|
||||
const result = await provider.inspectAndClose(
|
||||
{ path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok)
|
||||
throw new Error("Cancelled inspection must not publish success");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "cancelled",
|
||||
details: {
|
||||
captured_output: { stdout: "decoder output", truncated: false },
|
||||
},
|
||||
});
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,364 @@
|
||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import {
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
it,
|
||||
onTestFinished,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { z } from "zod";
|
||||
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
|
||||
import { PwntoolsRecordedCrashProvider } from "../../src/native/pwntools/PwntoolsRecordedCrashProvider.js";
|
||||
import type { PwntoolsLauncher } from "../../src/native/pwntools/PwntoolsDecoder.js";
|
||||
import {
|
||||
PWNTOOLS_MEMORY_FAILURE_EXIT,
|
||||
PWNTOOLS_PROVIDER_IDENTITY,
|
||||
} from "../../src/native/pwntools/PwntoolsRelease.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
|
||||
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
|
||||
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
|
||||
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
|
||||
import * as artifacts from "../../src/artifacts/readStableArtifact.js";
|
||||
import {
|
||||
recordedCrashFixture,
|
||||
recordedCrashFixtureBytes,
|
||||
recordedCrashDebuggerFixture,
|
||||
} from "../fixtures/binaryDiagnostics/recordedCrash.js";
|
||||
import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../support/workspace/workspaceFixture.js";
|
||||
|
||||
const supportedHost = process.platform !== "win32";
|
||||
const platform = Object.getOwnPropertyDescriptor(process, "platform");
|
||||
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
const worker = fileURLToPath(
|
||||
new URL("../fixtures/pwntoolsChangingArtifact.mjs", import.meta.url),
|
||||
);
|
||||
beforeAll(() =>
|
||||
supportedHost ? prepareProcessOwnershipInspection() : undefined,
|
||||
);
|
||||
beforeEach(() => {
|
||||
// Use the actual host inspector; simulate only the decoder availability gate.
|
||||
Object.defineProperty(process, "platform", { value: "linux" });
|
||||
Object.defineProperty(process, "arch", { value: "x64" });
|
||||
});
|
||||
afterEach(() => {
|
||||
if (platform !== undefined)
|
||||
Object.defineProperty(process, "platform", platform);
|
||||
if (architecture !== undefined)
|
||||
Object.defineProperty(process, "arch", architecture);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const fixture = async () => {
|
||||
const workspace = await createTestWorkspace("rea-stage-retirement-");
|
||||
onTestFinished(() => removeTestWorkspace(workspace.root));
|
||||
const path = workspace.path("selected.core");
|
||||
const value = recordedCrashFixture(path);
|
||||
await writeFile(path, recordedCrashFixtureBytes(value));
|
||||
const root = await PrivateRuntimeRoot.create({
|
||||
parent: workspace.root,
|
||||
prefix: "owned-",
|
||||
});
|
||||
const venv = workspace.path("venv");
|
||||
const plugin = workspace.path("gdbinit.py");
|
||||
await mkdir(venv);
|
||||
await writeFile(plugin, "");
|
||||
const environment = {
|
||||
REA_PWNTOOLS_PYTHON: process.execPath,
|
||||
REA_PWNDBG_GDB: process.execPath,
|
||||
REA_PWNDBG_GDBINIT: plugin,
|
||||
REA_PWNDBG_VENV_PATH: venv,
|
||||
};
|
||||
const {
|
||||
artifact: _artifact,
|
||||
diagnostics: _diagnostics,
|
||||
debugger: _debugger,
|
||||
decoder_diagnostics: _decoderDiagnostics,
|
||||
...payload
|
||||
} = value;
|
||||
const reply = JSON.stringify({
|
||||
ok: true,
|
||||
profile: PWNTOOLS_PROVIDER_IDENTITY.version,
|
||||
value: payload,
|
||||
});
|
||||
const basic: PwntoolsLauncher = async (spawn) => {
|
||||
await writeFile(join(root.path, "reply.json"), reply);
|
||||
return spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: ["-e", "process.stdout.write('basic diagnostic')"],
|
||||
});
|
||||
};
|
||||
return { path, root, environment, basic };
|
||||
};
|
||||
|
||||
const changingWorker = async (
|
||||
spawn: Parameters<NonNullable<PwntoolsLauncher>>[0],
|
||||
path: string,
|
||||
contents: { initial: string; final: string; exitCode: number },
|
||||
cleanupAllowed: () => boolean = () => true,
|
||||
) => {
|
||||
const trigger = join(spawn.cwd ?? "", "change.trigger");
|
||||
const ready = join(spawn.cwd ?? "", "descendant.ready");
|
||||
const done = join(spawn.cwd ?? "", "change.done");
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: [
|
||||
worker,
|
||||
"leader",
|
||||
path,
|
||||
contents.initial,
|
||||
contents.final,
|
||||
trigger,
|
||||
ready,
|
||||
done,
|
||||
String(contents.exitCode),
|
||||
],
|
||||
});
|
||||
let stops = 0;
|
||||
return {
|
||||
...launched,
|
||||
cleanup: async () => {
|
||||
if (++stops === 1 || !cleanupAllowed())
|
||||
return {
|
||||
cleaned: false as const,
|
||||
reason: "fixture inspection unavailable",
|
||||
};
|
||||
const descendant = Number(await readFile(ready, "utf8"));
|
||||
expect(() => process.kill(descendant, 0)).not.toThrow();
|
||||
await writeFile(trigger, "change now");
|
||||
await expect
|
||||
.poll(() =>
|
||||
access(done).then(
|
||||
() => true,
|
||||
() => false,
|
||||
),
|
||||
)
|
||||
.toBe(true);
|
||||
return cleanupOwnedProcessGroup(launched.ownership);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
it.runIf(supportedHost).each(["decoder", "debugger"] as const)(
|
||||
"classifies %s failure markers only after surviving descendants stop",
|
||||
async (stage) => {
|
||||
const { path, root, environment, basic } = await fixture();
|
||||
let launches = 0;
|
||||
const provider = new PwntoolsRecordedCrashProvider(
|
||||
environment,
|
||||
async (spawn) => {
|
||||
if (stage === "debugger" && ++launches === 1) return basic(spawn);
|
||||
const marker = join(spawn.cwd ?? "", "resource.failure");
|
||||
await writeFile(
|
||||
join(spawn.cwd ?? "", "limits.json"),
|
||||
JSON.stringify(recordedCrashDebuggerFixture().reported_limits),
|
||||
);
|
||||
return changingWorker(spawn, marker, {
|
||||
initial: "M",
|
||||
final: "!",
|
||||
exitCode: PWNTOOLS_MEMORY_FAILURE_EXIT,
|
||||
});
|
||||
},
|
||||
async () => root,
|
||||
);
|
||||
onTestFinished(() => provider.close());
|
||||
const result = await provider.inspectAndClose({
|
||||
path,
|
||||
include_debugger_context: stage === "debugger",
|
||||
});
|
||||
if (result.ok) throw new Error("Expected the original command failure");
|
||||
expect(projectAnalysisError(result.error)).toMatchObject({
|
||||
code: "execution_failure",
|
||||
details: {
|
||||
diagnostics: {
|
||||
phase: stage,
|
||||
resource_failure_marker: { resource: null },
|
||||
exit_code: PWNTOOLS_MEMORY_FAILURE_EXIT,
|
||||
captured_output: { stdout: "stage diagnostic" },
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"publishes debugger replies only after surviving descendants stop",
|
||||
async () => {
|
||||
const { path, root, environment, basic } = await fixture();
|
||||
let launches = 0;
|
||||
const context = recordedCrashDebuggerFixture();
|
||||
const finalContext = { ...context, pwndbg_version: "after retirement" };
|
||||
const provider = new PwntoolsRecordedCrashProvider(
|
||||
environment,
|
||||
async (spawn) => {
|
||||
if (++launches === 1) return basic(spawn);
|
||||
return changingWorker(spawn, join(spawn.cwd ?? "", "reply.json"), {
|
||||
initial: JSON.stringify({ ok: true, value: context }),
|
||||
final: JSON.stringify({ ok: true, value: finalContext }),
|
||||
exitCode: 0,
|
||||
});
|
||||
},
|
||||
async () => root,
|
||||
);
|
||||
onTestFinished(() => provider.close());
|
||||
const result = await provider.inspectAndClose({
|
||||
path,
|
||||
include_debugger_context: true,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.debugger).toMatchObject({
|
||||
status: "available",
|
||||
pwndbg_version: "after retirement",
|
||||
});
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost).each([
|
||||
{ stage: "decoder", outcome: "success" },
|
||||
{ stage: "decoder", outcome: "failure" },
|
||||
{ stage: "debugger", outcome: "success" },
|
||||
{ stage: "debugger", outcome: "failure" },
|
||||
] as const)(
|
||||
"does not read unresolved $stage files after command $outcome",
|
||||
async ({ stage, outcome }) => {
|
||||
const { path, root, environment, basic } = await fixture();
|
||||
let launches = 0;
|
||||
let cleanupAllowed = false;
|
||||
const read = vi.spyOn(artifacts, "readStableArtifact");
|
||||
const provider = new PwntoolsRecordedCrashProvider(
|
||||
environment,
|
||||
async (spawn) => {
|
||||
if (stage === "debugger" && ++launches === 1) return basic(spawn);
|
||||
return changingWorker(
|
||||
spawn,
|
||||
join(spawn.cwd ?? "", "resource.failure"),
|
||||
{
|
||||
initial: "M",
|
||||
final: "!",
|
||||
exitCode: outcome === "success" ? 0 : PWNTOOLS_MEMORY_FAILURE_EXIT,
|
||||
},
|
||||
() => cleanupAllowed,
|
||||
);
|
||||
},
|
||||
async () => root,
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspectAndClose({
|
||||
path,
|
||||
include_debugger_context: true,
|
||||
});
|
||||
if (result.ok) throw new Error("Expected unresolved process ownership");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected.code).toBe("cleanup_incomplete");
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
resources: expect.arrayContaining([
|
||||
expect.stringMatching(/^pid:\d+$/u),
|
||||
expect.stringMatching(/^process-group:\d+$/u),
|
||||
]),
|
||||
},
|
||||
});
|
||||
if (stage === "debugger")
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
partial_observation: {
|
||||
artifact: { path },
|
||||
debugger: { status: "unavailable", requested: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (outcome === "failure")
|
||||
expect(projected).toMatchObject({
|
||||
details: {
|
||||
diagnostics: {
|
||||
primary_error: { code: "execution_failure" },
|
||||
},
|
||||
},
|
||||
});
|
||||
const stagePath =
|
||||
stage === "debugger" ? join(root.path, "debugger") : root.path;
|
||||
const paths = read.mock.calls.map(([selected]) => selected);
|
||||
for (const file of ["reply.json", "resource.failure", "limits.json"])
|
||||
expect(paths).not.toContain(join(stagePath, file));
|
||||
const descendant = Number(
|
||||
await readFile(join(stagePath, "descendant.ready"), "utf8"),
|
||||
);
|
||||
expect(() => process.kill(descendant, 0)).not.toThrow();
|
||||
await expect(access(root.path)).resolves.toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(supportedHost)(
|
||||
"retains a live debugger after output overflow with basic evidence and retryable cleanup",
|
||||
async () => {
|
||||
const { path, root, environment, basic } = await fixture();
|
||||
let launches = 0;
|
||||
let pid: number | undefined;
|
||||
let cleanupAllowed = false;
|
||||
const provider = new PwntoolsRecordedCrashProvider(
|
||||
environment,
|
||||
async (spawn) => {
|
||||
if (++launches === 1) return basic(spawn);
|
||||
const launched = await spawnOwnedProviderProcess({
|
||||
...spawn,
|
||||
arguments: [
|
||||
"-e",
|
||||
'process.stdout.write("x".repeat(1048577)); setInterval(() => undefined, 1000)',
|
||||
],
|
||||
});
|
||||
pid = launched.process.pid;
|
||||
return {
|
||||
...launched,
|
||||
cleanup: () =>
|
||||
cleanupAllowed
|
||||
? cleanupOwnedProcessGroup(launched.ownership)
|
||||
: Promise.resolve({
|
||||
cleaned: false as const,
|
||||
reason: "fixture inspection unavailable",
|
||||
}),
|
||||
};
|
||||
},
|
||||
async () => root,
|
||||
);
|
||||
onTestFinished(async () => {
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
});
|
||||
const result = await provider.inspectAndClose({
|
||||
path,
|
||||
include_debugger_context: true,
|
||||
});
|
||||
if (result.ok) throw new Error("Expected retained output-limit failure");
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
captured_output: { truncated: true },
|
||||
diagnostics: { primary_error: { code: "unreadable_output" } },
|
||||
partial_observation: {
|
||||
artifact: { path },
|
||||
diagnostics: { stdout: "basic diagnostic" },
|
||||
debugger: { status: "unavailable", requested: true },
|
||||
},
|
||||
},
|
||||
});
|
||||
if (pid === undefined) throw new Error("Expected a live owned debugger");
|
||||
const debuggerPid = pid;
|
||||
expect(() => process.kill(debuggerPid, 0)).not.toThrow();
|
||||
cleanupAllowed = true;
|
||||
await provider.close();
|
||||
expect(() => process.kill(debuggerPid, 0)).toThrow();
|
||||
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,55 @@
|
||||
import { readFile, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("node:fs", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("node:fs")>();
|
||||
return {
|
||||
...original,
|
||||
constants: { ...original.constants, O_NOFOLLOW: 0 },
|
||||
};
|
||||
});
|
||||
|
||||
import { openRegularFile } from "../../src/filesystem/RegularFile.js";
|
||||
import { ZipArtifactReader } from "../../src/artifacts/ZipArtifactReader.js";
|
||||
import { writeOrderedZip } from "../fixtures/artifactEntryOrder.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
it("rejects a symlink when O_NOFOLLOW is unavailable and still follows when requested", async () => {
|
||||
const root = await createTestTempDirectory("rea-no-nofollow-");
|
||||
const target = join(root, "target.zip");
|
||||
const link = join(root, "selected.zip");
|
||||
await writeOrderedZip(target, ["member.bin"]);
|
||||
await symlink(target, link);
|
||||
|
||||
const reader = new ZipArtifactReader(target, "zip");
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
expect(entries.map(({ path }) => path)).toEqual(["member.bin"]);
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
|
||||
const linkedReader = new ZipArtifactReader(link, "zip");
|
||||
try {
|
||||
await expect(async () => {
|
||||
for await (const _entry of linkedReader.entries()) {
|
||||
// Consume through the public reader boundary.
|
||||
}
|
||||
}).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "format",
|
||||
});
|
||||
} finally {
|
||||
await linkedReader.close();
|
||||
}
|
||||
|
||||
const followed = await openRegularFile(link, { symlinks: "follow" });
|
||||
try {
|
||||
await expect(readFile(followed)).resolves.toEqual(await readFile(target));
|
||||
} finally {
|
||||
await followed.close();
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { readFile, utimes, writeFile } from "node:fs/promises";
|
||||
import { copyFile, mkdir, readFile, utimes, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
@@ -116,6 +116,66 @@ it("does not treat an old database timestamp as permission to replace a live own
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves executable arguments through the public runner", async () => {
|
||||
const directory = await createTestTempDirectory("rea-runner-argv-");
|
||||
const payload = 'spaces, "quotes", & ^ % ! (parens)';
|
||||
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
|
||||
expect(
|
||||
await execute(directory, process.execPath, ["-e", code, payload]),
|
||||
).toMatchObject({
|
||||
code: 0,
|
||||
stdout: JSON.stringify([payload]),
|
||||
stderr: "",
|
||||
});
|
||||
});
|
||||
|
||||
it.runIf(process.platform === "win32")(
|
||||
"launches an executable from a path containing spaces",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-runner-spaced-exe-");
|
||||
const executable = join(directory, "node runtime", "node.exe");
|
||||
await mkdir(join(directory, "node runtime"), { recursive: true });
|
||||
await copyFile(process.execPath, executable);
|
||||
const payload = 'argument with spaces and "quotes" & ^ % !';
|
||||
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
|
||||
expect(
|
||||
await execute(directory, executable, ["-e", code, payload]),
|
||||
).toMatchObject({
|
||||
code: 0,
|
||||
stdout: JSON.stringify([payload]),
|
||||
stderr: "",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(process.platform === "win32")(
|
||||
"resolves bare node and Windows command shims without losing arguments",
|
||||
async () => {
|
||||
const directory = await createTestTempDirectory("rea-runner-shims-");
|
||||
const payload = 'argument with spaces and "quotes" & ^ % !';
|
||||
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
|
||||
expect(
|
||||
await execute(directory, "node", ["-e", code, payload]),
|
||||
).toMatchObject({
|
||||
code: 0,
|
||||
stdout: JSON.stringify([payload]),
|
||||
stderr: "",
|
||||
});
|
||||
|
||||
const npm = await execute(directory, "npm", ["--version"]);
|
||||
expect(npm).toMatchObject({ code: 0, stderr: "" });
|
||||
expect(npm.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/u);
|
||||
|
||||
const turbo = await execute(
|
||||
directory,
|
||||
join(process.cwd(), "node_modules", ".bin", "turbo"),
|
||||
["--version"],
|
||||
);
|
||||
expect(turbo).toMatchObject({ code: 0, stderr: "" });
|
||||
expect(turbo.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/u);
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(process.platform !== "win32")(
|
||||
"recovers after abrupt owner death and keeps simultaneous contenders exclusive",
|
||||
async () => {
|
||||
@@ -219,6 +279,30 @@ function launch(directory: string, command: string) {
|
||||
return { child, ready, closed };
|
||||
}
|
||||
|
||||
function execute(
|
||||
directory: string,
|
||||
command: string,
|
||||
arguments_: string[] = [],
|
||||
) {
|
||||
return new Promise<{
|
||||
code: number | null;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}>((resolve, reject) => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[runnerPath, "test", command, ...arguments_],
|
||||
{ cwd: directory, stdio: ["ignore", "pipe", "pipe"] },
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", (chunk) => (stdout += chunk.toString()));
|
||||
child.stderr.on("data", (chunk) => (stderr += chunk.toString()));
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => resolve({ code, stdout, stderr }));
|
||||
});
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, message: string): Promise<T> {
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
return Promise.race([
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
readbackFailed: false,
|
||||
rejectRestore: false,
|
||||
rejectRemove: false,
|
||||
removeCopiedRecovery: false,
|
||||
initialCleanupFailure: undefined as unknown,
|
||||
readbackCleanupFailure: undefined as unknown,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
});
|
||||
|
||||
vi.mock("node:fs/promises", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("node:fs/promises")>();
|
||||
return {
|
||||
...original,
|
||||
rm: (
|
||||
...arguments_: Parameters<typeof original.rm>
|
||||
): ReturnType<typeof original.rm> => {
|
||||
if (state.rejectRemove && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore remove failure"));
|
||||
return original.rm(...arguments_);
|
||||
},
|
||||
writeFile: (
|
||||
...arguments_: Parameters<typeof original.writeFile>
|
||||
): ReturnType<typeof original.writeFile> => {
|
||||
if (state.rejectRestore && state.readbackFailed)
|
||||
return Promise.reject(new Error("injected restore write failure"));
|
||||
return original.writeFile(...arguments_);
|
||||
},
|
||||
copyFile: async (
|
||||
...arguments_: Parameters<typeof original.copyFile>
|
||||
): Promise<void> => {
|
||||
await original.copyFile(...arguments_);
|
||||
const destination = arguments_[1];
|
||||
if (
|
||||
state.removeCopiedRecovery &&
|
||||
typeof destination === "string" &&
|
||||
destination.endsWith(".recovery")
|
||||
)
|
||||
await original.rm(destination);
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("write-file-atomic", async (importOriginal) => {
|
||||
const original = await importOriginal<{
|
||||
default: typeof import("write-file-atomic");
|
||||
}>();
|
||||
return {
|
||||
...original,
|
||||
default: async (...arguments_: Parameters<typeof original.default>) => {
|
||||
if (state.initialCleanupFailure !== undefined)
|
||||
throw new Error("unexpected config write before initial read");
|
||||
const result = await original.default(...arguments_);
|
||||
state.readbackFailed = true;
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../src/application/RegularFileRead.js", async (importOriginal) => {
|
||||
const original =
|
||||
await importOriginal<
|
||||
typeof import("../../src/application/RegularFileRead.js")
|
||||
>();
|
||||
return {
|
||||
...original,
|
||||
readRegularFileText: (
|
||||
...arguments_: Parameters<typeof original.readRegularFileText>
|
||||
) =>
|
||||
state.initialCleanupFailure !== undefined
|
||||
? Promise.reject(state.initialCleanupFailure)
|
||||
: state.readbackFailed && state.readbackCleanupFailure !== undefined
|
||||
? Promise.reject(state.readbackCleanupFailure)
|
||||
: state.readbackFailed
|
||||
? Promise.reject(new Error("injected readback failure"))
|
||||
: original.readRegularFileText(...arguments_),
|
||||
};
|
||||
});
|
||||
|
||||
import { configureClientConfiguration } from "../../src/application/SetupClientConfiguration.js";
|
||||
import { RegularFileCleanupFailure } from "../../src/application/RegularFileRead.js";
|
||||
import { OwnedFileHandle } from "../../src/filesystem/OwnedFileHandle.js";
|
||||
import type { DoctorHost } from "../../src/application/Doctor.js";
|
||||
import { systemSetupHost } from "../../src/application/SetupHost.js";
|
||||
import { ConfigurationError } from "../../src/domain/configurationErrors.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
|
||||
const ownReadHandle = async (path: string) => {
|
||||
const owner = new OwnedFileHandle(await open(path, "r"));
|
||||
onTestFinished(() => owner.close());
|
||||
return owner;
|
||||
};
|
||||
|
||||
it("reports a failed config rollback and retains its backup path", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: `${path}.rea.backup`,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the first backup and reports a verified backup of the current original", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-stale-backup-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.rejectRestore = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRestore = false;
|
||||
|
||||
const recoveryPath = `${path}.rea.backup.${createHash("sha256")
|
||||
.update(currentOriginal, "utf8")
|
||||
.digest("hex")}.recovery`;
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: recoveryPath,
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore write failure",
|
||||
},
|
||||
});
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
expect(await readFile(recoveryPath, "utf8")).toBe(currentOriginal);
|
||||
});
|
||||
|
||||
it("does not write config when a recovery copy disappears before verification", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.removeCopiedRecovery = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-vanished-recovery-");
|
||||
const path = join(root, "client.json");
|
||||
const firstOriginal = '{"keep":"first"}\n';
|
||||
const currentOriginal = '{"keep":"current"}\n';
|
||||
await import("node:fs/promises").then(async ({ writeFile }) => {
|
||||
await writeFile(path, currentOriginal);
|
||||
await writeFile(`${path}.rea.backup`, firstOriginal);
|
||||
});
|
||||
state.removeCopiedRecovery = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.removeCopiedRecovery = false;
|
||||
|
||||
expect(result).toEqual({ status: "failed", reason: "backup" });
|
||||
expect(await readFile(path, "utf8")).toBe(currentOriginal);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(firstOriginal);
|
||||
});
|
||||
|
||||
it("does not roll back or remove config when its initial read cleanup fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-initial-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const failure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
await ownReadHandle(path),
|
||||
{ kind: "completed", value: original },
|
||||
new Error("injected initial close failure"),
|
||||
);
|
||||
state.initialCleanupFailure = failure;
|
||||
|
||||
await expect(
|
||||
configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
),
|
||||
).rejects.toBe(failure);
|
||||
expect(await readFile(path, "utf8")).toBe(original);
|
||||
});
|
||||
|
||||
it("reports first-run rollback removal failure without a backup", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
state.readbackCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-first-run-rollback-");
|
||||
const path = join(root, "client.json");
|
||||
state.rejectRemove = true;
|
||||
|
||||
const result = await configureClientConfiguration(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
state.rejectRemove = false;
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path,
|
||||
detail: "injected restore remove failure",
|
||||
},
|
||||
});
|
||||
expect(result).not.toHaveProperty("backupPath");
|
||||
expect(JSON.parse(await readFile(path, "utf8"))).toMatchObject({
|
||||
mcpServers: { rea: { command: "rea", args: ["mcp"] } },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains readback cleanup ownership when rollback also fails", async () => {
|
||||
state.readbackFailed = false;
|
||||
state.rejectRestore = false;
|
||||
state.rejectRemove = false;
|
||||
state.initialCleanupFailure = undefined;
|
||||
const root = await createTestTempDirectory("rea-config-readback-cleanup-");
|
||||
const path = join(root, "client.json");
|
||||
const original = '{"keep":true}\n';
|
||||
await import("node:fs/promises").then(({ writeFile }) =>
|
||||
writeFile(path, original),
|
||||
);
|
||||
const owner = await ownReadHandle(path);
|
||||
const cleanupFailure = new RegularFileCleanupFailure(
|
||||
path,
|
||||
owner,
|
||||
{ kind: "completed", value: "" },
|
||||
new Error("injected readback close failure"),
|
||||
);
|
||||
state.readbackCleanupFailure = cleanupFailure;
|
||||
state.rejectRestore = true;
|
||||
|
||||
const host = systemSetupHost(
|
||||
{ platform: "linux", homeDirectory: root } as DoctorHost,
|
||||
{ HOME: root },
|
||||
);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await host.configureClient(
|
||||
{ name: "cursor", configPath: path, format: "json" },
|
||||
{},
|
||||
["rea", "mcp"],
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
caught = cause;
|
||||
} finally {
|
||||
await host.close?.();
|
||||
}
|
||||
|
||||
if (!(caught instanceof ConfigurationError)) throw caught;
|
||||
expect(caught.message).toContain("injected restore write failure");
|
||||
expect(caught.message).toContain(`${path}.rea.backup`);
|
||||
const cleanupOwnerError = caught.cause;
|
||||
if (!(cleanupOwnerError instanceof RegularFileCleanupFailure))
|
||||
throw new Error("Configuration failure lost its read owner");
|
||||
expect(cleanupOwnerError).toMatchObject({
|
||||
path,
|
||||
outcome: { kind: "completed", value: "" },
|
||||
cleanupCause: expect.any(AggregateError),
|
||||
});
|
||||
expect(cleanupOwnerError.owner).toBe(owner);
|
||||
expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original);
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { mkdir, readFile, rm, writeFile, access } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { delimiter, dirname, join, relative, resolve } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { err, ok } from "../../src/domain/result.js";
|
||||
import { runUpdate, type UpdateResult } from "../../src/application/Update.js";
|
||||
import { PRODUCT_IDENTITY } from "../../src/identity.js";
|
||||
import { supportedClients } from "../../src/application/SupportedClients.js";
|
||||
import {
|
||||
@@ -125,6 +126,41 @@ describe("OMP integration maintenance", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("maintenance activation and layered configuration", () => {
|
||||
it("leaves a natively disabled ZCode registration outside maintenance", async () => {
|
||||
const configPath = await writeClient(
|
||||
"zcode",
|
||||
JSON.stringify({
|
||||
mcp: {
|
||||
servers: {
|
||||
rea: { command: entryPoint, args: ["mcp"], enable: false },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const original = await readFile(configPath, "utf8");
|
||||
await expect(
|
||||
existingMaintenanceScope(home, entryPoint, process.env),
|
||||
).resolves.toMatchObject({ clients: [] });
|
||||
expect(await readFile(configPath, "utf8")).toBe(original);
|
||||
});
|
||||
|
||||
it("selects an enabled registration inherited through layered OpenCode files", async () => {
|
||||
const directory = join(home, ".config", "opencode");
|
||||
await mkdir(directory, { recursive: true });
|
||||
await writeFile(
|
||||
join(directory, "opencode.json"),
|
||||
JSON.stringify({
|
||||
mcp: { rea: { type: "local", command: [entryPoint, "mcp"] } },
|
||||
}),
|
||||
);
|
||||
await writeClient("opencode", JSON.stringify({ theme: "user-selected" }));
|
||||
await expect(
|
||||
existingMaintenanceScope(home, entryPoint, process.env),
|
||||
).resolves.toMatchObject({ clients: ["opencode"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("existing REA integration maintenance", () => {
|
||||
it("selects owned registrations while preserving unconfigured, foreign, and disabled choices", async () => {
|
||||
await writeClient("codex", staleCodex);
|
||||
@@ -383,9 +419,157 @@ describe("update subprocess boundaries", () => {
|
||||
await writeFile(script, 'process.stdout.write("3.3.0\\n")');
|
||||
await expect(
|
||||
systemUpdateHost(packageRoot, home).installedVersion({
|
||||
manager: "npm",
|
||||
prefix: home,
|
||||
packageRoot,
|
||||
}),
|
||||
).resolves.toEqual(ok("3.3.0"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Bun global installation update", () => {
|
||||
it.each([
|
||||
["1.4.2", "updated", "absolute"],
|
||||
["1.2.17", "updated", "absolute"],
|
||||
["1.2.17", "updated", "relative"],
|
||||
["1.2.14", "failed", "absolute"],
|
||||
["1.2.17-canary.1", "failed", "absolute"],
|
||||
["unknown", "failed", "absolute"],
|
||||
])(
|
||||
"handles Bun %s with outcome %s using %s global-directory configuration",
|
||||
async (bunVersion, status, directoryMode) => {
|
||||
// A recording `bun` on PATH crosses the real subprocess boundary without registry access.
|
||||
const root = await createTestTempDirectory("rea-update-bun-");
|
||||
const globalDirectory = join(root, "bun", "install", "global");
|
||||
const packageRoot = join(
|
||||
globalDirectory,
|
||||
"node_modules",
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
);
|
||||
const versionPath = join(root, "installed-version");
|
||||
const logPath = join(root, "bun-invocations.jsonl");
|
||||
await mkdir(join(packageRoot, "scripts"), { recursive: true });
|
||||
await writeFile(
|
||||
join(globalDirectory, "package.json"),
|
||||
'{"dependencies":{"rea-agents":"3.2.1"}}\n',
|
||||
);
|
||||
await writeFile(versionPath, "3.2.1");
|
||||
await writeFile(
|
||||
join(packageRoot, "scripts", "rea.mjs"),
|
||||
`import { readFileSync } from "node:fs";\nprocess.stdout.write(readFileSync(${JSON.stringify(versionPath)}, "utf8") + "\\n");\n`,
|
||||
);
|
||||
const binDirectory = join(root, "bin");
|
||||
const recorder = join(binDirectory, "record-bun.mjs");
|
||||
await mkdir(binDirectory);
|
||||
await writeFile(
|
||||
recorder,
|
||||
[
|
||||
'import { appendFileSync, writeFileSync } from "node:fs";',
|
||||
"const args = process.argv.slice(2);",
|
||||
`appendFileSync(${JSON.stringify(logPath)}, JSON.stringify({ args, cwd: process.cwd(), globalDirectory: process.env.BUN_INSTALL_GLOBAL_DIR }) + "\\n");`,
|
||||
`if (JSON.stringify(args) === '["--version"]') console.log(${JSON.stringify(bunVersion)});`,
|
||||
`else if (JSON.stringify(args) === ${JSON.stringify(JSON.stringify(["info", PRODUCT_IDENTITY.packageName, "dist-tags.latest", "--json"]))}) process.stdout.write('"3.3.0"\\n');`,
|
||||
`else if (JSON.stringify(args) === ${JSON.stringify(JSON.stringify(["add", "--global", "--ignore-scripts", `${PRODUCT_IDENTITY.packageName}@3.3.0`]))}) writeFileSync(${JSON.stringify(versionPath)}, "3.3.0");`,
|
||||
"else process.exitCode = 2;",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
if (process.platform === "win32") {
|
||||
await writeFile(
|
||||
join(binDirectory, "bun.cmd"),
|
||||
`@"${process.execPath}" "${recorder}" %*\r\n`,
|
||||
);
|
||||
} else {
|
||||
await writeFile(
|
||||
join(binDirectory, "bun"),
|
||||
`#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(recorder)} "$@"\n`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
}
|
||||
const pathKey =
|
||||
Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") ??
|
||||
"PATH";
|
||||
const environment: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
[pathKey]: `${binDirectory}${delimiter}${process.env[pathKey] ?? ""}`,
|
||||
BUN_INSTALL: join(root, "bun"),
|
||||
};
|
||||
delete environment.BUN_INSTALL_GLOBAL_DIR;
|
||||
if (directoryMode === "relative")
|
||||
environment.BUN_INSTALL_GLOBAL_DIR = relative(root, globalDirectory);
|
||||
|
||||
const callerDirectory = process.cwd();
|
||||
let result: UpdateResult;
|
||||
try {
|
||||
process.chdir(root);
|
||||
result = await runUpdate(
|
||||
"3.2.1",
|
||||
systemUpdateHost(packageRoot, home, environment),
|
||||
"structured",
|
||||
);
|
||||
} finally {
|
||||
process.chdir(callerDirectory);
|
||||
}
|
||||
|
||||
const invocations = (await readFile(logPath, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line): unknown => JSON.parse(line));
|
||||
const versionInvocation = {
|
||||
args: ["--version"],
|
||||
cwd: globalDirectory,
|
||||
globalDirectory,
|
||||
};
|
||||
if (status === "failed") {
|
||||
expect(result).toEqual({
|
||||
status: "failed",
|
||||
currentVersion: "3.2.1",
|
||||
latestVersion: null,
|
||||
reason: "version-check",
|
||||
remediation: `REA updates for Bun global installations require Bun 1.2.17 or later; bun --version returned ${JSON.stringify(bunVersion)}. Upgrade Bun manually, then rerun rea update.`,
|
||||
});
|
||||
expect(invocations).toEqual([versionInvocation]);
|
||||
expect(await readFile(versionPath, "utf8")).toBe("3.2.1");
|
||||
return;
|
||||
}
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "updated",
|
||||
installMethod: "bun",
|
||||
installedVersion: "3.3.0",
|
||||
command: [
|
||||
"bun",
|
||||
"add",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
`${PRODUCT_IDENTITY.packageName}@3.3.0`,
|
||||
],
|
||||
});
|
||||
// `bun info` needs a project in its working directory, and the caller's
|
||||
// directory must never be selected, so all commands run in the owner.
|
||||
expect(invocations).toEqual([
|
||||
versionInvocation,
|
||||
{
|
||||
args: [
|
||||
"info",
|
||||
PRODUCT_IDENTITY.packageName,
|
||||
"dist-tags.latest",
|
||||
"--json",
|
||||
],
|
||||
cwd: globalDirectory,
|
||||
globalDirectory,
|
||||
},
|
||||
{
|
||||
args: [
|
||||
"add",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
`${PRODUCT_IDENTITY.packageName}@3.3.0`,
|
||||
],
|
||||
cwd: globalDirectory,
|
||||
globalDirectory,
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { WindowsPrivateRuntime } from "../../src/windows/WindowsPrivateRuntime.js";
|
||||
import { PrivateRuntimeRootUnavailableError } from "../../src/process/PrivateRuntimeRootUnavailableError.js";
|
||||
|
||||
const { nativeCall } = vi.hoisted(() => ({ nativeCall: vi.fn() }));
|
||||
vi.mock("../../src/windows/WindowsNativeLoader.js", async (original) => ({
|
||||
...(await original<
|
||||
typeof import("../../src/windows/WindowsNativeLoader.js")
|
||||
>()),
|
||||
requireWindowsNativeAuthority: () => ({ call: nativeCall }),
|
||||
}));
|
||||
beforeEach(() => {
|
||||
nativeCall.mockReset();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "sharing conflict before allocation",
|
||||
win32Code: 32,
|
||||
runtimeAllocation: "not-started",
|
||||
retryable: true,
|
||||
},
|
||||
{
|
||||
label: "lock conflict before allocation",
|
||||
win32Code: 33,
|
||||
runtimeAllocation: "not-started",
|
||||
retryable: true,
|
||||
},
|
||||
{ label: "unknown allocation", win32Code: 32, retryable: false },
|
||||
{
|
||||
label: "possible allocation",
|
||||
win32Code: 32,
|
||||
runtimeAllocation: "started",
|
||||
retryable: false,
|
||||
},
|
||||
{
|
||||
label: "permission failure",
|
||||
win32Code: 5,
|
||||
runtimeAllocation: "not-started",
|
||||
retryable: false,
|
||||
},
|
||||
{
|
||||
label: "string code",
|
||||
win32Code: "32",
|
||||
runtimeAllocation: "not-started",
|
||||
retryable: false,
|
||||
},
|
||||
{
|
||||
label: "inconsistent error code",
|
||||
win32Code: 32,
|
||||
code: "EACCES",
|
||||
runtimeAllocation: "not-started",
|
||||
retryable: false,
|
||||
},
|
||||
])(
|
||||
"retains $label without guessing runtime ownership",
|
||||
({ retryable, label: _label, ...facts }) => {
|
||||
const cause = Object.assign(new Error("Selected native diagnostic"), {
|
||||
code: "ERR_REA_WINDOWS_NATIVE",
|
||||
...facts,
|
||||
});
|
||||
nativeCall.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
let observed: unknown;
|
||||
try {
|
||||
WindowsPrivateRuntime.create("D:/selected parent", "selected-prefix-");
|
||||
} catch (failure: unknown) {
|
||||
observed = failure;
|
||||
}
|
||||
expect(nativeCall).toHaveBeenCalledTimes(1);
|
||||
expect(nativeCall).toHaveBeenCalledWith("runtime_create", [
|
||||
"D:/selected parent",
|
||||
"selected-prefix-",
|
||||
]);
|
||||
if (retryable) {
|
||||
expect(observed).toBeInstanceOf(PrivateRuntimeRootUnavailableError);
|
||||
expect(observed).toMatchObject({
|
||||
message: cause.message,
|
||||
cause,
|
||||
retryable: true,
|
||||
});
|
||||
} else expect(observed).toBe(cause);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not infer a transient status from a human-readable diagnostic", () => {
|
||||
const cause = new Error("Open Windows path component failed (Win32 32)");
|
||||
nativeCall.mockImplementation(() => {
|
||||
throw cause;
|
||||
});
|
||||
let observed: unknown;
|
||||
try {
|
||||
WindowsPrivateRuntime.create("D:/selected parent", "selected-prefix-");
|
||||
} catch (failure: unknown) {
|
||||
observed = failure;
|
||||
}
|
||||
expect(observed).toBe(cause);
|
||||
});
|
||||
Reference in New Issue
Block a user