Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions test/e2e-scenario/framework-tests/e2e-shell-supervisor.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

/**
* Focused unit tests for the shared shell supervisor + trusted-command
* modules. The headline guarantees of the consolidation are:
*
* 1. Every TS spawn site reaches the same NUL-byte argv guard.
* 2. Every TS spawn site reaches the same process-group cleanup
* with SIGTERM -> SIGKILL escalation, so a bash child that
* ignores SIGTERM (e.g. `trap "" TERM`) still dies on timeout.
*
* Both come from the leaf modules under framework/shell/, so the
* assertions live here at the leaf level. The end-to-end behaviour
* (orchestrator log redaction, fixture artifact persistence, probe
* outcome mapping) stays covered by the existing framework-tests
* (e2e-phase-orchestrators, e2e-fixture-context).
*/

import { spawn } from "node:child_process";
import { describe, expect, it } from "vitest";

import { superviseChild } from "../framework/shell/supervisor.ts";
import {
trustedShellCommand,
validateShellToken,
} from "../framework/shell/trusted-command.ts";

const NUL = String.fromCharCode(0);

describe("framework/shell/trusted-command", () => {
it("validateShellToken rejects NUL bytes with a labelled error", () => {
expect(() => validateShellToken(`a${NUL}b`, "argv[0]")).toThrowError(
/argv\[0\] cannot contain NUL bytes/,
);
});

it("validateShellToken passes a clean token through unchanged", () => {
expect(validateShellToken("bash", "command")).toBe("bash");
});

it("trustedShellCommand rejects NUL bytes in the command", () => {
expect(() =>
trustedShellCommand({ command: `ba${NUL}sh`, reason: "test" }),
).toThrowError(/command cannot contain NUL bytes/);
});

it("trustedShellCommand rejects NUL bytes in arguments", () => {
expect(() =>
trustedShellCommand({ command: "bash", args: [`x${NUL}y`], reason: "test" }),
).toThrowError(/argument cannot contain NUL bytes/);
});

it("trustedShellCommand requires a non-empty reason", () => {
expect(() => trustedShellCommand({ command: "bash", reason: " " })).toThrowError(
/reason is required/,
);
});

it("trustedShellCommand runs the caller's validate hook", () => {
expect(() =>
trustedShellCommand({
command: "bash",
args: ["-c", "echo hi"],
reason: "test",
validate: (_cmd, args) => {
if (args.includes("-c")) throw new Error("bash -c is forbidden here");
},
}),
).toThrowError(/bash -c is forbidden here/);
});
});

describe("framework/shell/supervisor", () => {
it("returns exitCode 0 when the child exits cleanly", async () => {
const child = spawn("bash", ["-c", "exit 0"], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
const result = await superviseChild(child, { timeoutMs: 5_000 });
expect(result).toMatchObject({ exitCode: 0, signal: null, timedOut: false });
expect(result.spawnError).toBeUndefined();
});

it("returns the child's non-zero exit code verbatim", async () => {
const child = spawn("bash", ["-c", "exit 7"], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
const result = await superviseChild(child, { timeoutMs: 5_000 });
expect(result.exitCode).toBe(7);
expect(result.timedOut).toBe(false);
});

it("captures stdout and stderr via the chunk callbacks", async () => {
const out: string[] = [];
const err: string[] = [];
const child = spawn("bash", ["-c", "echo to-stdout; echo to-stderr >&2"], {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
});
await superviseChild(child, {
timeoutMs: 5_000,
onStdout: (chunk) => out.push(chunk),
onStderr: (chunk) => err.push(chunk),
});
expect(out.join("")).toMatch(/to-stdout/);
expect(err.join("")).toMatch(/to-stderr/);
});

it("flags timedOut and kills the process group when the child ignores SIGTERM", async () => {
// The trap installs an empty SIGTERM handler, so a plain
// child.kill(SIGTERM) on the leader would never terminate the
// group. Without the supervisor's SIGKILL escalation the test
// would hang up to its outer timeout instead of resolving.
const script = 'trap "" TERM; sleep 30 & wait';
const child = spawn("bash", ["-c", script], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
const startedAt = Date.now();
const result = await superviseChild(child, { timeoutMs: 200, killGraceMs: 200 });
const elapsed = Date.now() - startedAt;
expect(result.timedOut).toBe(true);
// killGraceMs + a small scheduling margin; if escalation never
// ran this would take ~30 seconds.
expect(elapsed).toBeLessThan(5_000);
expect(result.signal === "SIGKILL" || result.exitCode !== 0).toBe(true);
});

it("honors an AbortSignal without flagging the run as a timeout", async () => {
const controller = new AbortController();
const child = spawn("bash", ["-c", "sleep 10"], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
setTimeout(() => controller.abort(), 50).unref();
const result = await superviseChild(child, {
timeoutMs: 10_000,
killGraceMs: 200,
signal: controller.signal,
});
expect(result.timedOut).toBe(false);
expect(result.exitCode === null || result.exitCode !== 0).toBe(true);
});

it("surfaces spawn errors via spawnError instead of a numeric exit", async () => {
const child = spawn("definitely-not-a-real-binary-xyz", [], {
detached: true,
stdio: ["ignore", "pipe", "pipe"],
});
const result = await superviseChild(child, { timeoutMs: 5_000 });
expect(result.spawnError).toBeDefined();
expect(result.exitCode).toBeNull();
});

it("feeds stdin to the child when stdio[0] is piped", async () => {
const out: string[] = [];
const child = spawn("bash", ["-c", "cat"], { detached: true, stdio: ["pipe", "pipe", "pipe"] });
const result = await superviseChild(child, {
timeoutMs: 5_000,
stdin: "supervised-stdin-payload",
onStdout: (chunk) => out.push(chunk),
});
expect(result.exitCode).toBe(0);
expect(out.join("")).toMatch(/supervised-stdin-payload/);
});
});
170 changes: 36 additions & 134 deletions test/e2e-scenario/framework/shell-probe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,23 @@
import { spawn } from "node:child_process";

import type { ArtifactSink } from "./artifacts.ts";
import { superviseChild } from "./shell/supervisor.ts";
import {
type TrustedShellCommand,
type TrustedShellCommandInput,
trustedShellCommand,
} from "./shell/trusted-command.ts";
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

/**
* Bridge-only host shell probe for the Vitest fixture migration.
* Fixture-flavored host shell probe.
*
* The end state is a shared spawn/evidence helper consumed by both this
* fixture layer and scenarios/orchestrators; that consolidation is tracked
* separately. Until it lands, this probe mirrors the hardened shell boundary:
* trusted descriptors, NUL-byte rejection, explicit env by default, canonical
* redaction (routed through the single shared entry point), and detached
* process-group termination for timeout/abort cleanup.
* The lifecycle boundary (detached process-group cleanup, SIGTERM ->
* SIGKILL escalation, timeout, AbortSignal) is owned by
* framework/shell/supervisor.ts and shared with the phase orchestrator
* and probe helpers. The trusted-command brand + NUL-byte guard live
* in framework/shell/trusted-command.ts. This file layers the
* fixture-specific policy on top: redaction at the canonical entry
* point, artifact persistence, and explicit-env-by-default.
*/

export interface ShellProbeRunOptions {
Expand All @@ -26,21 +33,8 @@
redactionValues?: string[];
}

const trustedShellCommandBrand: unique symbol = Symbol("TrustedShellCommand");

export interface TrustedShellCommand {
readonly command: string;
readonly args: readonly string[];
readonly reason: string;
readonly [trustedShellCommandBrand]: true;
}

export interface TrustedShellCommandInput {
command: string;
args?: string[];
reason: string;
validate?: (command: string, args: readonly string[]) => void;
}
export type { TrustedShellCommand, TrustedShellCommandInput } from "./shell/trusted-command.ts";
export { trustedShellCommand } from "./shell/trusted-command.ts";

export interface ShellProbeResult {
command: string[];
Expand Down Expand Up @@ -86,40 +80,6 @@
return next;
}

function validateShellToken(value: string, label: string): string {
if (value.includes("\0")) {
throw new Error(`shell probe ${label} cannot contain NUL bytes`);
}
return value;
}

/**
* Declares a shell command as trusted at the fixture/helper boundary.
*
* Build descriptors from constants or typed fixture helpers. Do not pass
* scenario, manifest, PR, or other untrusted values as the executable command.
* Put command-specific argument validation in `validate` when arguments include
* values derived from scenario data.
*/
export function trustedShellCommand(input: TrustedShellCommandInput): TrustedShellCommand {
const command = validateShellToken(input.command.trim(), "command");
if (!command) {
throw new Error("shell probe command is required");
}
const reason = input.reason.trim();
if (!reason) {
throw new Error("shell probe trusted command reason is required");
}
const args = (input.args ?? []).map((arg) => validateShellToken(arg, "argument"));
input.validate?.(command, args);
return {
command,
args,
reason,
[trustedShellCommandBrand]: true,
};
}

export class ShellProbe {
private readonly artifacts: ArtifactSink;
private readonly redact: (text: string, extraValues?: string[]) => string;
Expand Down Expand Up @@ -156,106 +116,48 @@
stderr: await this.artifacts.writeText(`${artifactBase}.stderr.txt`, result.stderr),
result: await this.artifacts.writeJson(`${artifactBase}.result.json`, result),
});

let stdout = "";
let stderr = "";
const child = spawn(command, args, {
cwd: options.cwd,
detached: true,
env: options.inheritEnv ? { ...process.env, ...(options.env ?? {}) } : { ...(options.env ?? {}) },
stdio: ["ignore", "pipe", "pipe"],
});
const pgid = child.pid;

let stdout = "";
let stderr = "";
let timedOut = false;

child.stdout.setEncoding("utf8");
child.stderr.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
stdout += chunk;
});
child.stderr.on("data", (chunk) => {
stderr += chunk;
const supervised = await superviseChild(child, {
timeoutMs,
killGraceMs,
signal: this.signal,
onStdout: (chunk) => {
stdout += chunk;
},
onStderr: (chunk) => {
stderr += chunk;
},
});

let killTimer: NodeJS.Timeout | undefined;
let terminationStarted = false;
const signalProcessGroup = (signal: NodeJS.Signals) => {
if (typeof pgid === "number") {
try {
process.kill(-pgid, signal);
return;
} catch {
/* fall back to the leader below */
}
}
try {
child.kill(signal);
} catch {
/* already gone */
}
};
const terminate = () => {
terminationStarted = true;
signalProcessGroup("SIGTERM");
if (killTimer) clearTimeout(killTimer);
killTimer = setTimeout(() => {
signalProcessGroup("SIGKILL");
}, killGraceMs);
killTimer.unref();
};
const abort = () => {
terminate();
};
const timeout = setTimeout(() => {
timedOut = true;
terminate();
}, timeoutMs);
if (this.signal.aborted) {
abort();
} else {
this.signal.addEventListener("abort", abort, { once: true });
}

let childResult: { code: number | null; signal: NodeJS.Signals | null } | undefined;
let childError: unknown;
try {
childResult = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve, reject) => {
child.on("error", reject);
child.on("close", (code, signal) => resolve({ code, signal }));
});
} catch (error) {
childError = error;
} finally {
clearTimeout(timeout);
if (killTimer && !terminationStarted) clearTimeout(killTimer);
this.signal.removeEventListener("abort", abort);
}

const redactedStdout = redactProbeText(stdout);
if (childError) {
const redactedMessage = redactProbeText(errorMessage(childError));
if (supervised.spawnError) {
const redactedMessage = redactProbeText(errorMessage(supervised.spawnError));
const redactedStderr = redactProbeText([stderr, redactedMessage].filter(Boolean).join("\n"));
await writeArtifacts({
command: redactedCommand,
exitCode: null,
signal: null,
timedOut,
timedOut: supervised.timedOut,
stdout: redactedStdout,
stderr: redactedStderr,
});
throw redactedError(childError, redactedMessage);
}

if (!childResult) {
throw new Error("shell probe child process did not report a result");
throw redactedError(supervised.spawnError, redactedMessage);
}

const redactedStderr = redactProbeText(stderr);
const result: Omit<ShellProbeResult, "artifacts"> = {
command: redactedCommand,
exitCode: childResult.code,
signal: childResult.signal,
timedOut,
exitCode: supervised.exitCode,
signal: supervised.signal,
timedOut: supervised.timedOut,
stdout: redactedStdout,
stderr: redactedStderr,
};
Expand Down
Loading
Loading