File size: 18,557 Bytes
e249c6d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
makeExecutable,
makeExecApprovalsTempDir,
} from "../../infra/exec-approvals-test-helpers.js";
import { loadExecApprovals, saveExecApprovals } from "../../infra/exec-approvals.js";
import {
DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS,
PLUGIN_APPROVAL_DETAIL_MAX_LENGTH,
} from "../../infra/plugin-approvals.js";
import { APPROVAL_SCRIPT_OPERAND_DRIFT_DENIED_MESSAGE } from "../../infra/system-run-approval-binding.js";
import { callGatewayTool } from "../tools/gateway.js";
import {
requestCliNativeToolApproval,
resolveCliNativeToolApprovalPlan,
} from "./cli-native-tool-approval.js";
vi.mock("../tools/gateway.js", () => ({
callGatewayTool: vi.fn(),
}));
const mockCallGatewayTool = vi.mocked(callGatewayTool);
afterEach(() => {
vi.unstubAllEnvs();
mockCallGatewayTool.mockReset();
vi.restoreAllMocks();
vi.useRealTimers();
});
describe("resolveCliNativeToolApprovalPlan", () => {
it.each([
["deny", "off", "deny"],
["deny", "on-miss", "deny"],
["deny", "always", "deny"],
// Exec mode "allowlist" maps to allowlist/off: deny without prompting.
["allowlist", "off", "deny"],
["allowlist", "on-miss", "prompt"],
["allowlist", "always", "prompt"],
["full", "off", "allow"],
["full", "on-miss", "prompt"],
["full", "always", "prompt"],
] as const)("resolves security=%s ask=%s to %s", (security, ask, expected) => {
expect(resolveCliNativeToolApprovalPlan({ security, ask })).toBe(expected);
});
});
describe("requestCliNativeToolApproval", () => {
it.each(["gog calendar list", "absolute"])(
"auto-allows and records an allowlisted native command: %s",
async (input) => {
const dir = makeExecApprovalsTempDir();
vi.stubEnv("OPENCLAW_STATE_DIR", dir);
const binary = makeExecutable(dir, "gog");
saveExecApprovals({ version: 1, agents: { main: { allowlist: [{ pattern: binary }] } } });
const command = input === "absolute" ? `${binary} calendar list` : input;
const outcome = await requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command },
pluginId: "claude-cli",
agentId: "main",
cwd: dir,
env: { PATH: dir },
ask: "on-miss",
});
expect(outcome).toMatchObject({ kind: "allow", grantAlways: false });
expect(mockCallGatewayTool).not.toHaveBeenCalled();
expect(loadExecApprovals().agents?.main?.allowlist?.[0]).toMatchObject({
lastUsedCommand: command,
lastUsedAt: expect.any(Number),
});
},
);
it.each([
["gog calendar list | missing-binary", "pipeline", false],
["gog | gog", "pipeline", false],
["gog $(date)", "command-substitution", false],
["gog '", "syntax-error", false],
["MODE=test gog", "MODE=test gog", true],
["gog > output.txt", "redirect", false],
["(gog)", "subshell", false],
["exec gog", "exec", true],
["gog *", "shell expansion", true],
])(
"keeps the binding guard and explains allowlist misses for %s",
async (command, reason, prompts) => {
const dir = makeExecApprovalsTempDir();
vi.stubEnv("OPENCLAW_STATE_DIR", dir);
const binary = makeExecutable(dir, "gog");
saveExecApprovals({ version: 1, agents: { main: { allowlist: [{ pattern: binary }] } } });
mockCallGatewayTool.mockResolvedValueOnce({ id: "native-miss", decision: "deny" });
const outcome = await requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command },
pluginId: "claude-cli",
agentId: "main",
cwd: dir,
env: { PATH: dir },
ask: "on-miss",
});
if (prompts) {
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
description: expect.stringContaining(reason),
allowedDecisions: ["allow-once", "deny"],
});
} else {
expect(mockCallGatewayTool).not.toHaveBeenCalled();
expect(outcome).toMatchObject({
kind: "deny",
reason: "operand-binding",
message: expect.stringContaining(reason),
});
}
expect(loadExecApprovals().agents?.main?.allowlist?.[0]?.lastUsedAt).toBeUndefined();
},
);
it("still prompts for an allowlisted Bash command when ask is always", async () => {
const dir = makeExecApprovalsTempDir();
vi.stubEnv("OPENCLAW_STATE_DIR", dir);
const binary = makeExecutable(dir, "gog");
saveExecApprovals({ version: 1, agents: { main: { allowlist: [{ pattern: binary }] } } });
mockCallGatewayTool.mockResolvedValueOnce({ id: "always", decision: "allow-once" });
expect(
await requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: `${binary} calendar list` },
pluginId: "claude-cli",
agentId: "main",
cwd: dir,
ask: "always",
}),
).toEqual({ kind: "allow", grantAlways: false });
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
allowedDecisions: ["allow-once", "deny"],
});
expect(loadExecApprovals().agents?.main?.allowlist?.[0]?.lastUsedAt).toBeUndefined();
});
it("binds manual approval to the native PATH when exec prepends differ", async () => {
const dir = makeExecApprovalsTempDir();
const nativeDir = makeExecApprovalsTempDir();
vi.stubEnv("OPENCLAW_STATE_DIR", dir);
makeExecutable(dir, "gog");
const nativeBinary = makeExecutable(nativeDir, "gog");
saveExecApprovals({ version: 1, agents: { main: { allowlist: [] } } });
mockCallGatewayTool.mockImplementationOnce(async () => {
fs.writeFileSync(nativeBinary, "changed during approval");
return { id: "path-drift", decision: "allow-once" };
});
expect(
await requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "gog" },
pluginId: "claude-cli",
agentId: "main",
cwd: dir,
ask: "on-miss",
env: { PATH: dir },
bindingEnv: { PATH: nativeDir },
}),
).toMatchObject({ kind: "deny", reason: "operand-binding" });
});
it("rechecks current grants before recording an auto-allow", async () => {
const dir = makeExecApprovalsTempDir();
vi.stubEnv("OPENCLAW_STATE_DIR", dir);
const binary = makeExecutable(dir, "gog");
saveExecApprovals({ version: 1, agents: { main: { allowlist: [{ pattern: binary }] } } });
const outcome = await requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: binary },
pluginId: "claude-cli",
agentId: "main",
cwd: dir,
ask: "on-miss",
assertActive: () => saveExecApprovals({ version: 1, agents: { main: { allowlist: [] } } }),
});
expect(outcome).toEqual({ kind: "deny", reason: "unavailable" });
expect(loadExecApprovals().agents?.main?.allowlist).toEqual([]);
expect(mockCallGatewayTool).not.toHaveBeenCalled();
});
it("registers and waits for a matching approval decision", async () => {
mockCallGatewayTool
.mockResolvedValueOnce({ id: "approval-1", status: "pending" })
.mockResolvedValueOnce({ id: "approval-1", decision: "allow-once" });
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
sessionKey: "agent:main:main",
agentId: "main",
toolCallId: "tool-1",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "allow", grantAlways: false });
const gatewayTimeoutMs = DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS + 10_000;
expect(mockCallGatewayTool).toHaveBeenNthCalledWith(
1,
"plugin.approval.request",
{ timeoutMs: gatewayTimeoutMs },
{
pluginId: "claude-cli",
toolName: "Bash",
toolCallId: "tool-1",
agentId: "main",
sessionKey: "agent:main:main",
title: "claude-cli native tool: Bash",
description: '{"command":"ls"}\nExec allowlist miss: ls',
detail: '{"command":"ls"}',
severity: "warning",
allowedDecisions: ["allow-once", "deny"],
timeoutMs: DEFAULT_PLUGIN_APPROVAL_TIMEOUT_MS,
twoPhase: true,
},
{ expectFinal: false },
);
expect(mockCallGatewayTool).toHaveBeenNthCalledWith(
2,
"plugin.approval.waitDecision",
{ timeoutMs: gatewayTimeoutMs },
{ id: "approval-1" },
{ signal: undefined },
);
});
it("honors an immediate decision without waiting", async () => {
mockCallGatewayTool.mockResolvedValueOnce({
id: "approval-2",
decision: "allow-always",
});
await expect(
requestCliNativeToolApproval({
toolName: "WebFetch",
toolInput: { url: "https://example.com" },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "allow", grantAlways: true });
expect(mockCallGatewayTool).toHaveBeenCalledOnce();
});
it("identifies the owning backend when another provider requests native approval", async () => {
mockCallGatewayTool.mockResolvedValueOnce({
id: "approval-other-provider",
decision: "allow-once",
});
await expect(
requestCliNativeToolApproval({
toolName: "Read",
toolInput: { file_path: "/tmp/example.txt" },
pluginId: "gemini-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "allow", grantAlways: false });
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
pluginId: "gemini-cli",
title: "gemini-cli native tool: Read",
});
});
it("fails closed when the approval wait times out", async () => {
mockCallGatewayTool
.mockResolvedValueOnce({ id: "approval-3" })
.mockRejectedValueOnce(new Error("gateway timeout"));
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "unavailable" });
});
it("fails closed when the gateway request errors", async () => {
mockCallGatewayTool.mockRejectedValueOnce(new Error("gateway unavailable"));
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "unavailable" });
});
it("fails closed when the run aborts while waiting", async () => {
const abortController = new AbortController();
mockCallGatewayTool
.mockResolvedValueOnce({ id: "approval-4" })
.mockImplementationOnce(() => new Promise(() => {}));
const approval = requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
abortSignal: abortController.signal,
ask: "on-miss",
});
abortController.abort(new Error("run stopped"));
await expect(approval).resolves.toEqual({ kind: "deny", reason: "unavailable" });
});
it("fails closed when the run aborts while registering the approval", async () => {
const abortController = new AbortController();
mockCallGatewayTool.mockImplementationOnce(() => new Promise(() => {}));
const approval = requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
abortSignal: abortController.signal,
ask: "on-miss",
});
abortController.abort(new Error("run stopped"));
await expect(approval).resolves.toEqual({ kind: "deny", reason: "unavailable" });
expect(mockCallGatewayTool).toHaveBeenCalledOnce();
});
it("shows head and tail of oversized non-Bash inputs and withholds allow-always", async () => {
mockCallGatewayTool.mockResolvedValueOnce({ id: "approval-5", decision: "deny" });
const content = `safe-prefix ${"x".repeat(500)} destructive-tail`;
await expect(
requestCliNativeToolApproval({
toolName: "Write",
toolInput: { file_path: "/tmp/output.txt", content },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "user" });
const requestPayload = mockCallGatewayTool.mock.calls[0]?.[2] as
| { description?: string; detail?: string; allowedDecisions?: unknown }
| undefined;
expect(requestPayload?.description).toContain("destructive-tail");
expect(requestPayload?.description).toContain(
'{"file_path":"/tmp/output.txt","content":"safe-prefix',
);
expect(requestPayload?.description).toMatch(/…\[\+\d+ chars hidden\]…/u);
expect(requestPayload?.description?.length).toBeLessThanOrEqual(512);
expect(requestPayload?.detail).toBe(JSON.stringify({ file_path: "/tmp/output.txt", content }));
expect(requestPayload?.allowedDecisions).toEqual(["allow-once", "deny"]);
});
it("never offers or honors allow-always for Bash", async () => {
mockCallGatewayTool.mockResolvedValueOnce({ id: "approval-5b", decision: "allow-always" });
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "ls" },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "unavailable" });
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
description: '{"command":"ls"}',
detail: '{"command":"ls"}',
allowedDecisions: ["allow-once", "deny"],
});
});
it("checks Bash script drift before rejecting an unexpected allow-always", async () => {
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-cli-always-drift-"));
const script = path.join(cwd, "script.sh");
try {
fs.writeFileSync(script, "#!/bin/sh\necho approved\n");
mockCallGatewayTool.mockImplementationOnce(async () => {
fs.writeFileSync(script, "#!/bin/sh\necho changed\n");
return { id: "approval-unexpected-always", decision: "allow-always" };
});
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "sh script.sh" },
pluginId: "claude-cli",
cwd,
ask: "on-miss",
}),
).resolves.toEqual({
kind: "deny",
reason: "operand-binding",
message: APPROVAL_SCRIPT_OPERAND_DRIFT_DENIED_MESSAGE,
});
} finally {
fs.rmSync(cwd, { recursive: true, force: true });
}
});
it("denies Bash whose channel description truncates even when detail would fit", async () => {
// Channel/push approvers never see the reviewer detail, so a Bash command
// hidden by description truncation must not be approvable from anywhere.
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: `echo ${"x".repeat(500)}; rm -rf /tmp/example` },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "policy-oversized" });
expect(mockCallGatewayTool).not.toHaveBeenCalled();
});
it("denies Bash input beyond the reviewer detail limit without calling the gateway", async () => {
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: "x".repeat(PLUGIN_APPROVAL_DETAIL_MAX_LENGTH) },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "policy-oversized" });
expect(mockCallGatewayTool).not.toHaveBeenCalled();
});
it("denies Bash whose short raw command expands past the summary bound when sanitized", async () => {
// ~70 bidi override chars stay under the raw description budget but escape
// to \u{202E} sequences that overflow the 512-char channel summary.
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: `echo ${"".repeat(70)}; rm -rf /tmp/example` },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "policy-oversized" });
expect(mockCallGatewayTool).not.toHaveBeenCalled();
});
it("denies Bash when reviewer sanitization would hide the command tail", async () => {
await expect(
requestCliNativeToolApproval({
toolName: "Bash",
toolInput: { command: `# ${"\u202e".repeat(3_000)}\necho destructive-tail` },
pluginId: "claude-cli",
ask: "on-miss",
}),
).resolves.toEqual({ kind: "deny", reason: "policy-oversized" });
expect(mockCallGatewayTool).not.toHaveBeenCalled();
});
it("withholds allow-always when ask is always", async () => {
mockCallGatewayTool.mockResolvedValueOnce({ id: "approval-5c", decision: "deny" });
await expect(
requestCliNativeToolApproval({
toolName: "WebFetch",
toolInput: { url: "https://example.com" },
pluginId: "claude-cli",
ask: "always",
}),
).resolves.toEqual({ kind: "deny", reason: "user" });
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
allowedDecisions: ["allow-once", "deny"],
});
});
it("truncates only the display title for long native tool names", async () => {
mockCallGatewayTool.mockResolvedValueOnce({ id: "approval-6", decision: "deny" });
const toolName = `mcp__claude-in-chrome__${"long-tool-segment-".repeat(6)}`;
await requestCliNativeToolApproval({
toolName,
toolInput: {},
pluginId: "claude-cli",
ask: "on-miss",
});
const requestPayload = mockCallGatewayTool.mock.calls[0]?.[2] as
| { title?: unknown; toolName?: unknown }
| undefined;
expect(requestPayload?.title).toHaveLength(80);
expect(requestPayload?.title).toMatch(/^claude-cli native tool: /u);
expect(requestPayload?.toolName).toBe(toolName);
});
it("uses an object fallback when JSON serialization returns undefined", async () => {
mockCallGatewayTool.mockResolvedValueOnce({ id: "approval-7", decision: "deny" });
await requestCliNativeToolApproval({
toolName: "WebFetch",
toolInput: { toJSON: () => undefined },
pluginId: "claude-cli",
ask: "on-miss",
});
expect(mockCallGatewayTool.mock.calls[0]?.[2]).toMatchObject({
description: "{}",
detail: "{}",
});
});
});
|