feat(application): add isolated JavaScript replay
Expose one plan/execute replay contract through both CLI and MCP with exact source, input, runtime, sandbox, limit, and export commitments. Run selected ESM and extracted CommonJS/Rspack factories in a disposable Linux x64 Bubblewrap namespace with a content-addressed Node ELF closure, architecture-checked seccomp, delegated systemd cgroup limits, bounded protocol capture, cancellation, and observable cleanup. Preserve left and right observations as Evidence, derive differential comparisons without erasing unknowns, add optional separately authorized reproducers, and fail closed on stale plans or unavailable host boundaries. Add source-owned parser, sanitizer, clipboard, denial, timeout, OOM, protocol-forgery, and cancellation coverage; a real Linux verifier and workflow; regenerated catalogs and TypeDoc; and updated the packaged REA analysis skill for the 83-tool inventory.
This commit is contained in:
@@ -0,0 +1,427 @@
|
||||
import {
|
||||
Script,
|
||||
SourceTextModule,
|
||||
SyntheticModule,
|
||||
createContext,
|
||||
type Module,
|
||||
} from "node:vm";
|
||||
import { types } from "node:util";
|
||||
|
||||
interface WorkerModule {
|
||||
readonly alias: string;
|
||||
readonly format: "esm" | "commonjs-factory";
|
||||
readonly dependencies: Readonly<Record<string, string>>;
|
||||
readonly source: string;
|
||||
}
|
||||
|
||||
interface WorkerSide {
|
||||
readonly modules: readonly WorkerModule[];
|
||||
readonly entryAlias: string;
|
||||
readonly entryExport: string;
|
||||
}
|
||||
|
||||
interface WorkerRequest {
|
||||
readonly schemaVersion: 1;
|
||||
readonly left: WorkerSide;
|
||||
readonly right?: WorkerSide;
|
||||
readonly cases: readonly {
|
||||
readonly caseId: string;
|
||||
readonly arguments: readonly unknown[];
|
||||
readonly inputSha256: string;
|
||||
}[];
|
||||
readonly determinism: {
|
||||
readonly clockIso: string;
|
||||
readonly randomSeed: number;
|
||||
};
|
||||
readonly limits: {
|
||||
readonly resultDepth: number;
|
||||
readonly resultNodes: number;
|
||||
readonly exceptionBytes: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface WorkerOutcome {
|
||||
readonly case_id: string;
|
||||
readonly outcome: "return" | "exception" | "serialization_error" | "denied";
|
||||
readonly value?: unknown;
|
||||
readonly exception?: {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
};
|
||||
readonly input_sha256: string;
|
||||
readonly output_sha256: null;
|
||||
readonly truncated: false;
|
||||
}
|
||||
|
||||
class ReplayDeniedError extends Error {
|
||||
override readonly name = "ReplayDeniedError";
|
||||
}
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
||||
const request = JSON.parse(
|
||||
Buffer.concat(chunks).toString("utf8"),
|
||||
) as WorkerRequest;
|
||||
if (request.schemaVersion !== 1)
|
||||
throw new TypeError("Unsupported replay worker protocol");
|
||||
const left: WorkerOutcome[] = [];
|
||||
const right: WorkerOutcome[] = [];
|
||||
for (let index = 0; index < request.cases.length; index += 1) {
|
||||
const replayCase = request.cases[index];
|
||||
if (replayCase === undefined) continue;
|
||||
left.push(await runCase(request.left, replayCase, request, index));
|
||||
if (request.right !== undefined)
|
||||
right.push(await runCase(request.right, replayCase, request, index));
|
||||
}
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
schema_version: 1,
|
||||
left,
|
||||
...(request.right === undefined ? {} : { right }),
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const runCase = async (
|
||||
side: WorkerSide,
|
||||
replayCase: WorkerRequest["cases"][number],
|
||||
request: WorkerRequest,
|
||||
index: number,
|
||||
): Promise<WorkerOutcome> => {
|
||||
try {
|
||||
const loaded = await loadEntry(side, request, index);
|
||||
if (typeof loaded !== "function")
|
||||
throw new TypeError(`Replay export is not callable: ${side.entryExport}`);
|
||||
const returned = await Reflect.apply(loaded, undefined, [
|
||||
...replayCase.arguments,
|
||||
]);
|
||||
try {
|
||||
return {
|
||||
case_id: replayCase.caseId,
|
||||
outcome: "return",
|
||||
value: projectValue(
|
||||
returned,
|
||||
request.limits.resultDepth,
|
||||
request.limits.resultNodes,
|
||||
),
|
||||
input_sha256: replayCase.inputSha256,
|
||||
output_sha256: null,
|
||||
truncated: false,
|
||||
};
|
||||
} catch (error: unknown) {
|
||||
return exceptionOutcome(
|
||||
replayCase,
|
||||
"serialization_error",
|
||||
error,
|
||||
request.limits.exceptionBytes,
|
||||
);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
return exceptionOutcome(
|
||||
replayCase,
|
||||
error instanceof ReplayDeniedError ? "denied" : "exception",
|
||||
error,
|
||||
request.limits.exceptionBytes,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const loadEntry = async (
|
||||
side: WorkerSide,
|
||||
request: WorkerRequest,
|
||||
caseIndex: number,
|
||||
): Promise<unknown> => {
|
||||
const modules = new Map(side.modules.map((module) => [module.alias, module]));
|
||||
const context = deterministicContext(request, caseIndex);
|
||||
const esmCache = new Map<string, Module>();
|
||||
const commonJsCache = new Map<string, Record<string, unknown>>();
|
||||
|
||||
const loadCommonJs = (alias: string): Record<string, unknown> => {
|
||||
const cached = commonJsCache.get(alias);
|
||||
if (cached !== undefined) return cached;
|
||||
const descriptor = requiredModule(modules, alias);
|
||||
if (descriptor.format !== "commonjs-factory")
|
||||
throw new TypeError(
|
||||
`Synchronous require cannot load ESM module: ${alias}`,
|
||||
);
|
||||
const module = { exports: {} as Record<string, unknown> };
|
||||
commonJsCache.set(alias, module.exports);
|
||||
const requireModule = ((specifier: string): Record<string, unknown> => {
|
||||
const dependency = descriptor.dependencies[specifier];
|
||||
if (dependency === undefined)
|
||||
throw new ReplayDeniedError(`Undeclared require: ${specifier}`);
|
||||
return loadCommonJs(dependency);
|
||||
}) as ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>;
|
||||
installRspackHelpers(requireModule);
|
||||
const source = normalizeFactorySource(descriptor.source);
|
||||
const factory = new Script(`(${source})`, {
|
||||
filename: `/modules/${alias}.js`,
|
||||
}).runInContext(context) as (
|
||||
module: { exports: Record<string, unknown> },
|
||||
exports: Record<string, unknown>,
|
||||
require_: typeof requireModule,
|
||||
) => void;
|
||||
factory(module, module.exports, requireModule);
|
||||
commonJsCache.set(alias, module.exports);
|
||||
return module.exports;
|
||||
};
|
||||
|
||||
const loadEsm = async (alias: string): Promise<Module> => {
|
||||
const cached = esmCache.get(alias);
|
||||
if (cached !== undefined) return cached;
|
||||
const descriptor = requiredModule(modules, alias);
|
||||
let module: Module;
|
||||
if (descriptor.format === "commonjs-factory") {
|
||||
const exports = loadCommonJs(alias);
|
||||
const names = [...new Set(["default", ...Object.keys(exports)])];
|
||||
module = new SyntheticModule(
|
||||
names,
|
||||
function () {
|
||||
this.setExport("default", exports);
|
||||
for (const name of Object.keys(exports))
|
||||
this.setExport(name, exports[name]);
|
||||
},
|
||||
{ context, identifier: `rea:${alias}` },
|
||||
);
|
||||
} else {
|
||||
module = new SourceTextModule(descriptor.source, {
|
||||
context,
|
||||
identifier: `rea:${alias}`,
|
||||
initializeImportMeta: (meta) => {
|
||||
meta.url = `rea:${alias}`;
|
||||
},
|
||||
importModuleDynamically: () => {
|
||||
throw new ReplayDeniedError(
|
||||
"Dynamic import is unavailable in controlled replay",
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
esmCache.set(alias, module);
|
||||
await module.link(async (specifier) => {
|
||||
const dependency = descriptor.dependencies[specifier];
|
||||
if (dependency === undefined)
|
||||
throw new ReplayDeniedError(`Undeclared import: ${specifier}`);
|
||||
return loadEsm(dependency);
|
||||
});
|
||||
await module.evaluate();
|
||||
return module;
|
||||
};
|
||||
|
||||
const entry = requiredModule(modules, side.entryAlias);
|
||||
if (entry.format === "commonjs-factory") {
|
||||
const exported = loadCommonJs(side.entryAlias);
|
||||
return side.entryExport === "default"
|
||||
? (exported.default ?? exported)
|
||||
: exported[side.entryExport];
|
||||
}
|
||||
const namespace = (await loadEsm(side.entryAlias)).namespace;
|
||||
return (namespace as Record<string, unknown>)[side.entryExport];
|
||||
};
|
||||
|
||||
const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
|
||||
let state = (request.determinism.randomSeed + caseIndex) >>> 0;
|
||||
const random = (): number => {
|
||||
state ^= state << 13;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5;
|
||||
return (state >>> 0) / 0x1_0000_0000;
|
||||
};
|
||||
const epoch = Date.parse(request.determinism.clockIso);
|
||||
class ReplayDate extends Date {
|
||||
constructor(...arguments_: [] | [string | number]) {
|
||||
super(arguments_.length === 0 ? epoch : arguments_[0]);
|
||||
}
|
||||
static override now(): number {
|
||||
return epoch;
|
||||
}
|
||||
}
|
||||
const replayMath = Object.create(Math) as Math;
|
||||
Object.defineProperty(replayMath, "random", { value: random });
|
||||
return createContext(
|
||||
{ Date: ReplayDate, Math: replayMath },
|
||||
{
|
||||
name: "rea-controlled-replay",
|
||||
codeGeneration: { strings: false, wasm: false },
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const installRspackHelpers = (
|
||||
require_: ((specifier: string) => Record<string, unknown>) &
|
||||
Record<string, unknown>,
|
||||
): void => {
|
||||
require_.d = (
|
||||
exports: Record<string, unknown>,
|
||||
definitions: Record<string, () => unknown>,
|
||||
) => {
|
||||
for (const [name, getter] of Object.entries(definitions))
|
||||
if (!Object.prototype.hasOwnProperty.call(exports, name))
|
||||
Object.defineProperty(exports, name, { enumerable: true, get: getter });
|
||||
};
|
||||
require_.r = (exports: Record<string, unknown>) => {
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
||||
};
|
||||
require_.n = (module: Record<string, unknown>) => {
|
||||
const getter = () => (module.__esModule === true ? module.default : module);
|
||||
Object.defineProperty(getter, "a", { get: getter });
|
||||
return getter;
|
||||
};
|
||||
require_.nmd = (module: Record<string, unknown>) => module;
|
||||
};
|
||||
|
||||
const requiredModule = (
|
||||
modules: ReadonlyMap<string, WorkerModule>,
|
||||
alias: string,
|
||||
): WorkerModule => {
|
||||
const module = modules.get(alias);
|
||||
if (module === undefined)
|
||||
throw new TypeError(`Undeclared module alias: ${alias}`);
|
||||
return module;
|
||||
};
|
||||
|
||||
const normalizeFactorySource = (source: string): string =>
|
||||
/^\s*\d+\s*\(/u.test(source)
|
||||
? source.replace(/^\s*\d+\s*\(/u, "function(")
|
||||
: source;
|
||||
|
||||
const projectValue = (
|
||||
value: unknown,
|
||||
maximumDepth: number,
|
||||
maximumNodes: number,
|
||||
): unknown => {
|
||||
let nodes = 0;
|
||||
const visit = (
|
||||
candidate: unknown,
|
||||
depth: number,
|
||||
ancestors: Set<object>,
|
||||
): unknown => {
|
||||
nodes += 1;
|
||||
if (nodes > maximumNodes || depth > maximumDepth)
|
||||
throw new RangeError("Replay result projection limit exceeded");
|
||||
if (
|
||||
candidate === null ||
|
||||
typeof candidate === "string" ||
|
||||
typeof candidate === "boolean"
|
||||
)
|
||||
return candidate;
|
||||
if (typeof candidate === "number") {
|
||||
if (!Number.isFinite(candidate))
|
||||
throw new TypeError("Non-finite replay result number");
|
||||
return candidate;
|
||||
}
|
||||
if (typeof candidate !== "object")
|
||||
throw new TypeError(
|
||||
`Unsupported replay result type: ${typeof candidate}`,
|
||||
);
|
||||
if (types.isProxy(candidate))
|
||||
throw new TypeError("Proxy replay results are unavailable");
|
||||
if (ancestors.has(candidate)) throw new TypeError("Cyclic replay result");
|
||||
ancestors.add(candidate);
|
||||
try {
|
||||
const descriptors = Object.getOwnPropertyDescriptors(candidate);
|
||||
const output: unknown[] | Record<string, unknown> = Array.isArray(
|
||||
candidate,
|
||||
)
|
||||
? []
|
||||
: {};
|
||||
if (!Array.isArray(candidate)) {
|
||||
const prototype = Object.getPrototypeOf(candidate) as object | null;
|
||||
if (prototype !== null && Object.getPrototypeOf(prototype) !== null)
|
||||
throw new TypeError("Unsupported replay result prototype");
|
||||
}
|
||||
for (const [key, descriptor] of Object.entries(descriptors)) {
|
||||
if (key === "length" && Array.isArray(candidate)) continue;
|
||||
if (!("value" in descriptor))
|
||||
throw new TypeError("Replay result accessors are unavailable");
|
||||
if (Array.isArray(output)) {
|
||||
if (!/^\d+$/u.test(key))
|
||||
throw new TypeError(
|
||||
"Replay arrays may only contain indexed values",
|
||||
);
|
||||
output[Number(key)] = visit(descriptor.value, depth + 1, ancestors);
|
||||
} else output[key] = visit(descriptor.value, depth + 1, ancestors);
|
||||
}
|
||||
return output;
|
||||
} finally {
|
||||
ancestors.delete(candidate);
|
||||
}
|
||||
};
|
||||
return visit(value, 0, new Set());
|
||||
};
|
||||
|
||||
const exceptionOutcome = (
|
||||
replayCase: WorkerRequest["cases"][number],
|
||||
outcome: "exception" | "serialization_error" | "denied",
|
||||
error: unknown,
|
||||
maximumBytes: number,
|
||||
): WorkerOutcome => {
|
||||
const details = exceptionDetails(error);
|
||||
const name = bounded(details.name, maximumBytes);
|
||||
const message = bounded(details.message, maximumBytes);
|
||||
const stack =
|
||||
details.stack === null ? null : bounded(details.stack, maximumBytes);
|
||||
return {
|
||||
case_id: replayCase.caseId,
|
||||
outcome,
|
||||
exception: { name, message, stack },
|
||||
input_sha256: replayCase.inputSha256,
|
||||
output_sha256: null,
|
||||
truncated: false,
|
||||
};
|
||||
};
|
||||
|
||||
const exceptionDetails = (
|
||||
error: unknown,
|
||||
): {
|
||||
readonly name: string;
|
||||
readonly message: string;
|
||||
readonly stack: string | null;
|
||||
} => {
|
||||
if (typeof error !== "object" || error === null)
|
||||
return { name: "Error", message: "Unknown replay exception", stack: null };
|
||||
if (types.isProxy(error))
|
||||
return { name: "Error", message: "Proxy replay exception", stack: null };
|
||||
const own = Object.getOwnPropertyDescriptors(error);
|
||||
const prototype = Object.getPrototypeOf(error) as object | null;
|
||||
const inherited =
|
||||
prototype === null ? {} : Object.getOwnPropertyDescriptors(prototype);
|
||||
const stringValue = (
|
||||
descriptor: PropertyDescriptor | undefined,
|
||||
): string | null =>
|
||||
descriptor !== undefined &&
|
||||
"value" in descriptor &&
|
||||
typeof descriptor.value === "string"
|
||||
? descriptor.value
|
||||
: null;
|
||||
return {
|
||||
name: stringValue(own.name) ?? stringValue(inherited.name) ?? "Error",
|
||||
message: stringValue(own.message) ?? "Unknown replay exception",
|
||||
stack: stringValue(own.stack),
|
||||
};
|
||||
};
|
||||
|
||||
const bounded = (value: string, maximumBytes: number): string => {
|
||||
const bytes = Buffer.from(value);
|
||||
if (bytes.byteLength <= maximumBytes) return value;
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
for (let end = maximumBytes; end >= Math.max(0, maximumBytes - 3); end -= 1) {
|
||||
try {
|
||||
return decoder.decode(bytes.subarray(0, end));
|
||||
} catch {
|
||||
/* try the preceding UTF-8 boundary */
|
||||
}
|
||||
}
|
||||
return "";
|
||||
};
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
const message =
|
||||
error instanceof Error ? error.message : "Replay worker failed";
|
||||
process.stderr.write(message.slice(0, 4096));
|
||||
process.exitCode = 70;
|
||||
});
|
||||
@@ -0,0 +1,580 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { open, readFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayPolicy,
|
||||
JavaScriptReplayRunner,
|
||||
PreparedReplayPlan,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
digestBytes,
|
||||
digestJson,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import type { ReplayExecutionResult } from "../domain/javascriptReplay.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
import {
|
||||
parseReplayWorkerResponse,
|
||||
type WorkerProtocolOutcome,
|
||||
type WorkerProtocolResponse,
|
||||
} from "./ReplayWorkerProtocol.js";
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
/** Run one prepared experiment under the exact Linux ADR-0002 boundary. */
|
||||
export class LinuxJavaScriptReplayRunner implements JavaScriptReplayRunner {
|
||||
async execute(
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ReplayExecutionResult> {
|
||||
if (isAborted(signal))
|
||||
return terminationResult(prepared, "", "cancelled", {
|
||||
state: "complete",
|
||||
residual_resources: [],
|
||||
});
|
||||
const unit = `rea-replay-${randomBytes(8).toString("hex")}.service`;
|
||||
const workerPath = prepared.publicPlan.runtime.worker.path;
|
||||
const closure = await resolveLinuxRuntimeClosure(policy.nodePath);
|
||||
assertRuntimeCommitment(prepared, closure);
|
||||
if (
|
||||
digestBytes(await readFile(workerPath)) !==
|
||||
prepared.publicPlan.runtime.worker.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker changed after approval");
|
||||
if (
|
||||
linuxX64ReplaySeccompDigest() !==
|
||||
prepared.publicPlan.sandbox.seccomp_sha256
|
||||
)
|
||||
throw new TypeError("Replay seccomp policy changed after approval");
|
||||
const request = workerRequest(prepared);
|
||||
const encoded = Buffer.from(JSON.stringify(request));
|
||||
if (encoded.byteLength > prepared.publicPlan.limits.protocol_bytes)
|
||||
throw new RangeError(
|
||||
"Replay worker protocol input exceeds the committed limit",
|
||||
);
|
||||
const filter = await temporaryFilterHandle();
|
||||
const arguments_ = systemdArguments(
|
||||
unit,
|
||||
policy,
|
||||
prepared,
|
||||
workerPath,
|
||||
closure,
|
||||
filter.path,
|
||||
);
|
||||
let child: ReturnType<typeof spawn> | undefined;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
let cancelled = false;
|
||||
let timedOut = false;
|
||||
let terminationRequest: Promise<void> | undefined;
|
||||
const requestTermination = (): void => {
|
||||
terminationRequest ??= killUnit(policy.systemctlPath, unit);
|
||||
child?.kill("SIGKILL");
|
||||
};
|
||||
const terminate = (): void => {
|
||||
cancelled = true;
|
||||
requestTermination();
|
||||
};
|
||||
try {
|
||||
const completion = new Promise<CollectedProcess>((resolve, reject) => {
|
||||
child = spawn(policy.systemdRunPath, arguments_, {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
PATH: "/usr/bin:/bin",
|
||||
LANG: "C",
|
||||
LC_ALL: "C",
|
||||
TZ: "UTC",
|
||||
...(process.env.XDG_RUNTIME_DIR === undefined
|
||||
? {}
|
||||
: { XDG_RUNTIME_DIR: process.env.XDG_RUNTIME_DIR }),
|
||||
...(process.env.DBUS_SESSION_BUS_ADDRESS === undefined
|
||||
? {}
|
||||
: {
|
||||
DBUS_SESSION_BUS_ADDRESS:
|
||||
process.env.DBUS_SESSION_BUS_ADDRESS,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const output = boundedCollector(
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
);
|
||||
const diagnostics = boundedCollector(
|
||||
prepared.publicPlan.limits.stderr_bytes,
|
||||
);
|
||||
child.stdout?.on("data", output.append);
|
||||
child.stderr?.on("data", diagnostics.append);
|
||||
child.once("error", reject);
|
||||
child.once("close", (code, signalName) =>
|
||||
resolve({
|
||||
code,
|
||||
signal: signalName,
|
||||
stdout: output.value(),
|
||||
stderr: diagnostics.value(),
|
||||
outputExceeded: output.exceeded(),
|
||||
}),
|
||||
);
|
||||
child.stdin?.end(encoded);
|
||||
});
|
||||
signal?.addEventListener("abort", terminate, { once: true });
|
||||
if (isAborted(signal)) terminate();
|
||||
timeout = setTimeout(() => {
|
||||
timedOut = true;
|
||||
requestTermination();
|
||||
}, prepared.publicPlan.limits.wall_time_ms);
|
||||
timeout.unref();
|
||||
const collected = await completion;
|
||||
if (terminationRequest !== undefined) await terminationRequest;
|
||||
const unitResult = await observeUnitResult(policy.systemctlPath, unit);
|
||||
const cleanup = await observeCleanup(policy.systemctlPath, unit);
|
||||
if (cancelled || timedOut)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
cancelled ? "cancelled" : "timeout",
|
||||
cleanup,
|
||||
);
|
||||
if (collected.outputExceeded)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
"Worker stdout exceeded the committed bound",
|
||||
);
|
||||
if (collected.code !== 0)
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
collected.code === 137 || unitResult === "oom-kill" ? "oom" : "crash",
|
||||
cleanup,
|
||||
);
|
||||
let response: WorkerProtocolResponse;
|
||||
try {
|
||||
response = parseReplayWorkerResponse(
|
||||
JSON.parse(collected.stdout),
|
||||
prepared.publicPlan.cases,
|
||||
prepared.publicPlan.right !== undefined,
|
||||
);
|
||||
} catch {
|
||||
return terminationResult(
|
||||
prepared,
|
||||
collected.stderr,
|
||||
"protocol_error",
|
||||
cleanup,
|
||||
);
|
||||
}
|
||||
const outcomes = commitOutcomes(response.left);
|
||||
const right =
|
||||
response.right === undefined
|
||||
? undefined
|
||||
: commitOutcomes(response.right);
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(right ?? [])],
|
||||
...(right === undefined
|
||||
? {}
|
||||
: { comparison: compareOutcomes(outcomes, right) }),
|
||||
stderr: collected.stderr,
|
||||
termination: "completed",
|
||||
cleanup,
|
||||
limitations: [
|
||||
"Controlled replay observes the isolated extracted modules, not the original application runtime.",
|
||||
"Network and host filesystem access were unavailable; unsupported dependencies may change behavior.",
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", terminate);
|
||||
if (timeout !== undefined) clearTimeout(timeout);
|
||||
if (child !== undefined && child.exitCode === null) {
|
||||
requestTermination();
|
||||
await terminationRequest;
|
||||
}
|
||||
await filter.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workerRequest = (prepared: PreparedReplayPlan) => ({
|
||||
schemaVersion: 1,
|
||||
left: workerSide(prepared.publicPlan.left, prepared.leftSources),
|
||||
...(prepared.publicPlan.right === undefined ||
|
||||
prepared.rightSources === undefined
|
||||
? {}
|
||||
: { right: workerSide(prepared.publicPlan.right, prepared.rightSources) }),
|
||||
cases: prepared.publicPlan.cases.map((item) => ({
|
||||
caseId: item.case_id,
|
||||
arguments: item.arguments,
|
||||
inputSha256: item.sha256,
|
||||
})),
|
||||
determinism: {
|
||||
clockIso: prepared.publicPlan.determinism.clock_iso,
|
||||
randomSeed: prepared.publicPlan.determinism.random_seed,
|
||||
},
|
||||
limits: {
|
||||
resultDepth: prepared.publicPlan.limits.result_depth,
|
||||
resultNodes: prepared.publicPlan.limits.result_nodes,
|
||||
exceptionBytes: Math.min(
|
||||
64 * 1024,
|
||||
prepared.publicPlan.limits.output_bytes,
|
||||
),
|
||||
},
|
||||
});
|
||||
|
||||
const workerSide = (
|
||||
side: PreparedReplayPlan["publicPlan"]["left"],
|
||||
sources: Readonly<Record<string, string>>,
|
||||
) => ({
|
||||
modules: side.modules.map((module) => ({
|
||||
alias: module.alias,
|
||||
format: module.format,
|
||||
dependencies: module.dependencies,
|
||||
source: sources[module.alias] ?? "",
|
||||
})),
|
||||
entryAlias: side.entry_alias,
|
||||
entryExport: side.entry_export,
|
||||
});
|
||||
|
||||
const systemdArguments = (
|
||||
unit: string,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
prepared: PreparedReplayPlan,
|
||||
workerPath: string,
|
||||
closure: readonly RuntimeFile[],
|
||||
filterPath: string,
|
||||
): string[] => {
|
||||
const limits = prepared.publicPlan.limits;
|
||||
const descriptorPaths = [
|
||||
filterPath,
|
||||
...closure.map(({ sourcePath }) => sourcePath),
|
||||
workerPath,
|
||||
];
|
||||
const workerFd = descriptorPaths.length + 2;
|
||||
const wrapper = descriptorPaths
|
||||
.map((_, index) => `exec ${String(index + 3)}<"$1"; shift`)
|
||||
.concat('exec "$@"')
|
||||
.join("\n");
|
||||
return [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
`--unit=${unit}`,
|
||||
`--property=MemoryMax=${String(limits.memory_bytes)}`,
|
||||
"--property=MemorySwapMax=0",
|
||||
`--property=TasksMax=${String(limits.tasks)}`,
|
||||
`--property=CPUQuota=${String(limits.cpu_quota_percent)}%`,
|
||||
"--property=KillMode=control-group",
|
||||
"--property=SendSIGKILL=yes",
|
||||
"--",
|
||||
policy.shellPath,
|
||||
"-c",
|
||||
wrapper,
|
||||
"rea-replay-wrapper",
|
||||
...descriptorPaths,
|
||||
policy.bubblewrapPath,
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--clearenv",
|
||||
"--setenv",
|
||||
"HOME",
|
||||
"/work",
|
||||
"--setenv",
|
||||
"TMPDIR",
|
||||
"/tmp",
|
||||
"--setenv",
|
||||
"TZ",
|
||||
"UTC",
|
||||
"--setenv",
|
||||
"LANG",
|
||||
"C",
|
||||
"--setenv",
|
||||
"LC_ALL",
|
||||
"C",
|
||||
"--tmpfs",
|
||||
"/",
|
||||
"--dir",
|
||||
"/runtime",
|
||||
"--dir",
|
||||
"/work",
|
||||
"--size",
|
||||
String(limits.tmpfs_bytes),
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
...bindArguments(closure),
|
||||
"--ro-bind-fd",
|
||||
String(workerFd),
|
||||
"/runtime/worker.js",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--remount-ro",
|
||||
"/",
|
||||
"--chdir",
|
||||
"/work",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/runtime/node",
|
||||
`--max-old-space-size=${String(Math.max(8, Math.floor(limits.memory_bytes / 1024 / 1024 / 2)))}`,
|
||||
"--experimental-vm-modules",
|
||||
"--permission",
|
||||
"--allow-fs-read=/runtime/worker.js",
|
||||
"/runtime/worker.js",
|
||||
];
|
||||
};
|
||||
|
||||
const bindArguments = (closure: readonly RuntimeFile[]): string[] => {
|
||||
const arguments_: string[] = [];
|
||||
const directories = new Set<string>();
|
||||
for (const [index, item] of closure.entries()) {
|
||||
const destination = item.destinationPath;
|
||||
let parent = dirname(destination);
|
||||
const chain: string[] = [];
|
||||
while (parent !== "/" && !directories.has(parent)) {
|
||||
chain.push(parent);
|
||||
parent = dirname(parent);
|
||||
}
|
||||
for (const directory of chain.reverse()) {
|
||||
directories.add(directory);
|
||||
arguments_.push("--dir", directory);
|
||||
}
|
||||
arguments_.push("--ro-bind-fd", String(index + 4), destination);
|
||||
}
|
||||
return arguments_;
|
||||
};
|
||||
|
||||
type RuntimeFile = Awaited<
|
||||
ReturnType<typeof resolveLinuxRuntimeClosure>
|
||||
>[number];
|
||||
|
||||
const assertRuntimeCommitment = (
|
||||
prepared: PreparedReplayPlan,
|
||||
closure: readonly RuntimeFile[],
|
||||
): void => {
|
||||
const observed = closure.map((item) => ({
|
||||
source_path: item.sourcePath,
|
||||
destination_path: item.destinationPath,
|
||||
sha256: item.sha256,
|
||||
}));
|
||||
if (
|
||||
digestJson(observed) !==
|
||||
digestJson(prepared.publicPlan.runtime.read_only_files)
|
||||
)
|
||||
throw new TypeError("Replay runtime closure changed after approval");
|
||||
};
|
||||
|
||||
const temporaryFilterHandle = async () => {
|
||||
const { mkdtemp, writeFile, rm } = await import("node:fs/promises");
|
||||
const { tmpdir } = await import("node:os");
|
||||
const { join } = await import("node:path");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-filter-"));
|
||||
const path = join(directory, "seccomp.bpf");
|
||||
await writeFile(path, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const handle = await open(path, "r");
|
||||
return {
|
||||
path,
|
||||
handle,
|
||||
close: async () => {
|
||||
await handle.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
interface CollectedProcess {
|
||||
readonly code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly outputExceeded: boolean;
|
||||
}
|
||||
|
||||
const boundedCollector = (maximum: number) => {
|
||||
const chunks: Buffer[] = [];
|
||||
let bytes = 0;
|
||||
let overflow = false;
|
||||
return {
|
||||
append: (chunk: Buffer) => {
|
||||
const retained = chunk.subarray(0, Math.max(0, maximum - bytes));
|
||||
if (retained.byteLength > 0) chunks.push(retained);
|
||||
bytes += retained.byteLength;
|
||||
if (retained.byteLength < chunk.byteLength) overflow = true;
|
||||
},
|
||||
value: () => Buffer.concat(chunks).toString("utf8"),
|
||||
exceeded: () => overflow,
|
||||
};
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximum: number,
|
||||
) =>
|
||||
new Promise<{ code: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const stdout = boundedCollector(maximum);
|
||||
const stderr = boundedCollector(maximum);
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
child.stdout?.on("data", stdout.append);
|
||||
child.stderr?.on("data", stderr.append);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout: stdout.value(), stderr: stderr.value() });
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const killUnit = async (systemctl: string, unit: string): Promise<void> => {
|
||||
try {
|
||||
await collect(
|
||||
systemctl,
|
||||
["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit],
|
||||
4096,
|
||||
);
|
||||
} catch {
|
||||
/* cleanup continues */
|
||||
}
|
||||
};
|
||||
|
||||
const observeCleanup = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<ReplayExecutionResult["cleanup"]> => {
|
||||
try {
|
||||
const state = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=ActiveState", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
if (
|
||||
state.code !== 0 ||
|
||||
state.stdout.trim() === "inactive" ||
|
||||
state.stdout.trim() === "failed" ||
|
||||
state.stdout.trim().length === 0
|
||||
) {
|
||||
await collect(systemctl, ["--user", "reset-failed", unit], 4096);
|
||||
return { state: "complete", residual_resources: [] };
|
||||
}
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
} catch {
|
||||
return { state: "incomplete", residual_resources: [unit] };
|
||||
}
|
||||
};
|
||||
|
||||
const observeUnitResult = async (
|
||||
systemctl: string,
|
||||
unit: string,
|
||||
): Promise<string> => {
|
||||
try {
|
||||
const result = await collect(
|
||||
systemctl,
|
||||
["--user", "show", "--property=Result", "--value", unit],
|
||||
4096,
|
||||
);
|
||||
return result.stdout.trim();
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
const commitOutcomes = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
): ReplayExecutionResult["outcomes"] =>
|
||||
outcomes.map((outcome) => {
|
||||
const semantic =
|
||||
outcome.value === undefined ? (outcome.exception ?? null) : outcome.value;
|
||||
return {
|
||||
case_id: outcome.case_id,
|
||||
outcome: outcome.outcome,
|
||||
...(outcome.value === undefined
|
||||
? {}
|
||||
: { value: jsonValueSchema.parse(outcome.value) }),
|
||||
...(outcome.exception === undefined
|
||||
? {}
|
||||
: { exception: outcome.exception }),
|
||||
input_sha256: outcome.input_sha256,
|
||||
output_sha256: digestJson(semantic),
|
||||
truncated: false,
|
||||
};
|
||||
});
|
||||
|
||||
const compareOutcomes = (
|
||||
left: ReplayExecutionResult["outcomes"],
|
||||
right: ReplayExecutionResult["outcomes"],
|
||||
): NonNullable<ReplayExecutionResult["comparison"]> =>
|
||||
left.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status:
|
||||
right[index] === undefined
|
||||
? "unknown"
|
||||
: item.outcome === right[index].outcome &&
|
||||
item.output_sha256 === right[index].output_sha256
|
||||
? "equal"
|
||||
: "changed",
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
}));
|
||||
|
||||
const terminationResult = (
|
||||
prepared: PreparedReplayPlan,
|
||||
stderr: string,
|
||||
termination: "timeout" | "oom" | "crash" | "cancelled" | "protocol_error",
|
||||
cleanup: ReplayExecutionResult["cleanup"],
|
||||
limitation?: string,
|
||||
): ReplayExecutionResult => {
|
||||
const outcomes = prepared.publicPlan.cases.map((item) => ({
|
||||
case_id: item.case_id,
|
||||
outcome: termination,
|
||||
input_sha256: item.sha256,
|
||||
output_sha256: null,
|
||||
truncated: termination === "protocol_error",
|
||||
}));
|
||||
const differential = prepared.publicPlan.right !== undefined;
|
||||
return {
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [...outcomes, ...(differential ? outcomes : [])],
|
||||
...(differential
|
||||
? {
|
||||
comparison: outcomes.map((item, index) => ({
|
||||
case_id: item.case_id,
|
||||
status: "unknown" as const,
|
||||
left_index: index,
|
||||
right_index: index,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
stderr,
|
||||
termination,
|
||||
cleanup,
|
||||
limitations: [
|
||||
limitation ??
|
||||
`Replay terminated with ${termination}; the requested functional result remains unknown.`,
|
||||
],
|
||||
reproducer: null,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, realpath } from "node:fs/promises";
|
||||
|
||||
import type { ReplayRuntimeFileIdentity } from "../application/JavaScriptReplayPlanning.js";
|
||||
|
||||
const LDD_OUTPUT_LIMIT = 64 * 1024;
|
||||
|
||||
/** Resolve and content-address the exact ELF closure mounted into a replay. */
|
||||
export const resolveLinuxRuntimeClosure = async (
|
||||
nodePath: string,
|
||||
): Promise<readonly ReplayRuntimeFileIdentity[]> => {
|
||||
const canonicalNode = await realpath(nodePath);
|
||||
const collected = await collectLdd(canonicalNode);
|
||||
if (collected.code !== 0)
|
||||
throw new TypeError(
|
||||
"Node runtime dependency closure could not be resolved",
|
||||
);
|
||||
const paths = [...collected.stdout.matchAll(/(?:=>\s+)?(\/[^\s()]+)/gu)]
|
||||
.map((match) => match[1])
|
||||
.filter((value): value is string => value !== undefined);
|
||||
const libraries = await Promise.all(
|
||||
[...new Set(paths)].map(async (path) => {
|
||||
const sourcePath = await realpath(path);
|
||||
return identity(sourcePath, path);
|
||||
}),
|
||||
);
|
||||
return [await identity(canonicalNode, "/runtime/node"), ...libraries];
|
||||
};
|
||||
|
||||
const identity = async (
|
||||
sourcePath: string,
|
||||
destinationPath: string,
|
||||
): Promise<ReplayRuntimeFileIdentity> => ({
|
||||
sourcePath,
|
||||
destinationPath,
|
||||
sha256: createHash("sha256")
|
||||
.update(await readFile(sourcePath))
|
||||
.digest("hex"),
|
||||
});
|
||||
|
||||
const collectLdd = async (
|
||||
path: string,
|
||||
): Promise<{ readonly code: number | null; readonly stdout: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn("/usr/bin/ldd", [path], {
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
});
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
let stdout = "";
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
const remaining = Math.max(
|
||||
0,
|
||||
LDD_OUTPUT_LIMIT - Buffer.byteLength(stdout),
|
||||
);
|
||||
stdout += chunk.subarray(0, remaining).toString("utf8");
|
||||
});
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
const BPF_LD_W_ABS = 0x20;
|
||||
const BPF_JMP_JEQ_K = 0x15;
|
||||
const BPF_RET_K = 0x06;
|
||||
const SECCOMP_RET_KILL_PROCESS = 0x8000_0000;
|
||||
const SECCOMP_RET_ERRNO = 0x0005_0000 | 1;
|
||||
const SECCOMP_RET_ALLOW = 0x7fff_0000;
|
||||
const AUDIT_ARCH_X86_64 = 0xc000_003e;
|
||||
const IOCTL = 16;
|
||||
const TIOCSTI = 0x5412;
|
||||
|
||||
const DENIED_X86_64_SYSCALLS = [
|
||||
101, 103, 155, 161, 163, 165, 166, 167, 168, 169, 172, 173, 175, 176, 179,
|
||||
212, 246, 248, 249, 250, 272, 298, 303, 304, 308, 310, 311, 312, 313, 320,
|
||||
321, 323, 425, 426, 427, 428, 429, 430, 431, 432, 433, 442,
|
||||
] as const;
|
||||
|
||||
interface Instruction {
|
||||
readonly code: number;
|
||||
readonly jt: number;
|
||||
readonly jf: number;
|
||||
readonly k: number;
|
||||
}
|
||||
|
||||
/** Build the architecture-checked deny filter committed by ADR-0002. */
|
||||
export const buildLinuxX64ReplaySeccomp = (): Uint8Array => {
|
||||
const instructions: Instruction[] = [
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 4 },
|
||||
{ code: BPF_JMP_JEQ_K, jt: 1, jf: 0, k: AUDIT_ARCH_X86_64 },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_KILL_PROCESS },
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 0 },
|
||||
];
|
||||
for (const syscall of DENIED_X86_64_SYSCALLS) {
|
||||
instructions.push({ code: BPF_JMP_JEQ_K, jt: 0, jf: 1, k: syscall });
|
||||
instructions.push({ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ERRNO });
|
||||
}
|
||||
instructions.push(
|
||||
{ code: BPF_JMP_JEQ_K, jt: 0, jf: 3, k: IOCTL },
|
||||
{ code: BPF_LD_W_ABS, jt: 0, jf: 0, k: 24 },
|
||||
{ code: BPF_JMP_JEQ_K, jt: 0, jf: 1, k: TIOCSTI },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ERRNO },
|
||||
{ code: BPF_RET_K, jt: 0, jf: 0, k: SECCOMP_RET_ALLOW },
|
||||
);
|
||||
const encoded = new Uint8Array(instructions.length * 8);
|
||||
const view = new DataView(encoded.buffer);
|
||||
instructions.forEach((instruction, index) => {
|
||||
const offset = index * 8;
|
||||
view.setUint16(offset, instruction.code, true);
|
||||
view.setUint8(offset + 2, instruction.jt);
|
||||
view.setUint8(offset + 3, instruction.jf);
|
||||
view.setUint32(offset + 4, instruction.k, true);
|
||||
});
|
||||
return encoded;
|
||||
};
|
||||
|
||||
export const linuxX64ReplaySeccompDigest = (): string =>
|
||||
createHash("sha256").update(buildLinuxX64ReplaySeccomp()).digest("hex");
|
||||
@@ -0,0 +1,76 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const workerOutcomeSchema = z
|
||||
.object({
|
||||
case_id: z.string(),
|
||||
outcome: z.enum(["return", "exception", "serialization_error", "denied"]),
|
||||
value: z.json().optional(),
|
||||
exception: z
|
||||
.object({
|
||||
name: z.string(),
|
||||
message: z.string(),
|
||||
stack: z.string().nullable(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
input_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
output_sha256: z.null(),
|
||||
truncated: z.literal(false),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((value, context) => {
|
||||
if (value.outcome === "return" && value.value === undefined)
|
||||
context.addIssue({ code: "custom", message: "Return value is missing" });
|
||||
if (value.outcome !== "return" && value.exception === undefined)
|
||||
context.addIssue({ code: "custom", message: "Exception is missing" });
|
||||
if (value.outcome === "return" && value.exception !== undefined)
|
||||
context.addIssue({ code: "custom", message: "Return has an exception" });
|
||||
});
|
||||
|
||||
const workerResponseSchema = z
|
||||
.object({
|
||||
schema_version: z.literal(1),
|
||||
left: z.array(workerOutcomeSchema),
|
||||
right: z.array(workerOutcomeSchema).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export type WorkerProtocolOutcome = z.infer<typeof workerOutcomeSchema>;
|
||||
export type WorkerProtocolResponse = z.infer<typeof workerResponseSchema>;
|
||||
|
||||
interface ExpectedCase {
|
||||
readonly case_id: string;
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
/** Strictly authenticate case ordering and commitments in worker output. */
|
||||
export const parseReplayWorkerResponse = (
|
||||
rawResponse: unknown,
|
||||
cases: readonly ExpectedCase[],
|
||||
differential: boolean,
|
||||
): WorkerProtocolResponse => {
|
||||
const response = workerResponseSchema.parse(rawResponse);
|
||||
if ((response.right !== undefined) !== differential)
|
||||
throw new TypeError("Replay worker differential response is incomplete");
|
||||
validateOutcomeSequence(response.left, cases);
|
||||
if (response.right !== undefined)
|
||||
validateOutcomeSequence(response.right, cases);
|
||||
return response;
|
||||
};
|
||||
|
||||
const validateOutcomeSequence = (
|
||||
outcomes: readonly WorkerProtocolOutcome[],
|
||||
cases: readonly ExpectedCase[],
|
||||
): void => {
|
||||
if (outcomes.length !== cases.length)
|
||||
throw new TypeError("Replay worker response case count changed");
|
||||
outcomes.forEach((outcome, index) => {
|
||||
const expected = cases[index];
|
||||
if (
|
||||
expected === undefined ||
|
||||
outcome.case_id !== expected.case_id ||
|
||||
outcome.input_sha256 !== expected.sha256
|
||||
)
|
||||
throw new TypeError("Replay worker response case identity changed");
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,268 @@
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
mkdtemp,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
stat,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawn, type StdioOptions } from "node:child_process";
|
||||
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
JavaScriptReplayPolicy,
|
||||
ReplayExecutableIdentity,
|
||||
ReplaySourceBytes,
|
||||
} from "../application/JavaScriptReplayPlanning.js";
|
||||
import { digestBytes } from "../application/JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
buildLinuxX64ReplaySeccomp,
|
||||
linuxX64ReplaySeccompDigest,
|
||||
} from "./LinuxSeccompPolicy.js";
|
||||
import { resolveLinuxRuntimeClosure } from "./LinuxRuntimeClosure.js";
|
||||
|
||||
const VERSION_OUTPUT_LIMIT = 16 * 1024;
|
||||
|
||||
/** Production planning host for descriptor-backed reads and fail-closed probes. */
|
||||
export class SystemJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
async readSource(
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
): Promise<ReplaySourceBytes> {
|
||||
const canonicalPath = await realpath(path);
|
||||
const handle = await open(
|
||||
canonicalPath,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW,
|
||||
);
|
||||
try {
|
||||
const metadata = await handle.stat();
|
||||
if (!metadata.isFile() || metadata.size > maximumBytes)
|
||||
throw new RangeError(
|
||||
`Replay source exceeds its declared limit: ${canonicalPath}`,
|
||||
);
|
||||
const bytes = await handle.readFile();
|
||||
return { canonicalPath, bytes };
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
}
|
||||
|
||||
async identifyExecutable(
|
||||
path: string,
|
||||
versionArguments: readonly string[],
|
||||
): Promise<ReplayExecutableIdentity> {
|
||||
const canonicalPath = await realpath(path);
|
||||
const metadata = await stat(canonicalPath);
|
||||
if (!metadata.isFile())
|
||||
throw new TypeError(`Replay executable is not a file: ${canonicalPath}`);
|
||||
const [bytes, version] = await Promise.all([
|
||||
readFile(canonicalPath),
|
||||
capture(canonicalPath, versionArguments, VERSION_OUTPUT_LIMIT),
|
||||
]);
|
||||
return {
|
||||
path: canonicalPath,
|
||||
version: version.trim(),
|
||||
sha256: digestBytes(bytes),
|
||||
};
|
||||
}
|
||||
|
||||
identifyWorker(): Promise<ReplayExecutableIdentity> {
|
||||
return this.identifyExecutable(
|
||||
fileURLToPath(new URL("./JavaScriptReplayWorker.js", import.meta.url)),
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
identifyRuntimeClosure(nodePath: string) {
|
||||
return resolveLinuxRuntimeClosure(nodePath);
|
||||
}
|
||||
|
||||
seccompDigest(): string {
|
||||
return linuxX64ReplaySeccompDigest();
|
||||
}
|
||||
|
||||
async probe(policy: JavaScriptReplayPolicy): Promise<void> {
|
||||
if (process.platform !== "linux" || process.arch !== "x64")
|
||||
throw new TypeError("Controlled replay requires Linux x86_64 in v1");
|
||||
const bwrapMetadata = await stat(policy.bubblewrapPath);
|
||||
if ((bwrapMetadata.mode & 0o4000) !== 0)
|
||||
throw new TypeError("Setuid Bubblewrap is not admitted by replay policy");
|
||||
if (
|
||||
(await readFile("/sys/fs/cgroup/cgroup.controllers", "utf8")).trim()
|
||||
.length === 0
|
||||
)
|
||||
throw new TypeError("Controlled replay requires delegated cgroup v2");
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-replay-probe-"));
|
||||
const filterPath = join(directory, "seccomp.bpf");
|
||||
await writeFile(filterPath, buildLinuxX64ReplaySeccomp(), { mode: 0o600 });
|
||||
const filter = await open(filterPath, "r");
|
||||
try {
|
||||
await run(
|
||||
policy.bubblewrapPath,
|
||||
[
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind-try",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
);
|
||||
await runExpectFailure(
|
||||
policy.bubblewrapPath,
|
||||
[
|
||||
"--unshare-all",
|
||||
"--unshare-user",
|
||||
"--disable-userns",
|
||||
"--new-session",
|
||||
"--die-with-parent",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--ro-bind",
|
||||
"/usr",
|
||||
"/usr",
|
||||
"--ro-bind",
|
||||
"/lib",
|
||||
"/lib",
|
||||
"--ro-bind-try",
|
||||
"/lib64",
|
||||
"/lib64",
|
||||
"--proc",
|
||||
"/proc",
|
||||
"--dev",
|
||||
"/dev",
|
||||
"--seccomp",
|
||||
"3",
|
||||
"--",
|
||||
"/usr/bin/unshare",
|
||||
"--mount",
|
||||
"/usr/bin/true",
|
||||
],
|
||||
["ignore", "pipe", "pipe", filter.fd],
|
||||
);
|
||||
await run(policy.systemdRunPath, [
|
||||
"--user",
|
||||
"--pipe",
|
||||
"--wait",
|
||||
"--service-type=exec",
|
||||
"--quiet",
|
||||
"--property=MemoryMax=16777216",
|
||||
"--property=MemorySwapMax=0",
|
||||
"--property=TasksMax=2",
|
||||
"--",
|
||||
"/usr/bin/true",
|
||||
]);
|
||||
} finally {
|
||||
await filter.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const capture = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximumBytes: number,
|
||||
): Promise<string> => {
|
||||
if (arguments_.length === 0) return "content-addressed-worker-v1";
|
||||
const result = await collect(executable, arguments_, maximumBytes);
|
||||
if (result.code !== 0)
|
||||
throw new TypeError(`Replay executable probe failed: ${executable}`);
|
||||
return result.stdout.length > 0 ? result.stdout : result.stderr;
|
||||
};
|
||||
|
||||
const run = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
stdio?: StdioOptions,
|
||||
): Promise<void> => {
|
||||
const result = await collect(
|
||||
executable,
|
||||
arguments_,
|
||||
VERSION_OUTPUT_LIMIT,
|
||||
stdio,
|
||||
);
|
||||
if (result.code !== 0)
|
||||
throw new TypeError(
|
||||
`Replay feature probe failed (${String(result.code)}): ${executable}: ${result.stderr.trim()}`,
|
||||
);
|
||||
};
|
||||
|
||||
const runExpectFailure = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
stdio: StdioOptions,
|
||||
): Promise<void> => {
|
||||
const result = await collect(
|
||||
executable,
|
||||
arguments_,
|
||||
VERSION_OUTPUT_LIMIT,
|
||||
stdio,
|
||||
);
|
||||
if (result.code === 0)
|
||||
throw new TypeError(
|
||||
`Replay denial probe unexpectedly succeeded: ${executable}`,
|
||||
);
|
||||
};
|
||||
|
||||
const collect = async (
|
||||
executable: string,
|
||||
arguments_: readonly string[],
|
||||
maximumBytes: number,
|
||||
stdio: StdioOptions = ["ignore", "pipe", "pipe"],
|
||||
): Promise<{
|
||||
readonly code: number | null;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const child = spawn(executable, [...arguments_], { stdio });
|
||||
const timeout = setTimeout(() => child.kill("SIGKILL"), 5_000);
|
||||
timeout.unref();
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
const retain = (current: string, chunk: Buffer): string => {
|
||||
const remaining = Math.max(0, maximumBytes - Buffer.byteLength(current));
|
||||
return current + chunk.subarray(0, remaining).toString("utf8");
|
||||
};
|
||||
if (child.stdout !== null)
|
||||
child.stdout.on("data", (chunk: Buffer) => {
|
||||
stdout = retain(stdout, chunk);
|
||||
});
|
||||
if (child.stderr !== null)
|
||||
child.stderr.on("data", (chunk: Buffer) => {
|
||||
stderr = retain(stderr, chunk);
|
||||
});
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
child.once("close", (code) => {
|
||||
clearTimeout(timeout);
|
||||
resolve({ code, stdout, stderr });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user