refactor: dedupe exec wrapper denial plan and test setup

This commit is contained in:
Peter Steinberger
2026-02-25 00:43:19 +00:00
parent 943b8f171a
commit a9ce6bd79b
3 changed files with 140 additions and 125 deletions

View File

@@ -24,6 +24,14 @@ import {
type ExecAllowlistEntry, type ExecAllowlistEntry,
} from "./exec-approvals.js"; } from "./exec-approvals.js";
function buildNestedEnvShellCommand(params: {
envExecutable: string;
depth: number;
payload: string;
}): string[] {
return [...Array(params.depth).fill(params.envExecutable), "/bin/sh", "-c", params.payload];
}
describe("exec approvals allowlist matching", () => { describe("exec approvals allowlist matching", () => {
const baseResolution = { const baseResolution = {
rawExecutable: "rg", rawExecutable: "rg",
@@ -311,7 +319,11 @@ describe("exec approvals command resolution", () => {
fs.chmodSync(envPath, 0o755); fs.chmodSync(envPath, 0o755);
const analysis = analyzeArgvCommand({ const analysis = analyzeArgvCommand({
argv: [envPath, envPath, envPath, envPath, envPath, "/bin/sh", "-c", "echo pwned"], argv: buildNestedEnvShellCommand({
envExecutable: envPath,
depth: 5,
payload: "echo pwned",
}),
cwd: dir, cwd: dir,
env: makePathEnv(binDir), env: makePathEnv(binDir),
}); });

View File

@@ -448,6 +448,19 @@ function isSemanticDispatchWrapperUsage(wrapper: string, argv: string[]): boolea
return !TRANSPARENT_DISPATCH_WRAPPERS.has(wrapper); return !TRANSPARENT_DISPATCH_WRAPPERS.has(wrapper);
} }
function blockedDispatchWrapperPlan(params: {
argv: string[];
wrappers: string[];
blockedWrapper: string;
}): DispatchWrapperExecutionPlan {
return {
argv: params.argv,
wrappers: params.wrappers,
policyBlocked: true,
blockedWrapper: params.blockedWrapper,
};
}
export function resolveDispatchWrapperExecutionPlan( export function resolveDispatchWrapperExecutionPlan(
argv: string[], argv: string[],
maxDepth = MAX_DISPATCH_WRAPPER_DEPTH, maxDepth = MAX_DISPATCH_WRAPPER_DEPTH,
@@ -457,36 +470,33 @@ export function resolveDispatchWrapperExecutionPlan(
for (let depth = 0; depth < maxDepth; depth += 1) { for (let depth = 0; depth < maxDepth; depth += 1) {
const unwrap = unwrapKnownDispatchWrapperInvocation(current); const unwrap = unwrapKnownDispatchWrapperInvocation(current);
if (unwrap.kind === "blocked") { if (unwrap.kind === "blocked") {
return { return blockedDispatchWrapperPlan({
argv: current, argv: current,
wrappers, wrappers,
policyBlocked: true,
blockedWrapper: unwrap.wrapper, blockedWrapper: unwrap.wrapper,
}; });
} }
if (unwrap.kind !== "unwrapped" || unwrap.argv.length === 0) { if (unwrap.kind !== "unwrapped" || unwrap.argv.length === 0) {
break; break;
} }
wrappers.push(unwrap.wrapper); wrappers.push(unwrap.wrapper);
if (isSemanticDispatchWrapperUsage(unwrap.wrapper, current)) { if (isSemanticDispatchWrapperUsage(unwrap.wrapper, current)) {
return { return blockedDispatchWrapperPlan({
argv: current, argv: current,
wrappers, wrappers,
policyBlocked: true,
blockedWrapper: unwrap.wrapper, blockedWrapper: unwrap.wrapper,
}; });
} }
current = unwrap.argv; current = unwrap.argv;
} }
if (wrappers.length >= maxDepth) { if (wrappers.length >= maxDepth) {
const overflow = unwrapKnownDispatchWrapperInvocation(current); const overflow = unwrapKnownDispatchWrapperInvocation(current);
if (overflow.kind === "blocked" || overflow.kind === "unwrapped") { if (overflow.kind === "blocked" || overflow.kind === "unwrapped") {
return { return blockedDispatchWrapperPlan({
argv: current, argv: current,
wrappers, wrappers,
policyBlocked: true,
blockedWrapper: overflow.wrapper, blockedWrapper: overflow.wrapper,
}; });
} }
} }
return { argv: current, wrappers, policyBlocked: false }; return { argv: current, wrappers, policyBlocked: false };

View File

@@ -21,6 +21,30 @@ describe("formatSystemRunAllowlistMissMessage", () => {
}); });
describe("handleSystemRunInvoke mac app exec host routing", () => { describe("handleSystemRunInvoke mac app exec host routing", () => {
function buildNestedEnvShellCommand(params: { depth: number; payload: string }): string[] {
return [...Array(params.depth).fill("/usr/bin/env"), "/bin/sh", "-c", params.payload];
}
async function withTempApprovalsHome<T>(params: {
approvals: Parameters<typeof saveExecApprovals>[0];
run: (ctx: { tempHome: string }) => Promise<T>;
}): Promise<T> {
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-exec-approvals-"));
const previousOpenClawHome = process.env.OPENCLAW_HOME;
process.env.OPENCLAW_HOME = tempHome;
saveExecApprovals(params.approvals);
try {
return await params.run({ tempHome });
} finally {
if (previousOpenClawHome === undefined) {
delete process.env.OPENCLAW_HOME;
} else {
process.env.OPENCLAW_HOME = previousOpenClawHome;
}
fs.rmSync(tempHome, { recursive: true, force: true });
}
}
async function runSystemInvoke(params: { async function runSystemInvoke(params: {
preferMacAppExecHost: boolean; preferMacAppExecHost: boolean;
runViaResponse?: ExecHostResponse | null; runViaResponse?: ExecHostResponse | null;
@@ -254,22 +278,6 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
}); });
it("denies ./skill-bin even when autoAllowSkills trust entry exists", async () => { it("denies ./skill-bin even when autoAllowSkills trust entry exists", async () => {
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-skill-path-spoof-"));
const previousOpenClawHome = process.env.OPENCLAW_HOME;
const skillBinPath = path.join(tempHome, "skill-bin");
fs.writeFileSync(skillBinPath, "#!/bin/sh\necho should-not-run\n", { mode: 0o755 });
fs.chmodSync(skillBinPath, 0o755);
process.env.OPENCLAW_HOME = tempHome;
saveExecApprovals({
version: 1,
defaults: {
security: "allowlist",
ask: "on-miss",
askFallback: "deny",
autoAllowSkills: true,
},
agents: {},
});
const runCommand = vi.fn(async () => ({ const runCommand = vi.fn(async () => ({
success: true, success: true,
stdout: "local-ok", stdout: "local-ok",
@@ -282,39 +290,47 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
const sendInvokeResult = vi.fn(async () => {}); const sendInvokeResult = vi.fn(async () => {});
const sendNodeEvent = vi.fn(async () => {}); const sendNodeEvent = vi.fn(async () => {});
try { await withTempApprovalsHome({
await handleSystemRunInvoke({ approvals: {
client: {} as never, version: 1,
params: { defaults: {
command: ["./skill-bin", "--help"], security: "allowlist",
cwd: tempHome, ask: "on-miss",
sessionKey: "agent:main:main", askFallback: "deny",
autoAllowSkills: true,
}, },
skillBins: { agents: {},
current: async () => [{ name: "skill-bin", resolvedPath: skillBinPath }], },
}, run: async ({ tempHome }) => {
execHostEnforced: false, const skillBinPath = path.join(tempHome, "skill-bin");
execHostFallbackAllowed: true, fs.writeFileSync(skillBinPath, "#!/bin/sh\necho should-not-run\n", { mode: 0o755 });
resolveExecSecurity: () => "allowlist", fs.chmodSync(skillBinPath, 0o755);
resolveExecAsk: () => "on-miss", await handleSystemRunInvoke({
isCmdExeInvocation: () => false, client: {} as never,
sanitizeEnv: () => undefined, params: {
runCommand, command: ["./skill-bin", "--help"],
runViaMacAppExecHost: vi.fn(async () => null), cwd: tempHome,
sendNodeEvent, sessionKey: "agent:main:main",
buildExecEventPayload: (payload) => payload, },
sendInvokeResult, skillBins: {
sendExecFinishedEvent: vi.fn(async () => {}), current: async () => [{ name: "skill-bin", resolvedPath: skillBinPath }],
preferMacAppExecHost: false, },
}); execHostEnforced: false,
} finally { execHostFallbackAllowed: true,
if (previousOpenClawHome === undefined) { resolveExecSecurity: () => "allowlist",
delete process.env.OPENCLAW_HOME; resolveExecAsk: () => "on-miss",
} else { isCmdExeInvocation: () => false,
process.env.OPENCLAW_HOME = previousOpenClawHome; sanitizeEnv: () => undefined,
} runCommand,
fs.rmSync(tempHome, { recursive: true, force: true }); runViaMacAppExecHost: vi.fn(async () => null),
} sendNodeEvent,
buildExecEventPayload: (payload) => payload,
sendInvokeResult,
sendExecFinishedEvent: vi.fn(async () => {}),
preferMacAppExecHost: false,
});
},
});
expect(runCommand).not.toHaveBeenCalled(); expect(runCommand).not.toHaveBeenCalled();
expect(sendNodeEvent).toHaveBeenCalledWith( expect(sendNodeEvent).toHaveBeenCalledWith(
@@ -353,82 +369,59 @@ describe("handleSystemRunInvoke mac app exec host routing", () => {
if (process.platform === "win32") { if (process.platform === "win32") {
return; return;
} }
const tempHome = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-env-depth-overflow-"));
const previousOpenClawHome = process.env.OPENCLAW_HOME;
const marker = path.join(tempHome, "pwned.txt");
process.env.OPENCLAW_HOME = tempHome;
saveExecApprovals({
version: 1,
defaults: {
security: "allowlist",
ask: "on-miss",
askFallback: "deny",
},
agents: {
main: {
allowlist: [{ pattern: "/usr/bin/env" }],
},
},
});
const runCommand = vi.fn(async () => { const runCommand = vi.fn(async () => {
fs.writeFileSync(marker, "executed"); throw new Error("runCommand should not be called for nested env depth overflow");
return {
success: true,
stdout: "local-ok",
stderr: "",
timedOut: false,
truncated: false,
exitCode: 0,
error: null,
};
}); });
const sendInvokeResult = vi.fn(async () => {}); const sendInvokeResult = vi.fn(async () => {});
const sendNodeEvent = vi.fn(async () => {}); const sendNodeEvent = vi.fn(async () => {});
try { await withTempApprovalsHome({
await handleSystemRunInvoke({ approvals: {
client: {} as never, version: 1,
params: { defaults: {
command: [ security: "allowlist",
"/usr/bin/env", ask: "on-miss",
"/usr/bin/env", askFallback: "deny",
"/usr/bin/env",
"/usr/bin/env",
"/usr/bin/env",
"/bin/sh",
"-c",
`echo PWNED > ${marker}`,
],
sessionKey: "agent:main:main",
}, },
skillBins: { agents: {
current: async () => [], main: {
allowlist: [{ pattern: "/usr/bin/env" }],
},
}, },
execHostEnforced: false, },
execHostFallbackAllowed: true, run: async ({ tempHome }) => {
resolveExecSecurity: () => "allowlist", const marker = path.join(tempHome, "pwned.txt");
resolveExecAsk: () => "on-miss", await handleSystemRunInvoke({
isCmdExeInvocation: () => false, client: {} as never,
sanitizeEnv: () => undefined, params: {
runCommand, command: buildNestedEnvShellCommand({
runViaMacAppExecHost: vi.fn(async () => null), depth: 5,
sendNodeEvent, payload: `echo PWNED > ${marker}`,
buildExecEventPayload: (payload) => payload, }),
sendInvokeResult, sessionKey: "agent:main:main",
sendExecFinishedEvent: vi.fn(async () => {}), },
preferMacAppExecHost: false, skillBins: {
}); current: async () => [],
} finally { },
if (previousOpenClawHome === undefined) { execHostEnforced: false,
delete process.env.OPENCLAW_HOME; execHostFallbackAllowed: true,
} else { resolveExecSecurity: () => "allowlist",
process.env.OPENCLAW_HOME = previousOpenClawHome; resolveExecAsk: () => "on-miss",
} isCmdExeInvocation: () => false,
fs.rmSync(tempHome, { recursive: true, force: true }); sanitizeEnv: () => undefined,
} runCommand,
runViaMacAppExecHost: vi.fn(async () => null),
sendNodeEvent,
buildExecEventPayload: (payload) => payload,
sendInvokeResult,
sendExecFinishedEvent: vi.fn(async () => {}),
preferMacAppExecHost: false,
});
expect(fs.existsSync(marker)).toBe(false);
},
});
expect(runCommand).not.toHaveBeenCalled(); expect(runCommand).not.toHaveBeenCalled();
expect(fs.existsSync(marker)).toBe(false);
expect(sendNodeEvent).toHaveBeenCalledWith( expect(sendNodeEvent).toHaveBeenCalledWith(
expect.anything(), expect.anything(),
"exec.denied", "exec.denied",