diff --git a/test/e2e/README.md b/test/e2e/README.md index bf1815f95b0..5c18324d8ab 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -187,6 +187,90 @@ discovery command locally to inspect the generated test matrix: npx tsx tools/e2e/credential-free-tests.mts ``` +## Inactive Windows MXC OpenClaw qualification + +`windows-mxc-openclaw-process-container.test.ts` is an explicit local +qualification target for epic #8178. It exercises an operator-supplied native +Windows OpenShell package and a staged OpenClaw artifact through the OpenShell +`process_container` driver. It does not register MXC, call `wxc-exec.exe` +directly, or establish Windows support. +The generated driver configuration requests the stricter less-privileged +AppContainer mode and records that choice in the receipt. + +The target requires a Windows x64 host that passes the minimum MXC candidate +check. It rejects a dirty NemoClaw checkout and requires exact expected +identities for that checkout, the OpenShell CLI and gateway, the +OpenShell-supplied `wxc-exec.exe`, the complete OpenClaw artifact tree, Node.js, +and the OpenClaw entrypoint. Compute the canonical artifact-tree digest after +staging: + +```powershell +npx tsx tools/e2e/windows-mxc-openclaw-artifact-tree.mts $env:NEMOCLAW_WINDOWS_MXC_OPENCLAW_ROOT +``` + +Set the following environment variables to paths or exact lowercase identity +values. Do not put credentials in them. + +| Variable | Meaning | +| --- | --- | +| `E2E_ARTIFACT_DIR` | Existing directory for the secret-free qualification receipt | +| `NEMOCLAW_E2E_EXPECTED_SHA` | Exact 40-character NemoClaw checkout revision | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI` | Extracted `openshell.exe` path | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY` | Extracted `openshell-gateway.exe` path | +| `NEMOCLAW_WINDOWS_MXC_WXC_EXEC` | `wxc-exec.exe` supplied for that OpenShell package | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_VERSION` | Exact OpenShell package version | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_REVISION` | Exact 40-character OpenShell source revision | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI_SHA256` | Expected OpenShell CLI SHA-256 | +| `NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY_SHA256` | Expected OpenShell gateway SHA-256 | +| `NEMOCLAW_WINDOWS_MXC_WXC_EXEC_SHA256` | Expected `wxc-exec.exe` SHA-256 | +| `NEMOCLAW_WINDOWS_MXC_OPENCLAW_ROOT` | Staged native OpenClaw artifact root | +| `NEMOCLAW_WINDOWS_MXC_NODE` | Node.js executable beneath the artifact root | +| `NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY` | OpenClaw entrypoint beneath the artifact root | +| `NEMOCLAW_WINDOWS_MXC_OPENCLAW_VERSION` | Expected OpenClaw version | +| `NEMOCLAW_WINDOWS_MXC_OPENCLAW_ARTIFACT_TREE_SHA256` | Expected canonical artifact-tree SHA-256 | +| `NEMOCLAW_WINDOWS_MXC_NODE_SHA256` | Expected Node.js SHA-256 | +| `NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY_SHA256` | Expected OpenClaw entrypoint SHA-256 | + +The target creates a random OpenClaw gateway token for readiness checks. It +passes that token through the MXC agent environment; current OpenShell +`process_container` packaging can therefore expose its encoded configuration, +including the token, to privileged host process inspection while `wxc-exec.exe` +starts the sandbox. The token is never written to the receipt or supplied in +the OpenClaw command arguments, is not reused, and is useful only for the +temporary loopback OpenClaw gateway. Cleanup attempts sandbox deletion, stops +the recorded OpenClaw process, clears the in-memory environment value, and +removes the runtime home, state, configuration, and gateway logs. A direct +process-tree termination is an emergency cleanup fallback only. The host-side +OpenShell processes receive an allowlist of Windows runtime variables rather +than the complete caller environment. Before using a termination fallback, +the host binds the process ID to the expected executable, command arguments, +and creation time. For OpenClaw, it also validates the probe-parent ancestry. +The host rejects a mismatched or reused PID. The fallback uses the +`taskkill.exe` beneath the validated Windows system root. If either the +OpenClaw process or OpenShell gateway needs that fallback, the qualification +fails. The delete retry and process-termination paths are failure containment, +not compatibility workarounds that permit a passing result; their presence does +not assume a specific upstream defect. Remove them only when failed or partial +OpenShell lifecycle operations can still guarantee teardown without host-side +cleanup. + +Run only the explicit target: + +```powershell +$env:NEMOCLAW_RUN_LIVE_E2E = "1" +$env:NEMOCLAW_RUN_WINDOWS_MXC_OPENCLAW_E2E = "1" +npx vitest run --project e2e-live test/e2e/live/windows-mxc-openclaw-process-container.test.ts +``` + +The target verifies OpenClaw startup and in-sandbox health, read-write and denied +filesystem behavior, registry cleanup, and termination of the recorded +OpenClaw process on sandbox delete. After preflight and local setup succeed, it +writes a secret-free receipt for either verdict and records whether sensitive +runtime artifacts were removed. When that cleanup succeeds, a failed run retains +only non-sensitive probe files for diagnosis. +Gateway mTLS, governed egress, managed inference, gateway-restart recovery, and +production activation remain outside this target. + The retired `hermes-dashboard` selector remains a compatibility alias for `hermes-e2e` in both selector inputs. Reports use the canonical `hermes-e2e` name. That lane always enables dashboard coverage while preserving diff --git a/test/e2e/live/windows-mxc-openclaw-process-container-helpers.ts b/test/e2e/live/windows-mxc-openclaw-process-container-helpers.ts new file mode 100644 index 00000000000..1b432b88812 --- /dev/null +++ b/test/e2e/live/windows-mxc-openclaw-process-container-helpers.ts @@ -0,0 +1,1533 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { type ChildProcess, spawnSync } from "node:child_process"; +import { randomBytes } from "node:crypto"; +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; + +import { assessWindowsMxcProcessContainerCandidate } from "../../../src/lib/onboard/windows-mxc/host-qualification.ts"; +import { + sha256File, + sha256WindowsOpenClawArtifactTree, +} from "../../../tools/e2e/windows-mxc-openclaw-artifact-tree.mts"; +import { + type ChildProcessProgress, + spawnObservedChild, +} from "../fixtures/observed-child-process.ts"; + +type QualificationProgress = ChildProcessProgress & { + phase(label: string): void; +}; + +const SHA256_PATTERN = /^[0-9a-f]{64}$/u; +const REVISION_PATTERN = /^[0-9a-f]{40}$/u; +const VERSION_PATTERN = /^[0-9]+(?:[.][0-9]+){2,3}(?:[-.][0-9A-Za-z][0-9A-Za-z.-]*)?$/u; +const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024; +const COMMAND_TIMEOUT_MS = 30_000; +const READY_TIMEOUT_MS = 180_000; +const TERMINATION_TIMEOUT_MS = 15_000; +const WINDOWS_PROCESS_ENVIRONMENT_NAMES = [ + "ComSpec", + "NUMBER_OF_PROCESSORS", + "OS", + "Path", + "PATHEXT", + "PROCESSOR_ARCHITECTURE", + "PROCESSOR_ARCHITEW6432", + "SystemDrive", + "SystemRoot", + "TEMP", + "TMP", + "windir", +] as const; + +const AGENT_ENVIRONMENT_NAMES = [ + "NEMOCLAW_MXC_E2E_DENY_PATH", + "NEMOCLAW_MXC_E2E_ENTRY", + "NEMOCLAW_MXC_E2E_HEARTBEAT_PATH", + "NEMOCLAW_MXC_E2E_HOME", + "NEMOCLAW_MXC_E2E_NODE", + "NEMOCLAW_MXC_E2E_OPENCLAW_PORT", + "NEMOCLAW_MXC_E2E_OPENCLAW_PID_PATH", + "NEMOCLAW_MXC_E2E_OUTCOME_PATH", + "NEMOCLAW_MXC_E2E_READY_PATH", + "NEMOCLAW_MXC_E2E_RESULT_PATH", + "NEMOCLAW_MXC_E2E_STOP_PATH", + "NEMOCLAW_MXC_E2E_TOKEN", +] as const; + +export interface WindowsMxcOpenClawQualificationInputs { + readonly artifactDirectory: string; + readonly expected: { + readonly nemoClawRevision: string; + readonly nodeSha256: string; + readonly openClawArtifactTreeSha256: string; + readonly openClawEntrySha256: string; + readonly openShellCliSha256: string; + readonly openShellGatewaySha256: string; + readonly wxcExecSha256: string; + }; + readonly openClaw: { + readonly entryPath: string; + readonly nodePath: string; + readonly root: string; + readonly version: string; + }; + readonly openShell: { + readonly cliPath: string; + readonly gatewayPath: string; + readonly packageVersion: string; + readonly revision: string; + readonly wxcExecPath: string; + }; +} + +export type CommandResult = { + readonly exitCode: number; + readonly stderr: string; + readonly stdout: string; +}; + +export interface WindowsProcessIdentity { + readonly commandLine: string; + readonly creationDate: string; + readonly executablePath: string; + readonly parentProcessId: number; + readonly processId: number; +} + +export type TrustedOpenClawProcessIdentity = { + readonly child: WindowsProcessIdentity; + readonly parent: WindowsProcessIdentity; +}; + +type QualificationChecks = { + readonly artifactIdentity: boolean; + readonly filesystemControlWrite: boolean; + readonly filesystemDeniedWrite: boolean; + readonly openClawHealth: boolean; + readonly openClawProcessPresentWhileReady: boolean; + readonly registryPresentWhileReady: boolean; + readonly registryRemovedAfterDelete: boolean; + readonly sandboxCreateAccepted: boolean; + readonly sandboxDeleteAccepted: boolean; + readonly workloadTerminatedByDelete: boolean; +}; + +export interface WindowsMxcOpenClawQualificationReceipt { + readonly schemaVersion: 1; + readonly classification: "inactive-candidate"; + readonly backend: "process_container"; + readonly configuration: { + readonly pcLeastPrivilege: true; + }; + readonly identities: { + readonly host: { + readonly architecture: "x64"; + readonly platform: "win32"; + readonly release: string; + }; + readonly nemoClawRevision: string; + readonly openClaw: { + readonly artifactTreeSha256: string; + readonly entrySha256: string; + readonly nodeSha256: string; + readonly version: string; + }; + readonly openShell: { + readonly cliSha256: string; + readonly gatewaySha256: string; + readonly packageVersion: string; + readonly revision: string; + }; + readonly wxcExecSha256: string; + }; + readonly checks: QualificationChecks; + readonly cleanup: { + readonly boundedStopMarkerNeeded: boolean; + readonly emergencyProcessTerminationNeeded: boolean; + readonly emergencyGatewayTerminationNeeded: boolean; + readonly gatewayProcessStopped: boolean; + readonly openClawProcessStopped: boolean; + readonly runDirectoryRemoved: boolean; + readonly sandboxDeleteRetried: boolean; + readonly sensitiveRuntimeArtifactsRemoved: boolean; + }; + readonly verdict: "pass" | "fail"; + readonly deferred: readonly [ + "gateway-mtls", + "managed-inference", + "governed-egress", + "gateway-restart-recovery", + "production-activation", + ]; +} + +function requiredEnvironment(environment: NodeJS.ProcessEnv, name: string): string { + const value = environment[name]?.trim(); + if (!value) throw new Error(`${name} is required`); + return value; +} + +function expectedPattern(environment: NodeJS.ProcessEnv, name: string, pattern: RegExp): string { + const value = requiredEnvironment(environment, name); + if (!pattern.test(value)) throw new Error(`${name} has an unsupported format`); + return value; +} + +function realRegularFile(input: string, name: string): string { + const absolute = path.resolve(input); + const status = fs.lstatSync(absolute); + if (!status.isFile() || status.isSymbolicLink()) { + throw new Error(`${name} must be a regular file, not a link`); + } + return fs.realpathSync(absolute); +} + +function realDirectory(input: string, name: string): string { + const absolute = path.resolve(input); + const status = fs.lstatSync(absolute); + if (!status.isDirectory() || status.isSymbolicLink()) { + throw new Error(`${name} must be a directory, not a link`); + } + return fs.realpathSync(absolute); +} + +function requireDescendant(file: string, root: string, name: string): void { + const relative = path.relative(root, file); + if (!relative || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error(`${name} must be a child of the OpenClaw artifact root`); + } +} + +export function parseWindowsMxcOpenClawQualificationEnvironment( + environment: NodeJS.ProcessEnv, +): WindowsMxcOpenClawQualificationInputs { + const openClawRoot = realDirectory( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_OPENCLAW_ROOT"), + "OpenClaw artifact root", + ); + const nodePath = realRegularFile( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_NODE"), + "OpenClaw Node.js executable", + ); + const entryPath = realRegularFile( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY"), + "OpenClaw entrypoint", + ); + requireDescendant(nodePath, openClawRoot, "OpenClaw Node.js executable"); + requireDescendant(entryPath, openClawRoot, "OpenClaw entrypoint"); + + return { + artifactDirectory: realDirectory( + requiredEnvironment(environment, "E2E_ARTIFACT_DIR"), + "E2E artifact directory", + ), + expected: { + nemoClawRevision: expectedPattern(environment, "NEMOCLAW_E2E_EXPECTED_SHA", REVISION_PATTERN), + nodeSha256: expectedPattern(environment, "NEMOCLAW_WINDOWS_MXC_NODE_SHA256", SHA256_PATTERN), + openClawArtifactTreeSha256: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENCLAW_ARTIFACT_TREE_SHA256", + SHA256_PATTERN, + ), + openClawEntrySha256: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY_SHA256", + SHA256_PATTERN, + ), + openShellCliSha256: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI_SHA256", + SHA256_PATTERN, + ), + openShellGatewaySha256: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY_SHA256", + SHA256_PATTERN, + ), + wxcExecSha256: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_WXC_EXEC_SHA256", + SHA256_PATTERN, + ), + }, + openClaw: { + entryPath, + nodePath, + root: openClawRoot, + version: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENCLAW_VERSION", + VERSION_PATTERN, + ), + }, + openShell: { + cliPath: realRegularFile( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI"), + "OpenShell CLI", + ), + gatewayPath: realRegularFile( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY"), + "OpenShell gateway", + ), + packageVersion: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENSHELL_VERSION", + VERSION_PATTERN, + ), + revision: expectedPattern( + environment, + "NEMOCLAW_WINDOWS_MXC_OPENSHELL_REVISION", + REVISION_PATTERN, + ), + wxcExecPath: realRegularFile( + requiredEnvironment(environment, "NEMOCLAW_WINDOWS_MXC_WXC_EXEC"), + "OpenShell-supplied wxc-exec", + ), + }, + }; +} + +export { sha256File }; + +export function sandboxListContainsExactName(output: string, sandboxName: string): boolean { + const parsed: unknown = JSON.parse(output); + if (!Array.isArray(parsed)) throw new Error("OpenShell sandbox list JSON must be an array"); + return parsed.some( + (entry) => + typeof entry === "object" && entry !== null && "name" in entry && entry.name === sandboxName, + ); +} + +export function shouldRetrySandboxDelete( + sandboxDeleteAccepted: boolean, + exactRegistryEntryPresent: boolean, +): boolean { + return !sandboxDeleteAccepted || exactRegistryEntryPresent; +} + +export function parseWindowsProcessIdentity(output: string): WindowsProcessIdentity | null { + if (!output.trim()) return null; + const value: unknown = JSON.parse(output); + if ( + typeof value !== "object" || + value === null || + !("ProcessId" in value) || + !Number.isSafeInteger(value.ProcessId) || + !("ParentProcessId" in value) || + !Number.isSafeInteger(value.ParentProcessId) || + !("ExecutablePath" in value) || + typeof value.ExecutablePath !== "string" || + !("CommandLine" in value) || + typeof value.CommandLine !== "string" || + !("CreationDate" in value) || + typeof value.CreationDate !== "string" + ) { + throw new Error("Windows process identity output is incomplete"); + } + return { + commandLine: value.CommandLine, + creationDate: value.CreationDate, + executablePath: value.ExecutablePath, + parentProcessId: value.ParentProcessId as number, + processId: value.ProcessId as number, + }; +} + +function normalizeWindowsIdentityValue(value: string): string { + return value.replaceAll("\\", "/").toLowerCase(); +} + +function commandLineHasExactArgument(commandLine: string, expected: string): boolean { + const escaped = normalizeWindowsIdentityValue(expected).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); + return new RegExp(`(?:^|[\\s\"])${escaped}(?=$|[\\s\"])`, "u").test( + normalizeWindowsIdentityValue(commandLine), + ); +} + +function commandLineHasExactArgumentPair( + commandLine: string, + first: string, + second: string, +): boolean { + const normalized = normalizeWindowsIdentityValue(commandLine); + const pair = [first, second] + .map((value) => normalizeWindowsIdentityValue(value).replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")) + .join('[\\s"]+'); + return new RegExp(`(?:^|[\\s\"])${pair}(?=$|[\\s\"])`, "u").test(normalized); +} + +export function sameWindowsProcessIdentity( + expected: WindowsProcessIdentity, + observed: WindowsProcessIdentity, +): boolean { + return ( + expected.processId === observed.processId && + expected.parentProcessId === observed.parentProcessId && + expected.creationDate === observed.creationDate && + normalizeWindowsIdentityValue(expected.executablePath) === + normalizeWindowsIdentityValue(observed.executablePath) && + expected.commandLine === observed.commandLine + ); +} + +export function assertExpectedOpenClawProcessIdentity( + identity: TrustedOpenClawProcessIdentity, + expected: { + readonly entryPath: string; + readonly nodePath: string; + readonly port: number; + readonly probeAgentPath: string; + }, +): void { + const nodePath = normalizeWindowsIdentityValue(expected.nodePath); + if ( + normalizeWindowsIdentityValue(identity.child.executablePath) !== nodePath || + normalizeWindowsIdentityValue(identity.parent.executablePath) !== nodePath || + identity.child.parentProcessId !== identity.parent.processId || + !commandLineHasExactArgument(identity.child.commandLine, expected.entryPath) || + !commandLineHasExactArgument(identity.child.commandLine, "gateway") || + !commandLineHasExactArgumentPair(identity.child.commandLine, "--port", String(expected.port)) || + !commandLineHasExactArgument(identity.parent.commandLine, expected.probeAgentPath) + ) { + throw new Error( + "sandbox-reported PID does not match the host-observed OpenClaw process identity", + ); + } +} + +export function assertExpectedOpenShellGatewayProcessIdentity( + identity: WindowsProcessIdentity, + expected: { readonly gatewayPath: string; readonly port: number }, +): void { + if ( + normalizeWindowsIdentityValue(identity.executablePath) !== + normalizeWindowsIdentityValue(expected.gatewayPath) || + !commandLineHasExactArgumentPair(identity.commandLine, "--port", String(expected.port)) || + !commandLineHasExactArgument(identity.commandLine, "--disable-tls") + ) { + throw new Error("spawned PID does not match the expected OpenShell gateway process identity"); + } +} + +export function allowlistedWindowsProcessEnvironment( + environment: NodeJS.ProcessEnv, +): NodeJS.ProcessEnv { + const allowed: NodeJS.ProcessEnv = {}; + const allowedNames = new Set(WINDOWS_PROCESS_ENVIRONMENT_NAMES.map((name) => name.toLowerCase())); + for (const [name, value] of Object.entries(environment)) { + if (value !== undefined && allowedNames.has(name.toLowerCase())) allowed[name] = value; + } + return allowed; +} + +function tomlString(value: string): string { + return JSON.stringify(value.replaceAll("\\", "/")); +} + +export function renderWindowsMxcGatewayConfig(input: { + readonly agentPath: string; + readonly shareDirectory: string; + readonly wxcExecPath: string; +}): string { + return [ + "[openshell.drivers.mxc]", + `wxc_exec_path = ${tomlString(input.wxcExecPath)}`, + 'backend = "process_container"', + 'default_configuration_id = "composable"', + `share_dir = ${tomlString(input.shareDirectory)}`, + `agent_cwd = ${tomlString(input.shareDirectory)}`, + "agent_command = [", + ` ${tomlString(input.agentPath)},`, + ` ${tomlString(path.join(input.shareDirectory, "probe-agent.mjs"))},`, + "]", + "agent_env = [", + ...AGENT_ENVIRONMENT_NAMES.map((name) => ` ${JSON.stringify(name)},`), + "]", + "pc_least_privilege = true", + "pc_capabilities = []", + "egress_proxy = false", + 'egress_proxy_addr = ""', + "debug = false", + "", + ].join("\n"); +} + +export function renderWindowsMxcFilesystemPolicy(input: { + readonly openClawRoot: string; + readonly shareDirectory: string; +}): string { + return [ + "version: 1", + "", + "filesystem_policy:", + " include_workdir: false", + " read_only:", + ` - ${JSON.stringify(input.openClawRoot.replaceAll("\\", "/"))}`, + " read_write:", + ` - ${JSON.stringify(input.shareDirectory.replaceAll("\\", "/"))}`, + "", + ].join("\n"); +} + +export function renderWindowsMxcOpenClawProbeAgent(): string { + return `import { execFile, spawn } from "node:child_process"; +import { existsSync, writeFileSync } from "node:fs"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); +const required = (name) => { + const value = process.env[name]; + if (!value) throw new Error(name + " is required"); + return value; +}; +const node = required("NEMOCLAW_MXC_E2E_NODE"); +const entry = required("NEMOCLAW_MXC_E2E_ENTRY"); +const home = required("NEMOCLAW_MXC_E2E_HOME"); +const token = required("NEMOCLAW_MXC_E2E_TOKEN"); +const readyPath = required("NEMOCLAW_MXC_E2E_READY_PATH"); +const resultPath = required("NEMOCLAW_MXC_E2E_RESULT_PATH"); +const outcomePath = required("NEMOCLAW_MXC_E2E_OUTCOME_PATH"); +const heartbeatPath = required("NEMOCLAW_MXC_E2E_HEARTBEAT_PATH"); +const stopPath = required("NEMOCLAW_MXC_E2E_STOP_PATH"); +const denyPath = required("NEMOCLAW_MXC_E2E_DENY_PATH"); +const port = required("NEMOCLAW_MXC_E2E_OPENCLAW_PORT"); +const openClawPidPath = required("NEMOCLAW_MXC_E2E_OPENCLAW_PID_PATH"); +const env = { + ...process.env, + HOME: home, + OPENCLAW_GATEWAY_TOKEN: token, + USERPROFILE: home, +}; +const sleep = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)); +const run = async (args, timeout = 15000) => { + try { + const output = await execFileAsync(node, args, { + env, + timeout, + windowsHide: true, + maxBuffer: 4 * 1024 * 1024, + }); + return { exitCode: 0, stdout: output.stdout, stderr: output.stderr }; + } catch (error) { + return { + exitCode: Number.isInteger(error.code) ? error.code : 1, + stdout: error.stdout || "", + stderr: error.stderr || error.message || String(error), + }; + } +}; + +writeFileSync(resultPath, JSON.stringify({ phase: "control", controlWrite: true }), "utf8"); +let deniedWrite = false; +try { + writeFileSync(denyPath, "denied write must not land", "utf8"); +} catch { + deniedWrite = true; +} + +const version = await run([entry, "--version"]); +const gateway = spawn( + node, + [ + entry, + "gateway", + "run", + "--dev", + "--allow-unconfigured", + "--auth", + "token", + "--bind", + "loopback", + "--port", + port, + ], + { env, stdio: "ignore", windowsHide: true }, +); +let gatewaySpawnError = null; +gateway.once("error", (error) => { + gatewaySpawnError = error instanceof Error ? error.message : String(error); +}); +if (gateway.pid !== undefined) writeFileSync(openClawPidPath, String(gateway.pid), "utf8"); + +let healthObserved = false; +let lastHealth = { exitCode: null, stdout: "", stderr: "" }; +const deadline = Date.now() + 120000; +while (Date.now() < deadline && gateway.exitCode === null && gatewaySpawnError === null) { + lastHealth = await run([ + entry, + "gateway", + "health", + "--json", + "--url", + "ws://127.0.0.1:" + port, + "--timeout", + "5000", + ]); + if (lastHealth.exitCode === 0) { + healthObserved = true; + break; + } + await sleep(1000); +} + +const result = { + controlWrite: true, + deniedWrite, + gatewayExitedBeforeReadiness: gateway.exitCode !== null, + gatewaySpawnError, + healthObserved, + openClawVersion: version.stdout.trim(), + versionExitCode: version.exitCode, +}; +writeFileSync(resultPath, JSON.stringify(result), "utf8"); +writeFileSync(outcomePath, JSON.stringify(result), "utf8"); +if (healthObserved) writeFileSync(readyPath, JSON.stringify(result), "utf8"); + +while (healthObserved && gateway.exitCode === null && !existsSync(stopPath)) { + writeFileSync(heartbeatPath, String(Date.now()), "utf8"); + await sleep(250); +} + +if (gateway.exitCode === null) { + gateway.kill(); + await Promise.race([ + new Promise((resolve) => gateway.once("exit", resolve)), + sleep(5000), + ]); +} +process.exit(healthObserved && deniedWrite ? 0 : 1); +`; +} + +function commandDetail(result: CommandResult): string { + return [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join("\n"); +} + +async function runCommand( + file: string, + args: readonly string[], + environment: NodeJS.ProcessEnv, + progress: ChildProcessProgress, + activityLabel: string, + timeoutMs = COMMAND_TIMEOUT_MS, +): Promise { + const child = spawnObservedChild(file, args, { + activityLabel, + progress, + spawn: { + env: environment, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }, + }); + return await new Promise((resolve, reject) => { + let stdout = ""; + let stderr = ""; + let outputBytes = 0; + const timer = setTimeout(() => { + child.kill(); + reject(new Error(`${path.basename(file)} timed out after ${timeoutMs}ms`)); + }, timeoutMs); + const append = (target: "stdout" | "stderr", chunk: Buffer) => { + outputBytes += chunk.byteLength; + if (outputBytes > MAX_COMMAND_OUTPUT_BYTES) { + clearTimeout(timer); + child.kill(); + reject(new Error(`${path.basename(file)} output exceeded its bound`)); + return; + } + if (target === "stdout") stdout += chunk.toString("utf8"); + else stderr += chunk.toString("utf8"); + }; + child.stdout?.on("data", (chunk: Buffer) => append("stdout", chunk)); + child.stderr?.on("data", (chunk: Buffer) => append("stderr", chunk)); + child.once("error", (error) => { + clearTimeout(timer); + reject(error); + }); + child.once("close", (code) => { + clearTimeout(timer); + resolve({ exitCode: code ?? 1, stdout, stderr }); + }); + }); +} + +export function parseWindowsProcessQueryResult( + result: CommandResult, +): WindowsProcessIdentity | null { + if (result.exitCode === 3) return null; + if (result.exitCode !== 0) { + throw new Error(`host process identity query failed: ${commandDetail(result)}`); + } + return parseWindowsProcessIdentity(result.stdout); +} + +async function observeWindowsProcessIdentity( + processId: number, + powershellPath: string, + environment: NodeJS.ProcessEnv, + progress: ChildProcessProgress, + activityLabel: string, +): Promise { + const result = await runCommand( + powershellPath, + [ + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-Command", + `$process = Get-CimInstance Win32_Process -Filter \"ProcessId = ${processId}\" -ErrorAction Stop; if ($null -eq $process) { exit 3 }; $process | Select-Object ProcessId, ParentProcessId, ExecutablePath, CommandLine, CreationDate | ConvertTo-Json -Compress`, + ], + environment, + progress, + activityLabel, + ); + return parseWindowsProcessQueryResult(result); +} + +function writeStopMarkerOnce(file: string): void { + try { + fs.writeFileSync(file, "stop\n", { encoding: "utf8", flag: "wx" }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + } +} + +async function observeTrustedOpenClawProcessIdentity(input: { + readonly entryPath: string; + readonly nodePath: string; + readonly port: number; + readonly powershellPath: string; + readonly probeAgentPath: string; + readonly processId: number; + readonly environment: NodeJS.ProcessEnv; + readonly progress: ChildProcessProgress; +}): Promise { + const child = await observeWindowsProcessIdentity( + input.processId, + input.powershellPath, + input.environment, + input.progress, + "command: windows-mxc-openclaw-process-identity", + ); + if (child === null) return null; + const parent = await observeWindowsProcessIdentity( + child.parentProcessId, + input.powershellPath, + input.environment, + input.progress, + "command: windows-mxc-openclaw-parent-identity", + ); + if (parent === null) throw new Error("OpenClaw parent process identity is unavailable"); + const identity = { child, parent }; + assertExpectedOpenClawProcessIdentity(identity, input); + return identity; +} + +async function trustedProcessIsAlive( + identity: WindowsProcessIdentity, + powershellPath: string, + environment: NodeJS.ProcessEnv, + progress: ChildProcessProgress, +): Promise { + const observed = await observeWindowsProcessIdentity( + identity.processId, + powershellPath, + environment, + progress, + "command: windows-mxc-openclaw-process-liveness", + ); + return observed !== null && sameWindowsProcessIdentity(identity, observed); +} + +async function waitForTrustedProcessExit( + identity: WindowsProcessIdentity, + powershellPath: string, + environment: NodeJS.ProcessEnv, + progress: ChildProcessProgress, +): Promise { + const deadline = Date.now() + TERMINATION_TIMEOUT_MS; + while (Date.now() < deadline) { + if (!(await trustedProcessIsAlive(identity, powershellPath, environment, progress))) + return true; + await new Promise((resolve) => setTimeout(resolve, 500)); + } + return !(await trustedProcessIsAlive(identity, powershellPath, environment, progress)); +} + +async function waitForPort(port: number, child: ChildProcess): Promise { + const deadline = Date.now() + COMMAND_TIMEOUT_MS; + while (Date.now() < deadline) { + if (child.exitCode !== null) throw new Error("OpenShell gateway exited before listening"); + const connected = await new Promise((resolve) => { + const socket = net.createConnection({ host: "127.0.0.1", port }); + socket.setTimeout(250); + socket.once("connect", () => { + socket.destroy(); + resolve(true); + }); + const finish = () => { + socket.destroy(); + resolve(false); + }; + socket.once("error", finish); + socket.once("timeout", finish); + }); + if (connected) return; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error(`OpenShell gateway did not listen within ${COMMAND_TIMEOUT_MS}ms`); +} + +async function freeLoopbackPort(): Promise { + return await new Promise((resolve, reject) => { + const server = net.createServer(); + server.unref(); + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + if (!address || typeof address === "string") { + server.close(); + reject(new Error("could not allocate a loopback port")); + return; + } + server.close((error) => (error ? reject(error) : resolve(address.port))); + }); + }); +} + +async function waitForFile(file: string, timeoutMs: number): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (fs.existsSync(file)) return true; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + return fs.existsSync(file); +} + +async function heartbeatStopped(file: string): Promise { + if (!fs.existsSync(file)) return true; + let last = fs.statSync(file).mtimeMs; + let stableSince = Date.now(); + const deadline = Date.now() + TERMINATION_TIMEOUT_MS; + while (Date.now() < deadline) { + await new Promise((resolve) => setTimeout(resolve, 500)); + const current = fs.existsSync(file) ? fs.statSync(file).mtimeMs : last; + if (current !== last) { + last = current; + stableSince = Date.now(); + } + if (Date.now() - stableSince >= 3000) return true; + } + return false; +} + +export function normalizeReportedVersion(output: string): string | null { + const normalized = output + .trim() + .replace(/^openclaw(?:\s+version)?\s+/iu, "") + .replace(/^v(?=[0-9])/u, ""); + return VERSION_PATTERN.test(normalized) ? normalized : null; +} + +export function assertCleanCheckoutIdentity(input: { + readonly expectedRevision: string; + readonly observedRevision: string; + readonly statusOutput: string; +}): void { + if (input.statusOutput.trim()) { + throw new Error("NemoClaw checkout must be clean for exact source identity"); + } + if (input.observedRevision !== input.expectedRevision) { + throw new Error("nemoClawRevision does not match the expected exact identity"); + } +} + +function assertCurrentCheckoutIdentity(expectedRevision: string): void { + const revision = spawnSync("git", ["rev-parse", "HEAD"], { + encoding: "utf8", + killSignal: "SIGKILL", + timeout: 10_000, + windowsHide: true, + }); + if (revision.status !== 0) { + throw new Error("could not resolve the NemoClaw checkout revision"); + } + const status = spawnSync("git", ["status", "--porcelain=v1", "--untracked-files=all"], { + encoding: "utf8", + killSignal: "SIGKILL", + timeout: 10_000, + windowsHide: true, + }); + if (status.status !== 0) throw new Error("could not inspect the NemoClaw checkout state"); + assertCleanCheckoutIdentity({ + expectedRevision, + observedRevision: revision.stdout.trim(), + statusOutput: status.stdout, + }); +} + +function readProcessId(file: string): number | null { + if (!fs.existsSync(file)) return null; + const value = fs.readFileSync(file, "utf8").trim(); + if (!/^[1-9][0-9]*$/u.test(value)) return null; + const processId = Number(value); + return Number.isSafeInteger(processId) ? processId : null; +} + +function nativeArchitecture(environment: NodeJS.ProcessEnv): "x64" | null { + const value = (environment.PROCESSOR_ARCHITEW6432 ?? environment.PROCESSOR_ARCHITECTURE ?? "") + .trim() + .toLowerCase(); + return value === "amd64" ? "x64" : null; +} + +function trustedWindowsSystemExecutable( + environment: NodeJS.ProcessEnv, + segments: readonly string[], + name: string, +): string { + const systemRoot = realDirectory(requiredEnvironment(environment, "SystemRoot"), "SystemRoot"); + return realRegularFile(path.join(systemRoot, ...segments), name); +} + +function assertExactFileIdentity(file: string, expectedSha256: string, name: string): void { + if (sha256File(file) !== expectedSha256) { + throw new Error(`${name} does not match the expected exact identity`); + } +} + +export function assertExactArtifactIdentities(inputs: WindowsMxcOpenClawQualificationInputs): void { + const observed = { + nodeSha256: sha256File(inputs.openClaw.nodePath), + openClawArtifactTreeSha256: sha256WindowsOpenClawArtifactTree(inputs.openClaw.root), + openClawEntrySha256: sha256File(inputs.openClaw.entryPath), + openShellCliSha256: sha256File(inputs.openShell.cliPath), + openShellGatewaySha256: sha256File(inputs.openShell.gatewayPath), + wxcExecSha256: sha256File(inputs.openShell.wxcExecPath), + }; + for (const [name, value] of Object.entries(observed)) { + if (value !== inputs.expected[name as keyof typeof observed]) { + throw new Error(`${name} does not match the expected exact identity`); + } + } +} + +function assertExactIdentities(inputs: WindowsMxcOpenClawQualificationInputs): void { + assertCurrentCheckoutIdentity(inputs.expected.nemoClawRevision); + assertExactArtifactIdentities(inputs); +} + +function receiptPasses(checks: QualificationChecks): boolean { + return Object.values(checks).every(Boolean); +} + +export async function runWindowsMxcOpenClawProcessContainerQualification( + inputs: WindowsMxcOpenClawQualificationInputs, + progress: QualificationProgress, + environment: NodeJS.ProcessEnv = process.env, +): Promise { + if (process.platform !== "win32" || nativeArchitecture(environment) !== "x64") { + throw new Error("Windows MXC OpenClaw qualification requires a native Windows x64 host"); + } + const host = assessWindowsMxcProcessContainerCandidate({ + platform: process.platform, + nativeArchitecture: "x64", + release: os.release(), + }); + if (!host.candidate) throw new Error(host.detail); + assertExactIdentities(inputs); + const powershellPath = trustedWindowsSystemExecutable( + environment, + ["System32", "WindowsPowerShell", "v1.0", "powershell.exe"], + "Windows PowerShell", + ); + const taskkillPath = trustedWindowsSystemExecutable( + environment, + ["System32", "taskkill.exe"], + "Windows taskkill", + ); + + assertExactArtifactIdentities(inputs); + const version = await runCommand( + inputs.openClaw.nodePath, + [inputs.openClaw.entryPath, "--version"], + environment, + progress, + "command: windows-mxc-openclaw-version", + ); + if ( + version.exitCode !== 0 || + normalizeReportedVersion(version.stdout) !== inputs.openClaw.version + ) { + throw new Error("OpenClaw runtime version does not match the expected identity"); + } + + const runId = randomBytes(4).toString("hex"); + const runRoot = fs.mkdtempSync(path.join(os.tmpdir(), `nemoclaw-mxc-openclaw-${runId}-`)); + const shareDirectory = path.join(runRoot, "share"); + const stateDirectory = path.join(runRoot, "state"); + const configDirectory = path.join(runRoot, "config"); + const homeDirectory = path.join(shareDirectory, "home"); + for (const directory of [shareDirectory, stateDirectory, configDirectory, homeDirectory]) { + fs.mkdirSync(directory, { recursive: true }); + } + + const agentPath = inputs.openClaw.nodePath; + const gatewayConfigPath = path.join(runRoot, "gateway.toml"); + const policyPath = path.join(runRoot, "policy.yaml"); + const probeAgentPath = path.join(shareDirectory, "probe-agent.mjs"); + const readyPath = path.join(shareDirectory, "ready.json"); + const resultPath = path.join(shareDirectory, "result.json"); + const outcomePath = path.join(shareDirectory, "outcome.json"); + const heartbeatPath = path.join(shareDirectory, "heartbeat.txt"); + const openClawPidPath = path.join(shareDirectory, "openclaw.pid"); + const stopPath = path.join(shareDirectory, "stop.txt"); + const denyPath = path.join(runRoot, "denied-write.txt"); + const gatewayLogPath = path.join(runRoot, "openshell-gateway.log"); + const gatewayErrorPath = path.join(runRoot, "openshell-gateway.err.log"); + const gatewayPort = await freeLoopbackPort(); + const openClawPort = await freeLoopbackPort(); + const sandboxName = `mxc-oc-${runId}`; + const gatewayName = `mxc-gw-${runId}`; + const token = randomBytes(32).toString("base64url"); + + fs.writeFileSync( + gatewayConfigPath, + renderWindowsMxcGatewayConfig({ + agentPath, + shareDirectory, + wxcExecPath: inputs.openShell.wxcExecPath, + }), + { encoding: "utf8", mode: 0o600 }, + ); + fs.writeFileSync( + policyPath, + renderWindowsMxcFilesystemPolicy({ + openClawRoot: inputs.openClaw.root, + shareDirectory, + }), + { encoding: "utf8", mode: 0o600 }, + ); + fs.writeFileSync(probeAgentPath, renderWindowsMxcOpenClawProbeAgent(), { + encoding: "utf8", + mode: 0o600, + }); + + const gatewayEnvironment: NodeJS.ProcessEnv = { + ...allowlistedWindowsProcessEnvironment(environment), + NEMOCLAW_MXC_E2E_DENY_PATH: denyPath, + NEMOCLAW_MXC_E2E_ENTRY: inputs.openClaw.entryPath, + NEMOCLAW_MXC_E2E_HEARTBEAT_PATH: heartbeatPath, + NEMOCLAW_MXC_E2E_HOME: homeDirectory, + NEMOCLAW_MXC_E2E_NODE: inputs.openClaw.nodePath, + NEMOCLAW_MXC_E2E_OPENCLAW_PORT: String(openClawPort), + NEMOCLAW_MXC_E2E_OPENCLAW_PID_PATH: openClawPidPath, + NEMOCLAW_MXC_E2E_OUTCOME_PATH: outcomePath, + NEMOCLAW_MXC_E2E_READY_PATH: readyPath, + NEMOCLAW_MXC_E2E_RESULT_PATH: resultPath, + NEMOCLAW_MXC_E2E_STOP_PATH: stopPath, + NEMOCLAW_MXC_E2E_TOKEN: token, + OPENSHELL_DRIVERS: "mxc", + OPENSHELL_GATEWAY: "", + OPENSHELL_GATEWAY_CONFIG: gatewayConfigPath, + XDG_CONFIG_HOME: configDirectory, + XDG_STATE_HOME: stateDirectory, + }; + const controlEnvironment: NodeJS.ProcessEnv = { + ...gatewayEnvironment, + NEMOCLAW_MXC_E2E_TOKEN: undefined, + }; + + const gatewayStdout = fs.openSync(gatewayLogPath, "w"); + const gatewayStderr = fs.openSync(gatewayErrorPath, "w"); + let gateway: ChildProcess | null = null; + let gatewayStopped = false; + let boundedStopMarkerNeeded = false; + let emergencyProcessTerminationNeeded = false; + let emergencyGatewayTerminationNeeded = false; + let openClawProcessStopped = false; + let runDirectoryRemoved = false; + let sandboxCreateStarted = false; + let sandboxDeleteRetried = false; + let sensitiveRuntimeArtifactsRemoved = false; + let openClawProcessId: number | null = null; + let trustedOpenClawProcess: TrustedOpenClawProcessIdentity | null = null; + let trustedGatewayProcess: WindowsProcessIdentity | null = null; + let primaryFailure: unknown = null; + const cleanupFailures: unknown[] = []; + let checks: QualificationChecks = { + artifactIdentity: true, + filesystemControlWrite: false, + filesystemDeniedWrite: false, + openClawHealth: false, + openClawProcessPresentWhileReady: false, + registryPresentWhileReady: false, + registryRemovedAfterDelete: false, + sandboxCreateAccepted: false, + sandboxDeleteAccepted: false, + workloadTerminatedByDelete: false, + }; + const runOpenShellCommand = async ( + args: readonly string[], + activityLabel: string, + timeoutMs = COMMAND_TIMEOUT_MS, + ): Promise => { + assertExactFileIdentity( + inputs.openShell.cliPath, + inputs.expected.openShellCliSha256, + "openShellCliSha256", + ); + return await runCommand( + inputs.openShell.cliPath, + args, + controlEnvironment, + progress, + activityLabel, + timeoutMs, + ); + }; + + try { + assertExactFileIdentity( + inputs.openShell.gatewayPath, + inputs.expected.openShellGatewaySha256, + "openShellGatewaySha256", + ); + gateway = spawnObservedChild( + inputs.openShell.gatewayPath, + [ + "--port", + String(gatewayPort), + "--disable-tls", + "--db-url", + "sqlite::memory:", + "--log-level", + "info", + ], + { + activityLabel: "command: windows-mxc-openshell-gateway", + progress, + spawn: { + cwd: path.dirname(inputs.openShell.gatewayPath), + env: gatewayEnvironment, + stdio: ["ignore", gatewayStdout, gatewayStderr], + windowsHide: true, + }, + }, + ); + await waitForPort(gatewayPort, gateway); + if (gateway.pid === undefined) throw new Error("OpenShell gateway did not report a process ID"); + trustedGatewayProcess = await observeWindowsProcessIdentity( + gateway.pid, + powershellPath, + controlEnvironment, + progress, + "command: windows-mxc-openshell-gateway-process-identity", + ); + if (trustedGatewayProcess === null) { + throw new Error("OpenShell gateway process identity is unavailable after readiness"); + } + assertExpectedOpenShellGatewayProcessIdentity(trustedGatewayProcess, { + gatewayPath: inputs.openShell.gatewayPath, + port: gatewayPort, + }); + + const add = await runOpenShellCommand( + ["gateway", "add", `http://127.0.0.1:${gatewayPort}`, "--local", "--name", gatewayName], + "command: windows-mxc-gateway-add", + ); + if (add.exitCode !== 0) throw new Error(`OpenShell gateway add failed: ${commandDetail(add)}`); + const select = await runOpenShellCommand( + ["gateway", "select", gatewayName], + "command: windows-mxc-gateway-select", + ); + if (select.exitCode !== 0) { + throw new Error(`OpenShell gateway select failed: ${commandDetail(select)}`); + } + + assertExactArtifactIdentities(inputs); + sandboxCreateStarted = true; + const create = await runOpenShellCommand( + [ + "sandbox", + "create", + "--name", + sandboxName, + "--policy", + policyPath, + "--no-tty", + "--", + "exit", + ], + "command: windows-mxc-sandbox-create", + READY_TIMEOUT_MS, + ); + if (create.exitCode !== 0) { + throw new Error(`OpenShell sandbox create failed: ${commandDetail(create)}`); + } + + await waitForFile(outcomePath, READY_TIMEOUT_MS); + const ready = fs.existsSync(readyPath); + const probeResult = fs.existsSync(resultPath) + ? (JSON.parse(fs.readFileSync(resultPath, "utf8")) as Record) + : {}; + openClawProcessId = readProcessId(openClawPidPath); + if (openClawProcessId !== null) { + trustedOpenClawProcess = await observeTrustedOpenClawProcessIdentity({ + entryPath: inputs.openClaw.entryPath, + environment: controlEnvironment, + nodePath: inputs.openClaw.nodePath, + port: openClawPort, + powershellPath, + probeAgentPath, + processId: openClawProcessId, + progress, + }); + } + const reportedVersion = + typeof probeResult.openClawVersion === "string" + ? normalizeReportedVersion(probeResult.openClawVersion) + : null; + checks = { + ...checks, + filesystemControlWrite: probeResult.controlWrite === true, + filesystemDeniedWrite: probeResult.deniedWrite === true && !fs.existsSync(denyPath), + openClawHealth: + ready && probeResult.healthObserved === true && reportedVersion === inputs.openClaw.version, + openClawProcessPresentWhileReady: trustedOpenClawProcess !== null, + }; + + const listWhileReady = await runOpenShellCommand( + ["sandbox", "list", "-o", "json"], + "command: windows-mxc-sandbox-list-ready", + ); + checks = { + ...checks, + registryPresentWhileReady: + listWhileReady.exitCode === 0 && + sandboxListContainsExactName(listWhileReady.stdout, sandboxName), + }; + checks = { + ...checks, + sandboxCreateAccepted: create.exitCode === 0, + }; + + progress.phase("delete the sandbox and verify registry plus OpenClaw process cleanup"); + const remove = await runOpenShellCommand( + ["sandbox", "delete", sandboxName], + "command: windows-mxc-sandbox-delete", + ); + checks = { ...checks, sandboxDeleteAccepted: remove.exitCode === 0 }; + checks = { + ...checks, + workloadTerminatedByDelete: + trustedOpenClawProcess !== null && + (await waitForTrustedProcessExit( + trustedOpenClawProcess.child, + powershellPath, + controlEnvironment, + progress, + )), + }; + + if (!checks.workloadTerminatedByDelete) { + boundedStopMarkerNeeded = true; + writeStopMarkerOnce(stopPath); + await heartbeatStopped(heartbeatPath); + } + + const listAfterDelete = await runOpenShellCommand( + ["sandbox", "list", "-o", "json"], + "command: windows-mxc-sandbox-list-deleted", + ); + checks = { + ...checks, + registryRemovedAfterDelete: + listAfterDelete.exitCode === 0 && + !sandboxListContainsExactName(listAfterDelete.stdout, sandboxName), + }; + } catch (error) { + primaryFailure = error; + } finally { + if (sandboxCreateStarted) { + let exactRegistryEntryPresent = true; + try { + const cleanupListBeforeRetry = await runOpenShellCommand( + ["sandbox", "list", "-o", "json"], + "command: windows-mxc-sandbox-list-before-cleanup", + ); + if (cleanupListBeforeRetry.exitCode === 0) { + exactRegistryEntryPresent = sandboxListContainsExactName( + cleanupListBeforeRetry.stdout, + sandboxName, + ); + checks = { ...checks, registryRemovedAfterDelete: !exactRegistryEntryPresent }; + } + } catch { + exactRegistryEntryPresent = true; + } + + if (shouldRetrySandboxDelete(checks.sandboxDeleteAccepted, exactRegistryEntryPresent)) { + sandboxDeleteRetried = true; + try { + const cleanupDelete = await runOpenShellCommand( + ["sandbox", "delete", sandboxName], + "command: windows-mxc-sandbox-delete-cleanup", + ); + checks = { ...checks, sandboxDeleteAccepted: cleanupDelete.exitCode === 0 }; + if (cleanupDelete.exitCode !== 0) { + cleanupFailures.push( + new Error(`cleanup sandbox delete failed: ${commandDetail(cleanupDelete)}`), + ); + } + } catch (error) { + cleanupFailures.push(error); + } + } + + try { + const cleanupList = await runOpenShellCommand( + ["sandbox", "list", "-o", "json"], + "command: windows-mxc-sandbox-list-cleanup", + ); + const registryRemovedAfterDelete = + cleanupList.exitCode === 0 && + !sandboxListContainsExactName(cleanupList.stdout, sandboxName); + checks = { + ...checks, + registryRemovedAfterDelete, + }; + if (!registryRemovedAfterDelete) { + cleanupFailures.push(new Error("exact sandbox registry entry remains after cleanup")); + } + } catch (error) { + cleanupFailures.push(error); + } + } + try { + writeStopMarkerOnce(stopPath); + await heartbeatStopped(heartbeatPath); + if ( + trustedOpenClawProcess !== null && + (await trustedProcessIsAlive( + trustedOpenClawProcess.child, + powershellPath, + controlEnvironment, + progress, + )) + ) { + emergencyProcessTerminationNeeded = true; + const terminate = await runCommand( + taskkillPath, + ["/PID", String(trustedOpenClawProcess.child.processId), "/T", "/F"], + controlEnvironment, + progress, + "command: windows-mxc-openclaw-emergency-termination", + ); + if ( + terminate.exitCode !== 0 && + (await trustedProcessIsAlive( + trustedOpenClawProcess.child, + powershellPath, + controlEnvironment, + progress, + )) + ) { + cleanupFailures.push( + new Error(`OpenClaw emergency termination failed: ${commandDetail(terminate)}`), + ); + } + } + openClawProcessStopped = + trustedOpenClawProcess === null + ? !sandboxCreateStarted + : await waitForTrustedProcessExit( + trustedOpenClawProcess.child, + powershellPath, + controlEnvironment, + progress, + ); + } catch (error) { + cleanupFailures.push(error); + } + try { + if (gateway && gateway.exitCode === null) { + gateway.kill(); + await Promise.race([ + new Promise((resolve) => gateway?.once("exit", resolve)), + new Promise((resolve) => setTimeout(resolve, 5000)), + ]); + } + if ( + trustedGatewayProcess !== null && + (await trustedProcessIsAlive( + trustedGatewayProcess, + powershellPath, + controlEnvironment, + progress, + )) + ) { + emergencyGatewayTerminationNeeded = true; + const terminateGateway = await runCommand( + taskkillPath, + ["/PID", String(trustedGatewayProcess.processId), "/T", "/F"], + controlEnvironment, + progress, + "command: windows-mxc-openshell-gateway-emergency-termination", + ); + if ( + terminateGateway.exitCode !== 0 && + (await trustedProcessIsAlive( + trustedGatewayProcess, + powershellPath, + controlEnvironment, + progress, + )) + ) { + cleanupFailures.push( + new Error( + `OpenShell gateway emergency termination failed: ${commandDetail(terminateGateway)}`, + ), + ); + } + } + gatewayStopped = + trustedGatewayProcess === null + ? gateway === null || gateway.exitCode !== null + : await waitForTrustedProcessExit( + trustedGatewayProcess, + powershellPath, + controlEnvironment, + progress, + ); + } catch (error) { + cleanupFailures.push(error); + } + gatewayEnvironment.NEMOCLAW_MXC_E2E_TOKEN = undefined; + for (const descriptor of [gatewayStdout, gatewayStderr]) { + try { + fs.closeSync(descriptor); + } catch (error) { + cleanupFailures.push(error); + } + } + const sensitivePaths = [ + homeDirectory, + configDirectory, + stateDirectory, + gatewayLogPath, + gatewayErrorPath, + ]; + for (const sensitivePath of sensitivePaths) { + try { + fs.rmSync(sensitivePath, { force: true, recursive: true }); + } catch (error) { + cleanupFailures.push(error); + } + } + sensitiveRuntimeArtifactsRemoved = sensitivePaths.every( + (sensitivePath) => !fs.existsSync(sensitivePath), + ); + } + + const lifecyclePassedBeforeDirectoryRemoval = + receiptPasses(checks) && + !boundedStopMarkerNeeded && + !emergencyProcessTerminationNeeded && + !emergencyGatewayTerminationNeeded && + !sandboxDeleteRetried && + gatewayStopped && + openClawProcessStopped && + sensitiveRuntimeArtifactsRemoved && + primaryFailure === null && + cleanupFailures.length === 0; + if (lifecyclePassedBeforeDirectoryRemoval) { + try { + fs.rmSync(runRoot, { force: true, recursive: true }); + runDirectoryRemoved = !fs.existsSync(runRoot); + if (!runDirectoryRemoved) { + cleanupFailures.push(new Error("qualification run directory remains after cleanup")); + } + } catch (error) { + cleanupFailures.push(error); + } + } + + const receipt: WindowsMxcOpenClawQualificationReceipt = { + schemaVersion: 1, + classification: "inactive-candidate", + backend: "process_container", + configuration: { + pcLeastPrivilege: true, + }, + identities: { + host: { + architecture: "x64", + platform: "win32", + release: os.release(), + }, + nemoClawRevision: inputs.expected.nemoClawRevision, + openClaw: { + artifactTreeSha256: inputs.expected.openClawArtifactTreeSha256, + entrySha256: inputs.expected.openClawEntrySha256, + nodeSha256: inputs.expected.nodeSha256, + version: inputs.openClaw.version, + }, + openShell: { + cliSha256: inputs.expected.openShellCliSha256, + gatewaySha256: inputs.expected.openShellGatewaySha256, + packageVersion: inputs.openShell.packageVersion, + revision: inputs.openShell.revision, + }, + wxcExecSha256: inputs.expected.wxcExecSha256, + }, + checks, + cleanup: { + boundedStopMarkerNeeded, + emergencyProcessTerminationNeeded, + emergencyGatewayTerminationNeeded, + gatewayProcessStopped: gatewayStopped, + openClawProcessStopped, + runDirectoryRemoved, + sandboxDeleteRetried, + sensitiveRuntimeArtifactsRemoved, + }, + verdict: + lifecyclePassedBeforeDirectoryRemoval && runDirectoryRemoved && cleanupFailures.length === 0 + ? "pass" + : "fail", + deferred: [ + "gateway-mtls", + "managed-inference", + "governed-egress", + "gateway-restart-recovery", + "production-activation", + ], + }; + + const receiptPath = path.join( + inputs.artifactDirectory, + `windows-mxc-openclaw-receipt-${runId}.json`, + ); + fs.writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, { + encoding: "utf8", + flag: "wx", + mode: 0o600, + }); + if (receipt.verdict === "pass") { + return receipt; + } + const failures = [primaryFailure, ...cleanupFailures].filter( + (failure): failure is NonNullable => failure !== null, + ); + throw new AggregateError( + failures, + `Windows MXC OpenClaw qualification failed; cleanup sandbox delete retried=${sandboxDeleteRetried}, OpenClaw stopped=${openClawProcessStopped}; receipt: ${receiptPath}`, + ); +} diff --git a/test/e2e/live/windows-mxc-openclaw-process-container.test.ts b/test/e2e/live/windows-mxc-openclaw-process-container.test.ts new file mode 100644 index 00000000000..4483a44924c --- /dev/null +++ b/test/e2e/live/windows-mxc-openclaw-process-container.test.ts @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { expect, test } from "../fixtures/e2e-test.ts"; +import { + parseWindowsMxcOpenClawQualificationEnvironment, + runWindowsMxcOpenClawProcessContainerQualification, +} from "./windows-mxc-openclaw-process-container-helpers.ts"; + +const qualificationTest = + process.env.NEMOCLAW_RUN_WINDOWS_MXC_OPENCLAW_E2E === "1" ? test : test.skip; + +qualificationTest( + "qualifies the inactive native OpenClaw process_container candidate through OpenShell (#8178)", + { + timeout: 8 * 60_000, + meta: { + e2ePhases: [ + "qualify the Windows host and validate exact artifact identities", + "start OpenClaw and verify in-sandbox readiness plus filesystem enforcement", + "delete the sandbox and verify registry plus OpenClaw process cleanup", + ], + }, + }, + async ({ progress }) => { + progress.phase("qualify the Windows host and validate exact artifact identities"); + const inputs = parseWindowsMxcOpenClawQualificationEnvironment(process.env); + + progress.phase("start OpenClaw and verify in-sandbox readiness plus filesystem enforcement"); + const receipt = await runWindowsMxcOpenClawProcessContainerQualification(inputs, progress); + + expect(receipt.verdict).toBe("pass"); + expect(receipt.configuration).toEqual({ pcLeastPrivilege: true }); + expect(receipt.cleanup).toEqual({ + boundedStopMarkerNeeded: false, + emergencyGatewayTerminationNeeded: false, + emergencyProcessTerminationNeeded: false, + gatewayProcessStopped: true, + openClawProcessStopped: true, + runDirectoryRemoved: true, + sandboxDeleteRetried: false, + sensitiveRuntimeArtifactsRemoved: true, + }); + }, +); diff --git a/test/e2e/mock-parity.json b/test/e2e/mock-parity.json index 35ad66037f4..bd85ff6238f 100644 --- a/test/e2e/mock-parity.json +++ b/test/e2e/mock-parity.json @@ -583,6 +583,13 @@ "test/e2e/support/e2e-semantic-phase-check.test.ts", "test/e2e/support/workflow-e2e-progress.test.ts" ] + }, + { + "live": "test/e2e/live/windows-mxc-openclaw-process-container.test.ts", + "fast": [ + "test/e2e/support/e2e-semantic-phase-check.test.ts", + "test/e2e/support/windows-mxc-openclaw-process-container.test.ts" + ] } ] } diff --git a/test/e2e/support/e2e-semantic-phase-check.test.ts b/test/e2e/support/e2e-semantic-phase-check.test.ts index 4e3b2066041..217dcb9f93e 100644 --- a/test/e2e/support/e2e-semantic-phase-check.test.ts +++ b/test/e2e/support/e2e-semantic-phase-check.test.ts @@ -12,6 +12,7 @@ import { semanticPhaseCoverageModules, validateCollectedSemanticPhaseModule, validateTestScopedPhaseCalls, + validateWindowsMxcControlBoundarySource, } from "../../../tools/e2e/check-semantic-phases.mts"; import { REPO_ROOT } from "../fixtures/paths.ts"; @@ -31,6 +32,48 @@ const TEST_PROGRESS_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/progress.ts const FAKE_OPENAI_SOURCE = path.join(REPO_ROOT, "test/e2e/fixtures/fake-openai-compatible.ts"); describe("semantic E2E phase checker", () => { + test("accepts formatted OpenShell create-then-delete control flow for Windows MXC", () => { + const source = ` + async function qualify(runOpenShellCommand, sandboxName) { + await runOpenShellCommand(["sandbox", "create", "--name", sandboxName], "create"); + await runOpenShellCommand( + ["sandbox", "delete", sandboxName], + "delete", + ); + } + `; + + expect(validateWindowsMxcControlBoundarySource(source)).toEqual([]); + }); + + test("rejects direct wxc-exec control and delete-before-create for Windows MXC", () => { + const source = ` + async function qualify(cli, env, progress, sandboxName, wxcExecPath) { + await runCommand(cli, ["sandbox", "delete", sandboxName], env, progress, "delete"); + spawnObservedChild(wxcExecPath, ["run"], { progress }); + await runCommand(cli, ["sandbox", "create"], env, progress, "create"); + } + `; + + expect(validateWindowsMxcControlBoundarySource(source)).toEqual([ + "wxc-exec must not be invoked outside the OpenShell control boundary", + "OpenShell sandbox delete must not run before sandbox create", + ]); + }); + + test("rejects a Windows MXC control flow without sandbox lifecycle commands", () => { + const source = ` + async function qualify(cli, env, progress) { + await runCommand(cli, ["gateway", "select", "name"], env, progress, "select"); + } + `; + + expect(validateWindowsMxcControlBoundarySource(source)).toEqual([ + "OpenShell sandbox create command is missing", + "OpenShell sandbox delete command is missing", + ]); + }); + // source-shape-contract: compatibility -- Generated policy output must precede semantic collection and remain shared with the canonical CLI build test("builds the policy boundary before semantic collection and CLI compilation", () => { const scripts = ( diff --git a/test/e2e/support/windows-mxc-openclaw-process-container.test.ts b/test/e2e/support/windows-mxc-openclaw-process-container.test.ts new file mode 100644 index 00000000000..d66e544d30e --- /dev/null +++ b/test/e2e/support/windows-mxc-openclaw-process-container.test.ts @@ -0,0 +1,348 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import net from "node:net"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; +import { sha256WindowsOpenClawArtifactTree } from "../../../tools/e2e/windows-mxc-openclaw-artifact-tree.mts"; +import { + allowlistedWindowsProcessEnvironment, + assertCleanCheckoutIdentity, + assertExactArtifactIdentities, + assertExpectedOpenClawProcessIdentity, + assertExpectedOpenShellGatewayProcessIdentity, + normalizeReportedVersion, + parseWindowsMxcOpenClawQualificationEnvironment, + parseWindowsProcessQueryResult, + renderWindowsMxcFilesystemPolicy, + renderWindowsMxcGatewayConfig, + renderWindowsMxcOpenClawProbeAgent, + sameWindowsProcessIdentity, + sandboxListContainsExactName, + sha256File, + shouldRetrySandboxDelete, +} from "../live/windows-mxc-openclaw-process-container-helpers.ts"; + +const roots: string[] = []; + +function fixture(): { readonly environment: NodeJS.ProcessEnv; readonly root: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-mxc-contract-")); + roots.push(root); + const artifactDirectory = path.join(root, "evidence"); + const openClawRoot = path.join(root, "openclaw"); + fs.mkdirSync(artifactDirectory, { recursive: true }); + fs.mkdirSync(path.join(openClawRoot, "node"), { recursive: true }); + fs.mkdirSync(path.join(openClawRoot, "runtime"), { recursive: true }); + const paths = { + cli: path.join(root, "openshell.exe"), + entry: path.join(openClawRoot, "runtime", "openclaw.mjs"), + gateway: path.join(root, "openshell-gateway.exe"), + node: path.join(openClawRoot, "node", "node.exe"), + wxc: path.join(root, "wxc-exec.exe"), + }; + for (const [name, file] of Object.entries(paths)) fs.writeFileSync(file, name, "utf8"); + return { + root, + environment: { + E2E_ARTIFACT_DIR: artifactDirectory, + NEMOCLAW_E2E_EXPECTED_SHA: "a".repeat(40), + NEMOCLAW_WINDOWS_MXC_NODE: paths.node, + NEMOCLAW_WINDOWS_MXC_NODE_SHA256: sha256File(paths.node), + NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY: paths.entry, + NEMOCLAW_WINDOWS_MXC_OPENCLAW_ENTRY_SHA256: sha256File(paths.entry), + NEMOCLAW_WINDOWS_MXC_OPENCLAW_ARTIFACT_TREE_SHA256: + sha256WindowsOpenClawArtifactTree(openClawRoot), + NEMOCLAW_WINDOWS_MXC_OPENCLAW_ROOT: openClawRoot, + NEMOCLAW_WINDOWS_MXC_OPENCLAW_VERSION: "2026.7.1", + NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI: paths.cli, + NEMOCLAW_WINDOWS_MXC_OPENSHELL_CLI_SHA256: sha256File(paths.cli), + NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY: paths.gateway, + NEMOCLAW_WINDOWS_MXC_OPENSHELL_GATEWAY_SHA256: sha256File(paths.gateway), + NEMOCLAW_WINDOWS_MXC_OPENSHELL_REVISION: "b".repeat(40), + NEMOCLAW_WINDOWS_MXC_OPENSHELL_VERSION: "0.0.12", + NEMOCLAW_WINDOWS_MXC_WXC_EXEC: paths.wxc, + NEMOCLAW_WINDOWS_MXC_WXC_EXEC_SHA256: sha256File(paths.wxc), + }, + }; +} + +afterEach(() => { + for (const root of roots.splice(0)) fs.rmSync(root, { force: true, recursive: true }); +}); + +describe("inactive Windows MXC OpenClaw process_container qualification", () => { + it("requires exact identities and keeps the OpenClaw launch files under one artifact root (#8178)", () => { + const { environment } = fixture(); + const parsed = parseWindowsMxcOpenClawQualificationEnvironment(environment); + + expect(parsed.openClaw.version).toBe("2026.7.1"); + expect(parsed.openShell.packageVersion).toBe("0.0.12"); + expect(parsed.expected.openClawArtifactTreeSha256).toBe( + environment.NEMOCLAW_WINDOWS_MXC_OPENCLAW_ARTIFACT_TREE_SHA256, + ); + expect(parsed.expected.wxcExecSha256).toBe(environment.NEMOCLAW_WINDOWS_MXC_WXC_EXEC_SHA256); + }); + + it("rejects an OpenClaw executable outside the staged artifact root (#8178)", () => { + const { environment, root } = fixture(); + const outside = path.join(root, "outside-node.exe"); + fs.writeFileSync(outside, "node", "utf8"); + environment.NEMOCLAW_WINDOWS_MXC_NODE = outside; + environment.NEMOCLAW_WINDOWS_MXC_NODE_SHA256 = sha256File(outside); + + expect(() => parseWindowsMxcOpenClawQualificationEnvironment(environment)).toThrow( + /must be a child of the OpenClaw artifact root/u, + ); + }); + + it("rejects moving aliases instead of exact digest and revision identities (#8178)", () => { + const { environment } = fixture(); + environment.NEMOCLAW_WINDOWS_MXC_OPENSHELL_REVISION = "main"; + environment.NEMOCLAW_WINDOWS_MXC_WXC_EXEC_SHA256 = "latest"; + + expect(() => parseWindowsMxcOpenClawQualificationEnvironment(environment)).toThrow( + /unsupported format/u, + ); + }); + + it("rejects an artifact replaced after its initial identity check (#8178)", () => { + const { environment } = fixture(); + const parsed = parseWindowsMxcOpenClawQualificationEnvironment(environment); + assertExactArtifactIdentities(parsed); + + fs.writeFileSync(parsed.openShell.cliPath, "replacement", "utf8"); + + expect(() => assertExactArtifactIdentities(parsed)).toThrow( + /openShellCliSha256 does not match the expected exact identity/u, + ); + }); + + it("rejects dirty source identity and version-prefix matches (#8178)", () => { + expect(() => + assertCleanCheckoutIdentity({ + expectedRevision: "a".repeat(40), + observedRevision: "a".repeat(40), + statusOutput: " M test/e2e/README.md\n", + }), + ).toThrow(/must be clean/u); + expect(() => + assertCleanCheckoutIdentity({ + expectedRevision: "a".repeat(40), + observedRevision: "b".repeat(40), + statusOutput: "", + }), + ).toThrow(/does not match/u); + expect(normalizeReportedVersion("OpenClaw 2026.7.1\n")).toBe("2026.7.1"); + expect(normalizeReportedVersion("2026.7.10\n")).toBe("2026.7.10"); + expect(normalizeReportedVersion("OpenClaw version 2026.7.1 extra\n")).toBeNull(); + }); + + it("matches exact registry names and identifies when delete needs a retry (#8178)", () => { + expect(sandboxListContainsExactName('[{"name":"mxc-oc-123-extra"}]', "mxc-oc-123")).toBe(false); + expect(sandboxListContainsExactName('[{"name":"mxc-oc-123"}]', "mxc-oc-123")).toBe(true); + expect(shouldRetrySandboxDelete(true, true)).toBe(true); + expect(shouldRetrySandboxDelete(true, false)).toBe(false); + }); + + it("compares the complete Windows process identity (#8178)", () => { + const child = { + commandLine: '"C:\\artifact\\node.exe" "C:\\artifact\\openclaw.mjs" gateway run --port 23456', + creationDate: "20260804180001.000000-420", + executablePath: "C:\\artifact\\node.exe", + parentProcessId: 41, + processId: 42, + }; + expect( + sameWindowsProcessIdentity(child, { + ...child, + creationDate: "20260804180002.000000-420", + }), + ).toBe(false); + }); + + it("accepts only the expected OpenClaw child and parent command identities (#8178)", () => { + const parent = { + commandLine: '"C:\\artifact\\node.exe" "C:\\probe\\probe-agent.mjs"', + creationDate: "20260804180000.000000-420", + executablePath: "C:\\artifact\\node.exe", + parentProcessId: 40, + processId: 41, + }; + const child = { + commandLine: '"C:\\artifact\\node.exe" "C:\\artifact\\openclaw.mjs" gateway run --port 23456', + creationDate: "20260804180001.000000-420", + executablePath: "C:\\artifact\\node.exe", + parentProcessId: 41, + processId: 42, + }; + expect(() => + assertExpectedOpenClawProcessIdentity( + { child, parent }, + { + entryPath: "C:\\artifact\\openclaw.mjs", + nodePath: "C:\\artifact\\node.exe", + port: 23456, + probeAgentPath: "C:\\probe\\probe-agent.mjs", + }, + ), + ).not.toThrow(); + expect(() => + assertExpectedOpenClawProcessIdentity( + { child: { ...child, executablePath: "C:\\Windows\\System32\\svchost.exe" }, parent }, + { + entryPath: "C:\\artifact\\openclaw.mjs", + nodePath: "C:\\artifact\\node.exe", + port: 23456, + probeAgentPath: "C:\\probe\\probe-agent.mjs", + }, + ), + ).toThrow(/does not match/u); + expect(() => + assertExpectedOpenClawProcessIdentity( + { + child: { + ...child, + commandLine: + '"C:\\artifact\\node.exe" "C:\\artifact\\openclaw.mjs.extra" gateway run --port 23456', + }, + parent, + }, + { + entryPath: "C:\\artifact\\openclaw.mjs", + nodePath: "C:\\artifact\\node.exe", + port: 23456, + probeAgentPath: "C:\\probe\\probe-agent.mjs", + }, + ), + ).toThrow(/does not match/u); + }); + + it("requires the OpenShell gateway path and ordered port argument pair (#8178)", () => { + const identity = { + commandLine: '"C:\\package\\openshell-gateway.exe" --port 17670 --disable-tls', + creationDate: "20260804180000.000000-420", + executablePath: "C:\\package\\openshell-gateway.exe", + parentProcessId: 40, + processId: 41, + }; + expect(() => + assertExpectedOpenShellGatewayProcessIdentity(identity, { + gatewayPath: "C:\\package\\openshell-gateway.exe", + port: 17670, + }), + ).not.toThrow(); + expect(() => + assertExpectedOpenShellGatewayProcessIdentity( + { + ...identity, + commandLine: '"C:\\package\\openshell-gateway.exe" --disable-tls 17670 --port', + }, + { gatewayPath: "C:\\package\\openshell-gateway.exe", port: 17670 }, + ), + ).toThrow(/does not match/u); + }); + + it("renders a gateway-scoped process_container probe without credential values (#8178)", () => { + const config = renderWindowsMxcGatewayConfig({ + agentPath: "C:\\artifact\\node.exe", + shareDirectory: "C:\\probe\\share", + wxcExecPath: "C:\\package\\wxc-exec.exe", + }); + + expect(config).toContain('backend = "process_container"'); + expect(config).toContain("pc_least_privilege = true"); + expect(config).toContain('"NEMOCLAW_MXC_E2E_TOKEN"'); + expect(config).not.toContain("credential-value"); + expect(config).not.toContain("--token"); + }); + + it("grants the artifact read-only and only the probe share read-write (#8178)", () => { + const policy = renderWindowsMxcFilesystemPolicy({ + openClawRoot: "C:\\artifact", + shareDirectory: "C:\\probe\\share", + }); + + expect(policy).toContain('read_only:\n - "C:/artifact"'); + expect(policy).toContain('read_write:\n - "C:/probe/share"'); + expect(policy).toContain("include_workdir: false"); + }); + + it("keeps the ephemeral readiness token out of OpenClaw arguments and source literals (#8178)", () => { + const agent = renderWindowsMxcOpenClawProbeAgent(); + + expect(agent).toContain('required("NEMOCLAW_MXC_E2E_TOKEN")'); + expect(agent).toContain("if (gateway.pid !== undefined)"); + expect(agent).toContain('gateway.once("error"'); + expect(agent).toContain("writeFileSync(outcomePath"); + expect(agent).toContain('"gateway",\n "health"'); + expect(agent).not.toContain('"--token"'); + expect(agent).not.toMatch(/[A-Za-z0-9_-]{40,}/u); + }); + + it("passes only allowlisted Windows runtime variables to host child processes (#8178)", () => { + const allowed = allowlistedWindowsProcessEnvironment({ + AWS_SECRET_ACCESS_KEY: "secret", + Path: "C:\\Windows\\System32", + SystemRoot: "C:\\Windows", + UNRELATED_CREDENTIAL: "secret", + }); + + expect(allowed).toEqual({ Path: "C:\\Windows\\System32", SystemRoot: "C:\\Windows" }); + }); + + it("fails closed when a Windows process query fails without output (#8178)", () => { + expect(() => + parseWindowsProcessQueryResult({ exitCode: 1, stderr: "query failed", stdout: "" }), + ).toThrow(/query failed/u); + expect(parseWindowsProcessQueryResult({ exitCode: 3, stderr: "", stdout: "" })).toBeNull(); + }); + + it("changes the artifact digest when file content or relative paths change (#8178)", () => { + const { root } = fixture(); + const artifact = path.join(root, "digest-artifact"); + fs.mkdirSync(artifact); + const first = path.join(artifact, "first.txt"); + fs.writeFileSync(first, "one", "utf8"); + const initial = sha256WindowsOpenClawArtifactTree(artifact); + fs.writeFileSync(first, "two", "utf8"); + const contentChanged = sha256WindowsOpenClawArtifactTree(artifact); + fs.renameSync(first, path.join(artifact, "second.txt")); + const pathChanged = sha256WindowsOpenClawArtifactTree(artifact); + + expect(contentChanged).not.toBe(initial); + expect(pathChanged).not.toBe(contentChanged); + }); + + it("rejects links in the OpenClaw artifact tree (#8178)", () => { + const { root } = fixture(); + const artifact = path.join(root, "linked-artifact"); + fs.mkdirSync(artifact); + const target = path.join(artifact, "target.txt"); + fs.writeFileSync(target, "content", "utf8"); + fs.symlinkSync(target, path.join(artifact, "link.txt")); + + expect(() => sha256WindowsOpenClawArtifactTree(artifact)).toThrow(/must not contain links/u); + }); + + it.runIf(process.platform !== "win32")( + "rejects unsupported entries in the OpenClaw artifact tree (#8178)", + async () => { + const artifact = fs.mkdtempSync(path.join("/tmp", "nemoclaw-mxc-socket-")); + roots.push(artifact); + const socketPath = path.join(artifact, "runtime.sock"); + const server = net.createServer(); + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(socketPath, resolve); + }); + try { + expect(() => sha256WindowsOpenClawArtifactTree(artifact)).toThrow(/unsupported file type/u); + } finally { + await new Promise((resolve) => server.close(() => resolve())); + } + }, + ); +}); diff --git a/tools/e2e/check-semantic-phases.mts b/tools/e2e/check-semantic-phases.mts index 58c7887d063..8dc8bfcc0df 100644 --- a/tools/e2e/check-semantic-phases.mts +++ b/tools/e2e/check-semantic-phases.mts @@ -95,6 +95,8 @@ const E2E_ROOT = path.join(REPO_ROOT, "test", "e2e"); const E2E_PROCESS_ROOTS = [E2E_ROOT, path.join(REPO_ROOT, "tools", "e2e")]; const E2E_RUNTIME_OBSERVABILITY_FILES = [path.join(E2E_ROOT, "risk-signal-reporter.ts")]; const REGISTRY_TARGET_TEST = "test/e2e/live/registry-targets.test.ts"; +const WINDOWS_MXC_OPENCLAW_HELPER = + "test/e2e/live/windows-mxc-openclaw-process-container-helpers.ts"; const LIVE_TEST_FORWARDERS = new Map([ ["test/e2e/live/bootstrap-install-smoke.test.ts", "test/e2e/live/launchable-smoke.test.ts"], ]); @@ -107,6 +109,99 @@ type SemanticPhaseWorkflowPlan = { }; type SemanticPhaseWorkflowInventory = Pick; +export function validateWindowsMxcControlBoundarySource(source: string): string[] { + const sourceFile = ts.createSourceFile( + WINDOWS_MXC_OPENCLAW_HELPER, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TS, + ); + const failures: string[] = []; + const controlCalls = new Set([ + "exec", + "execFile", + "execFileSync", + "execSync", + "runCommand", + "spawn", + "spawnObservedChild", + "spawnSync", + ]); + let createPosition: number | null = null; + const deletePositions: number[] = []; + + function containsWxcExecPath(node: ts.Node): boolean { + let found = false; + function inspect(candidate: ts.Node): void { + if ( + (ts.isIdentifier(candidate) && candidate.text === "wxcExecPath") || + (ts.isPropertyAccessExpression(candidate) && candidate.name.text === "wxcExecPath") + ) { + found = true; + return; + } + ts.forEachChild(candidate, inspect); + } + inspect(node); + return found; + } + + function invokedName(expression: ts.Expression): string | null { + if (ts.isIdentifier(expression)) return expression.text; + if (ts.isPropertyAccessExpression(expression)) return expression.name.text; + return null; + } + + function commandKind(node: ts.CallExpression): "create" | "delete" | null { + const name = invokedName(node.expression); + if (name !== "runCommand" && name !== "runOpenShellCommand") return null; + const args = name === "runCommand" ? node.arguments[1] : node.arguments[0]; + if (!args || !ts.isArrayLiteralExpression(args) || args.elements.length < 2) return null; + const [scope, action, target] = args.elements; + if (!ts.isStringLiteralLike(scope) || scope.text !== "sandbox") return null; + if (!ts.isStringLiteralLike(action)) return null; + if (action.text === "create") return "create"; + if ( + action.text === "delete" && + target !== undefined && + ts.isIdentifier(target) && + target.text === "sandboxName" + ) { + return "delete"; + } + return null; + } + + function inspect(node: ts.Node): void { + if (ts.isCallExpression(node)) { + // This deliberately broad source-level guard uses textual positions. It is + // not a runtime control-flow proof, and any wxcExecPath use in a process + // invocation subtree is rejected conservatively. + const name = invokedName(node.expression); + if (name && controlCalls.has(name) && node.arguments.some(containsWxcExecPath)) { + failures.push("wxc-exec must not be invoked outside the OpenShell control boundary"); + } + const kind = commandKind(node); + if (kind === "create" && createPosition === null) createPosition = node.getStart(sourceFile); + if (kind === "delete") deletePositions.push(node.getStart(sourceFile)); + } + ts.forEachChild(node, inspect); + } + inspect(sourceFile); + + if (createPosition === null) failures.push("OpenShell sandbox create command is missing"); + if (deletePositions.length === 0) failures.push("OpenShell sandbox delete command is missing"); + const observedCreatePosition = createPosition; + if ( + observedCreatePosition !== null && + deletePositions.some((position) => position < observedCreatePosition) + ) { + failures.push("OpenShell sandbox delete must not run before sandbox create"); + } + return [...new Set(failures)]; +} + function credentialFreeProjectForWorkflowFile( file: string, testMatrix: readonly CredentialFreeTestMatrixRow[], @@ -282,6 +377,14 @@ const OBSERVED_CHILD_PROGRESS_POLICIES = new Map `${relativeFile}: ${failure}`, + ), + ); + } directChildProcessCalls.push( ...collectDirectChildProcessCalls(file, sourceFile, childProcessAuditFailures), ); diff --git a/tools/e2e/windows-mxc-openclaw-artifact-tree.mts b/tools/e2e/windows-mxc-openclaw-artifact-tree.mts new file mode 100644 index 00000000000..d5f2211e945 --- /dev/null +++ b/tools/e2e/windows-mxc-openclaw-artifact-tree.mts @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const MAX_ARTIFACT_FILES = 100_000; + +export function sha256File(file: string): string { + return createHash("sha256").update(fs.readFileSync(file)).digest("hex"); +} + +export function sha256WindowsOpenClawArtifactTree(root: string): string { + const realRoot = fs.realpathSync(root); + const rootStatus = fs.lstatSync(realRoot); + if (!rootStatus.isDirectory() || rootStatus.isSymbolicLink()) { + throw new Error("OpenClaw artifact root must be a directory, not a link"); + } + + const files: string[] = []; + const pending = [realRoot]; + while (pending.length > 0) { + const directory = pending.pop(); + if (!directory) break; + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + const candidate = path.join(directory, entry.name); + const status = fs.lstatSync(candidate); + if (status.isSymbolicLink()) { + throw new Error("OpenClaw artifact tree must not contain links"); + } + if (status.isDirectory()) pending.push(candidate); + else if (status.isFile()) files.push(candidate); + else throw new Error("OpenClaw artifact tree contains an unsupported file type"); + if (files.length > MAX_ARTIFACT_FILES) { + throw new Error("OpenClaw artifact tree exceeds its file bound"); + } + } + } + + files.sort((a, b) => { + const left = path.relative(realRoot, a).split(path.sep).join("/"); + const right = path.relative(realRoot, b).split(path.sep).join("/"); + return left < right ? -1 : left > right ? 1 : 0; + }); + const digest = createHash("sha256"); + for (const file of files) { + const relative = path.relative(realRoot, file).split(path.sep).join("/"); + digest.update(relative, "utf8"); + digest.update("\0", "utf8"); + digest.update(sha256File(file), "utf8"); + digest.update("\n", "utf8"); + } + return digest.digest("hex"); +} + +function main(): void { + const root = process.argv[2]; + if (!root || process.argv.length !== 3) { + throw new Error("usage: windows-mxc-openclaw-artifact-tree.mts "); + } + process.stdout.write(`${sha256WindowsOpenClawArtifactTree(root)}\n`); +} + +if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) main();