Files
openclaw/src/node-host/invoke-system-run-allowlist.test.ts
Peter Steinberger 82d1a03f25 refactor(agents): move implicit-main fallback into load-time roster injection (#112678)
* refactor(agents): require explicit roster defaults

* feat(onboard): create named first roster agent

* refactor(agents): remove runtime main fallbacks

* style(agents): apply roster refactor formatting

* refactor(agents): finish roster-only runtime sweep

* fix(doctor): migrate legacy main session sqlite

* fix(doctor): harden roster session migrations

* fix(onboard): commit first agent atomically

* fix(config): support empty-roster analysis

* fix(agents): preserve legacy main state during creation

* fix(setup): materialize baseline agent roster

* fix(agents): harden legacy default transfer recovery

* fix(agents): simplify roster-only legacy compatibility

* fix(agents): preserve staged first-agent entries

* fix(config): migrate persisted implicit-main rosters

* fix(config): preserve staged empty rosters

* fix(agents): finalize roster-only upgrade paths

* fix(sessions): close legacy main migration outcomes

* fix(config): migrate legacy roster markers at load

* fix(sessions): preserve roster upgrade history

* refactor(sessions): restore lean legacy main compatibility

* fix(setup): prepare first-agent credentials before publish

* fix(config): stabilize roster snapshot migration

* refactor(sessions): shrink legacy main compatibility

* fix(agents): restore roster compatibility fidelity

* fix(sessions): preserve divergent legacy history

* refactor(agents): narrow roster-only scope

* fix(config): isolate roster migration

* test(agents): align roster-only fixtures

* fix(agents): keep main agent undeletable

* fix(agents): harden roster migration invariants

* fix(agents): close setup and audit scope gaps

* fix(cron): scope session reaper throttles by agent

* fix(agents): preserve scoped owner precedence

* fix(config): preserve authored config ownership

* fix(setup): keep default workspace and roster in sync

* fix(setup): preserve default entry workspace on bare runs

* fix(agents): adapt roster rebase to keyed entries

* fix(agents): honor both roster representations

* fix(agents): route roster reads through shared helpers

* fix(config): preserve canonical roster writes

* fix(cron): resolve dynamic default for session reaper

* fix(agents): close dynamic default migration gaps

* fix(agents): align scoped session ownership

* fix(sessions): preserve legacy main directory casing

* fix(agents): align cron and legacy auth ownership

* fix(setup): provision the committed default workspace

* fix(cron): align scoped ownership and reaping

* fix(cron): treat blank agent ids as absent

* fix(cron): retain configured session-store owners

* fix(agents): repair roster-aware CI boundaries

* fix(cron): preserve scoped ownership resolution

* fix(agents): preserve rosterless maintenance paths

* fix(agents): propagate roster ownership through runtime boundaries

* fix(agents): preserve roster ownership across runtime paths

* fix(agents): harden roster diagnostics and legacy routing

* fix(agents): remove redundant diagnostic import

* test(agents): type CLI policy fixture explicitly

* fix(config): preserve canonical roster mutation identity

* fix(doctor): read canonical agent rosters consistently

* fix(config): resolve compound roster unsets safely

* fix(config): finalize main-session reconciliation

* fix(doctor): read canonical session state safely

* fix(sessions): preserve current visibility alias

* fix(config): track roster include provenance

* test(config): type roster provenance cases

* fix(config): refine roster include ownership

* fix(agents): preserve staged roster invariants

* test(config): align fixtures with explicit roster ownership

* test(node-host): preserve optional plan typing

* fix(config): preserve authored roster projections

* test(config): keep raw roster fixtures explicit

* test(config): normalize rosters at runtime fixtures

* fix(config): protect authored roster ownership

* fix(agents): require explicit session ownership

* fix(agents): enforce scoped roster ownership

* fix(sessions): merge fixed-store agent partitions

* fix(agents): harden roster ownership boundaries

* fix(config): reject ambiguous roster projections

* fix(sessions): preserve persisted store ownership

* fix(sessions): keep collision diagnostics additive

* fix(security): scan malformed roster workspaces

* test(config): align snapshot fixtures after rebase

* test(agents): use explicit roster fixtures

* fix(config): harden roster diagnostic boundaries

* fix(sessions): isolate fixed-store agent databases

* test(agents): type malformed default markers

* refactor(sessions): extract store collision resolution

* test(system-agent): split oversized setup coverage

* style(system-agent): format split setup suite

* fix(sessions): preserve promoted store ownership

* fix(sessions): derive scoped owner before target

* fix(sessions): preserve explicit sqlite ownership

* fix(agents): restore roster compatibility across CI

* fix(agents): enforce roster-owned runtime boundaries

* fix(agents): satisfy default lookup lint

* test(sessions): split known-owner coverage

* fix(state): satisfy path identity lint

* fix(agents): preserve malformed roster safety boundaries

* fix(agents): restore roster compatibility at runtime boundaries

* fix(config): satisfy roster boundary type checks

* fix(agents): preserve roster ownership across runtime probes

Setup inference probes now execute as the configured roster owner. Malformed agent-prefixed session rows are intentionally omitted by the fail-closed visibility contract rather than normalized by tests.

* fix(agents): satisfy session list owner lint

* fix(agents): preserve roster-owned runtime boundaries

Restore shared logical rows for exact SQLite session locators while keeping their physical database owner separate. The ownership regression test now constructs an explicit sole-owner database directly instead of relying on first-touch capture, matching the intentional shared-store contract.

* fix(sessions): preserve multiply owned exact stores

* fix(sessions): restore runtime owner boundaries

Keep incognito sentinels agent-owned, fold default-agent approvals into the global snapshot, and preserve the configless legacy-main CLI policy fallback. Also repair the existing CLI watchdog test lifecycle so the compact shard observes its timeout without an unawaited assertion or async timer stall; product behavior is unchanged by that test-only fix.

* test(ci): align owner-scoped fixtures

These assertions are unchanged. The fixtures now declare the intended non-default runner, expose the session-key constant imported by production status code, and select the main approvals bucket explicitly on Windows.

* fix(agents): close final roster ownership gaps
2026-07-24 22:38:09 -07:00

451 lines
14 KiB
TypeScript

/** Tests system.run allowlist planning, output truncation, and argv resolution. */
import { spawn } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { expectDefined } from "@openclaw/normalization-core";
import { describe, expect, it } from "vitest";
import { resolveExecApprovalsFromFile, type ExecCommandSegment } from "../infra/exec-approvals.js";
import { planShellAuthorization } from "../infra/exec-authorization-plan.js";
import { buildAuthorizedShellCommandFromPlan } from "../infra/exec-authorization-render.js";
import { resolveExecSafeBinRuntimePolicy } from "../infra/exec-safe-bin-runtime-policy.js";
import {
evaluateSystemRunAllowlist,
resolveSystemRunExecArgv,
} from "./invoke-system-run-allowlist.js";
function resolveAllowlistApprovals() {
return resolveExecApprovalsFromFile({
file: {
version: 1,
defaults: {
security: "allowlist",
ask: "off",
askFallback: "deny",
},
},
});
}
function resolveWindowsShellExecArgv(segment: ExecCommandSegment) {
return resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["powershell.exe", "-Command", "safe --version"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
skillBins: [],
autoAllowSkills: false,
isWindows: true,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "safe --version",
segments: [segment],
segmentSatisfiedBy: ["allowlist"],
authorizationPlan: undefined,
cwd: "C:\\workspace",
env: undefined,
});
}
function runExecutable(params: {
argv: string[];
cwd: string;
env: NodeJS.ProcessEnv;
}): Promise<{ exitCode: number | null; stdout: string }> {
return new Promise((resolve, reject) => {
const child = spawn(
expectDefined(params.argv[0], "params.argv[0] test invariant"),
params.argv.slice(1),
{
cwd: params.cwd,
env: params.env,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
},
);
const stdout: Buffer[] = [];
child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
child.once("error", reject);
child.once("close", (exitCode) => {
resolve({ exitCode, stdout: Buffer.concat(stdout).toString("utf8") });
});
});
}
describe("resolveSystemRunExecArgv", () => {
it("pins Windows shell execution to the resolved allowlisted executable", async () => {
const trustedExecutable = "C:\\trusted-bin\\safe.exe";
const result = await resolveWindowsShellExecArgv({
raw: "safe --version",
argv: ["safe", "--version"],
resolution: {
execution: {
rawExecutable: "safe",
resolvedPath: trustedExecutable,
executableName: "safe.exe",
},
policy: {
rawExecutable: "safe",
resolvedPath: trustedExecutable,
executableName: "safe.exe",
},
},
});
expect(result).toEqual([trustedExecutable, "--version"]);
});
it("preserves unresolved Windows shell argv authorized by a bare wildcard", async () => {
const result = await resolveWindowsShellExecArgv({
raw: "safe --version",
argv: ["safe", "--version"],
resolution: null,
});
expect(result).toEqual(["safe", "--version"]);
});
it("fails closed for Windows opaque shell transports before inner argv rewrite", async () => {
const trustedExecutable = "C:\\trusted-bin\\safe-tool.exe";
const result = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["nu.exe", "--commands", "safe-tool arg"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
skillBins: [],
autoAllowSkills: false,
isWindows: true,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "safe-tool arg",
segments: [
{
raw: "safe-tool arg",
argv: ["safe-tool", "arg"],
resolution: {
execution: {
rawExecutable: "safe-tool",
resolvedPath: trustedExecutable,
executableName: "safe-tool.exe",
},
policy: {
rawExecutable: "safe-tool",
resolvedPath: trustedExecutable,
executableName: "safe-tool.exe",
},
},
},
],
segmentSatisfiedBy: ["allowlist"],
authorizationPlan: undefined,
cwd: "C:\\workspace",
env: undefined,
});
expect(result).toBeNull();
});
it("fails closed when the Windows shell execution plan is blocked", async () => {
const result = await resolveWindowsShellExecArgv({
raw: "safe --version",
argv: ["safe", "--version"],
resolution: {
policyBlocked: true,
execution: {
rawExecutable: "safe",
executableName: "safe",
},
policy: {
rawExecutable: "safe",
executableName: "safe",
},
},
});
expect(result).toBeNull();
});
it.runIf(process.platform === "win32")(
"executes the allowlisted path instead of a workspace shadow executable",
async () => {
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-windows-shadow-"));
const trustedBin = path.join(fixtureRoot, "trusted-bin");
const workspace = path.join(fixtureRoot, "workspace");
fs.mkdirSync(trustedBin);
fs.mkdirSync(workspace);
const trustedExecutable = path.join(trustedBin, "safe.exe");
const shadowExecutable = path.join(workspace, "safe.exe");
const systemRoot = process.env.SystemRoot ?? process.env.WINDIR ?? "C:\\Windows";
fs.copyFileSync(path.join(systemRoot, "System32", "cmd.exe"), trustedExecutable);
fs.copyFileSync(path.join(systemRoot, "System32", "where.exe"), shadowExecutable);
const env = {
...process.env,
PATH: `${trustedBin}${path.delimiter}${process.env.PATH ?? ""}`,
PATHEXT: process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD",
};
const shellCommand = "safe /d /s /c echo TRUSTED_EXECUTABLE";
const commandTail = ["/d", "/s", "/c", "echo", "TRUSTED_EXECUTABLE"];
try {
const bareResult = await runExecutable({
argv: ["safe", ...commandTail],
cwd: workspace,
env,
});
expect(bareResult.exitCode).not.toBe(0);
expect(bareResult.stdout).not.toContain("TRUSTED_EXECUTABLE");
const approvals = resolveExecApprovalsFromFile({
agentId: "main",
file: {
version: 1,
defaults: { security: "allowlist", ask: "off", askFallback: "deny" },
agents: { main: { allowlist: [{ pattern: trustedExecutable }] } },
},
});
const analysis = await evaluateSystemRunAllowlist({
shellCommand,
argv: ["powershell.exe", "-Command", shellCommand],
approvals,
security: "allowlist",
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
cwd: workspace,
env,
skillBins: [],
autoAllowSkills: false,
});
expect(analysis.analysisOk).toBe(true);
expect(analysis.allowlistSatisfied).toBe(true);
const execArgv = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["powershell.exe", "-Command", shellCommand],
security: "allowlist",
approvals,
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
skillBins: [],
autoAllowSkills: false,
isWindows: true,
policy: {
approvedByAsk: false,
analysisOk: analysis.analysisOk,
allowlistSatisfied: analysis.allowlistSatisfied,
},
shellCommand,
segments: analysis.segments,
segmentSatisfiedBy: analysis.segmentSatisfiedBy,
authorizationPlan: analysis.authorizationPlan,
cwd: workspace,
env,
});
expect(execArgv?.[0]).toBe(fs.realpathSync(trustedExecutable));
const fixedResult = await runExecutable({ argv: execArgv ?? [], cwd: workspace, env });
expect(fixedResult.exitCode).toBe(0);
expect(fixedResult.stdout).toContain("TRUSTED_EXECUTABLE");
} finally {
fs.rmSync(fixtureRoot, { recursive: true, force: true });
}
},
);
it.runIf(process.platform !== "win32")(
"fails closed when shell rewriting has no authorization plan",
async () => {
const env = { PATH: "/usr/bin:/bin" };
const result = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["/bin/sh", "-lc", "head -c 16"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
skillBins: [],
autoAllowSkills: false,
isWindows: false,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "head -c 16",
segments: [],
segmentSatisfiedBy: ["safeBins"],
authorizationPlan: undefined,
cwd: undefined,
env,
});
expect(result).toBeNull();
},
);
it.runIf(process.platform !== "win32")(
"returns rebuilt shell argv when the authorization plan supports rewriting",
async () => {
const env = { PATH: "/usr/bin:/bin" };
const authorizationPlan = await planShellAuthorization({
command: "head -c 16",
env,
platform: process.platform,
});
expect(authorizationPlan.ok).toBe(true);
if (!authorizationPlan.ok) {
throw new Error(authorizationPlan.reason);
}
const safeBinPolicy = resolveExecSafeBinRuntimePolicy({
global: { safeBins: ["head"] },
});
const segmentSatisfiedBy: ["safeBins"] = ["safeBins"];
const expectedCommand = buildAuthorizedShellCommandFromPlan({
plan: authorizationPlan,
mode: "safeBins",
segmentSatisfiedBy,
});
expect(expectedCommand.ok).toBe(true);
if (!expectedCommand.ok) {
throw new Error(expectedCommand.reason);
}
const result = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["/bin/sh", "-lc", "head -c 16"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: safeBinPolicy.safeBins,
safeBinProfiles: safeBinPolicy.safeBinProfiles,
trustedSafeBinDirs: safeBinPolicy.trustedSafeBinDirs,
skillBins: [],
autoAllowSkills: false,
isWindows: false,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "head -c 16",
segments: authorizationPlan.groups.flatMap((group) =>
group.candidates.map((candidate) => candidate.sourceSegment),
),
segmentSatisfiedBy,
authorizationPlan,
cwd: undefined,
env,
});
expect(result).not.toBeNull();
expect(result?.[0]).toBe("/bin/sh");
expect(result?.[2]).toBe(expectedCommand.command);
},
);
it.runIf(process.platform !== "win32")(
"fails closed instead of rewriting opaque shell transports",
async () => {
const env = { PATH: "/usr/bin:/bin" };
const authorizationPlan = await planShellAuthorization({
command: "head -c 16",
env,
platform: process.platform,
});
expect(authorizationPlan.ok).toBe(true);
if (!authorizationPlan.ok) {
throw new Error(authorizationPlan.reason);
}
const safeBinPolicy = resolveExecSafeBinRuntimePolicy({
global: { safeBins: ["head"] },
});
const result = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["nu", "--commands", "head -c 16"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: safeBinPolicy.safeBins,
safeBinProfiles: safeBinPolicy.safeBinProfiles,
trustedSafeBinDirs: safeBinPolicy.trustedSafeBinDirs,
skillBins: [],
autoAllowSkills: false,
isWindows: false,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "head -c 16",
segments: authorizationPlan.groups.flatMap((group) =>
group.candidates.map((candidate) => candidate.sourceSegment),
),
segmentSatisfiedBy: ["safeBins"],
authorizationPlan,
cwd: undefined,
env,
});
expect(result).toBeNull();
},
);
it.runIf(process.platform !== "win32")(
"fails closed when opaque shell transports use inner allowlist authorization",
async () => {
const env = { PATH: "/usr/bin:/bin" };
const authorizationPlan = await planShellAuthorization({
command: "head -c 16",
env,
platform: process.platform,
});
expect(authorizationPlan.ok).toBe(true);
if (!authorizationPlan.ok) {
throw new Error(authorizationPlan.reason);
}
const result = await resolveSystemRunExecArgv({
plannedAllowlistArgv: undefined,
argv: ["nu", "--commands", "head -c 16"],
security: "allowlist",
approvals: resolveAllowlistApprovals(),
safeBins: new Set(),
safeBinProfiles: {},
trustedSafeBinDirs: new Set(),
skillBins: [],
autoAllowSkills: false,
isWindows: false,
policy: {
approvedByAsk: false,
analysisOk: true,
allowlistSatisfied: true,
},
shellCommand: "head -c 16",
segments: authorizationPlan.groups.flatMap((group) =>
group.candidates.map((candidate) => candidate.sourceSegment),
),
segmentSatisfiedBy: ["allowlist"],
authorizationPlan,
cwd: undefined,
env,
});
expect(result).toBeNull();
},
);
});