Elffuss BraidHub

kikocis/continue public

main · 32.5 KiBRawPermalink
1import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
3import * as toolsModule from "../tools/index.js";
4
5import {
6 checkToolPermission,
7 filterExcludedTools,
8 matchesArguments,
9 matchesToolPattern,
10} from "./permissionChecker.js";
11import { ToolPermissions } from "./types.js";
12
13describe("Permission Checker", () => {
14 describe("matchesToolPattern", () => {
15 it("should match exact tool names", () => {
16 expect(matchesToolPattern("readFile", "readFile")).toBe(true);
17 expect(matchesToolPattern("writeFile", "readFile")).toBe(false);
18 });
19
20 it("should match universal wildcard", () => {
21 expect(matchesToolPattern("anyTool", "*")).toBe(true);
22 expect(matchesToolPattern("readFile", "*")).toBe(true);
23 expect(matchesToolPattern("", "*")).toBe(true);
24 });
25
26 it("should match prefix wildcards", () => {
27 expect(matchesToolPattern("mcp__ide__getDiagnostics", "mcp__*")).toBe(
28 true,
29 );
30 expect(matchesToolPattern("mcp__filesystem__read", "mcp__*")).toBe(true);
31 expect(matchesToolPattern("builtin__readFile", "mcp__*")).toBe(false);
32 });
33
34 it("should match suffix wildcards", () => {
35 expect(matchesToolPattern("readFile", "*File")).toBe(true);
36 expect(matchesToolPattern("writeFile", "*File")).toBe(true);
37 expect(matchesToolPattern("readData", "*File")).toBe(false);
38 });
39
40 it("should match complex wildcard patterns", () => {
41 expect(matchesToolPattern("test_function_123", "test_*_123")).toBe(true);
42 expect(matchesToolPattern("test_abc_123", "test_*_123")).toBe(true);
43 expect(matchesToolPattern("test_function_456", "test_*_123")).toBe(false);
44 });
45
46 it("should handle empty strings", () => {
47 expect(matchesToolPattern("", "")).toBe(true);
48 expect(matchesToolPattern("tool", "")).toBe(false);
49 expect(matchesToolPattern("", "tool")).toBe(false);
50 });
51
52 it("should handle special regex characters in patterns", () => {
53 expect(matchesToolPattern("test.file", "test.file")).toBe(true);
54 expect(matchesToolPattern("test_file", "test.file")).toBe(false);
55 expect(matchesToolPattern("test[file]", "test[file]")).toBe(true);
56 expect(matchesToolPattern("testa", "test[abc]")).toBe(false);
57 expect(matchesToolPattern("test[abc]", "test[abc]")).toBe(true);
58 expect(matchesToolPattern("test(abc)", "test(abc)")).toBe(true);
59 expect(matchesToolPattern("test+plus", "test+plus")).toBe(true);
60 expect(matchesToolPattern("test^caret", "test^caret")).toBe(true);
61 expect(matchesToolPattern("test$dollar", "test$dollar")).toBe(true);
62 expect(matchesToolPattern("test{brace}", "test{brace}")).toBe(true);
63 expect(matchesToolPattern("test|pipe", "test|pipe")).toBe(true);
64 expect(matchesToolPattern("test\\backslash", "test\\backslash")).toBe(
65 true,
66 );
67 });
68
69 it("should handle wildcard patterns with special regex characters", () => {
70 expect(matchesToolPattern("test[abc].txt", "test[abc].*")).toBe(true);
71 expect(matchesToolPattern("test[abc]_file", "test[abc].*")).toBe(false);
72 expect(matchesToolPattern("mcp__tool[1]", "mcp__*")).toBe(true);
73 expect(matchesToolPattern("file.test.txt", "*.test.*")).toBe(true);
74 expect(matchesToolPattern("(tool)_name", "(tool)*")).toBe(true);
75 expect(matchesToolPattern("tool+plus_extra", "tool+plus*")).toBe(true);
76 });
77
78 describe("Bash command patterns", () => {
79 it("should match Bash command patterns with Bash tool", () => {
80 expect(matchesToolPattern("Bash", "Bash(ls*)", { command: "ls" })).toBe(
81 true,
82 );
83 expect(
84 matchesToolPattern("Bash", "Bash(ls*)", { command: "ls -la" }),
85 ).toBe(true);
86 expect(
87 matchesToolPattern("Bash", "Bash(ls*)", { command: "pwd" }),
88 ).toBe(false);
89 });
90
91 it("should match Bash command patterns with Bash display name", () => {
92 expect(
93 matchesToolPattern("Bash", "Bash(git*)", { command: "git status" }),
94 ).toBe(true);
95 expect(
96 matchesToolPattern("Bash", "Bash(git*)", { command: "git commit" }),
97 ).toBe(true);
98 expect(
99 matchesToolPattern("Bash", "Bash(git*)", { command: "npm install" }),
100 ).toBe(false);
101 });
102
103 it("should match exact Bash commands", () => {
104 expect(matchesToolPattern("Bash", "Bash(ls)", { command: "ls" })).toBe(
105 true,
106 );
107 expect(
108 matchesToolPattern("Bash", "Bash(ls)", { command: "ls -la" }),
109 ).toBe(false);
110 });
111
112 it("should not match Bash patterns for non-bash tools", () => {
113 expect(matchesToolPattern("Read", "Bash(ls*)", { command: "ls" })).toBe(
114 false,
115 );
116 expect(
117 matchesToolPattern("Write", "Bash(git*)", { command: "git status" }),
118 ).toBe(false);
119 });
120
121 it("should not match Bash patterns without command argument", () => {
122 expect(matchesToolPattern("Bash", "Bash(ls*)", {})).toBe(false);
123 expect(
124 matchesToolPattern("Bash", "Bash(ls*)", { other: "value" }),
125 ).toBe(false);
126 });
127
128 it("should handle complex Bash command patterns", () => {
129 expect(
130 matchesToolPattern("Bash", "Bash(npm*)", { command: "npm install" }),
131 ).toBe(true);
132 expect(
133 matchesToolPattern("Bash", "Bash(npm*)", {
134 command: "npm run build",
135 }),
136 ).toBe(true);
137 expect(
138 matchesToolPattern("Bash", "Bash(git*commit*)", {
139 command: "git commit -m 'test'",
140 }),
141 ).toBe(true);
142 });
143 });
144 });
145
146 describe("matchesArguments", () => {
147 it("should return true when no patterns provided", () => {
148 expect(matchesArguments({ path: "/test.txt" })).toBe(true);
149 expect(matchesArguments({})).toBe(true);
150 expect(matchesArguments({ any: "value" }, undefined)).toBe(true);
151 });
152
153 it("should match exact argument values", () => {
154 const args = { path: "/test.txt", mode: "read" };
155 const patterns = { path: "/test.txt" };
156 expect(matchesArguments(args, patterns)).toBe(true);
157
158 const nonMatchingPatterns = { path: "/other.txt" };
159 expect(matchesArguments(args, nonMatchingPatterns)).toBe(false);
160 });
161
162 it("should match wildcard argument patterns", () => {
163 const args = { path: "/any/file.txt", mode: "write" };
164 const patterns = { path: "*", mode: "write" };
165 expect(matchesArguments(args, patterns)).toBe(true);
166
167 const wildcardOnlyPatterns = { path: "*" };
168 expect(matchesArguments(args, wildcardOnlyPatterns)).toBe(true);
169 });
170
171 it("should require all patterns to match", () => {
172 const args = { path: "/test.txt", mode: "read", format: "json" };
173 const allMatchingPatterns = { path: "/test.txt", mode: "read" };
174 expect(matchesArguments(args, allMatchingPatterns)).toBe(true);
175
176 const partialMatchingPatterns = { path: "/test.txt", mode: "write" };
177 expect(matchesArguments(args, partialMatchingPatterns)).toBe(false);
178 });
179
180 it("should handle missing arguments", () => {
181 const args = { path: "/test.txt" };
182 const patternsRequiringMissing = { path: "/test.txt", mode: "read" };
183 expect(matchesArguments(args, patternsRequiringMissing)).toBe(false);
184 });
185
186 it("should handle different data types", () => {
187 const args = { count: 42, enabled: true, data: null, list: [1, 2, 3] };
188 const patterns = { count: 42, enabled: true };
189 expect(matchesArguments(args, patterns)).toBe(true);
190
191 const mismatchedPatterns = { count: "42" }; // string vs number
192 expect(matchesArguments(args, mismatchedPatterns)).toBe(false);
193 });
194
195 it("should handle complex object arguments with reference equality", () => {
196 const configObj = { host: "localhost", port: 3000 };
197 const optionsArray = ["verbose", "debug"];
198
199 const args = {
200 config: configObj,
201 options: optionsArray,
202 };
203 const patterns = {
204 config: configObj, // Same reference
205 options: optionsArray, // Same reference
206 };
207 expect(matchesArguments(args, patterns)).toBe(true);
208
209 const differentObjectPatterns = {
210 config: { host: "localhost", port: 8080 }, // Different object
211 };
212 expect(matchesArguments(args, differentObjectPatterns)).toBe(false);
213
214 const differentButEqualObjectPatterns = {
215 config: { host: "localhost", port: 3000 }, // Different reference, same content
216 };
217 expect(matchesArguments(args, differentButEqualObjectPatterns)).toBe(
218 false,
219 );
220 });
221
222 describe("glob pattern matching", () => {
223 it("should match glob patterns with asterisk wildcards", () => {
224 const args = {
225 command: "cd ../projects && ls",
226 file_path: "/src/file.ts",
227 };
228
229 // Test command patterns
230 expect(matchesArguments(args, { command: "cd*" })).toBe(true);
231 expect(matchesArguments(args, { command: "*ls" })).toBe(true);
232 expect(matchesArguments(args, { command: "*&&*" })).toBe(true);
233 expect(matchesArguments(args, { command: "pwd*" })).toBe(false);
234
235 // Test file path patterns
236 expect(matchesArguments(args, { file_path: "*.ts" })).toBe(true);
237 expect(matchesArguments(args, { file_path: "/src/*" })).toBe(true);
238 expect(matchesArguments(args, { file_path: "**/file.ts" })).toBe(true);
239 expect(matchesArguments(args, { file_path: "*.js" })).toBe(false);
240 });
241
242 it("should match glob patterns with question mark wildcards", () => {
243 const args = { command: "git add", file: "test1.js" };
244
245 expect(matchesArguments(args, { command: "git a?d" })).toBe(true);
246 expect(matchesArguments(args, { command: "git a??d" })).toBe(false);
247 expect(matchesArguments(args, { file: "test?.js" })).toBe(true);
248 expect(matchesArguments(args, { file: "test??.js" })).toBe(false);
249 });
250
251 it("should match complex glob patterns", () => {
252 const args = {
253 command: "npm run test:unit",
254 path: "/home/user/projects/myapp/src/utils/helper.ts",
255 };
256
257 expect(matchesArguments(args, { command: "npm * test:*" })).toBe(true);
258 expect(matchesArguments(args, { command: "npm run *:unit" })).toBe(
259 true,
260 );
261 expect(matchesArguments(args, { path: "**/src/**/*.ts" })).toBe(true);
262 expect(
263 matchesArguments(args, { path: "/home/*/projects/*/src/**" }),
264 ).toBe(true);
265 expect(matchesArguments(args, { command: "yarn *" })).toBe(false);
266 });
267
268 it("should escape special regex characters in glob patterns", () => {
269 const args = {
270 command: "echo 'test.pattern'",
271 regex: "test[0-9]+",
272 special: "file(1).txt",
273 };
274
275 // Literal dots, brackets, parentheses should match exactly
276 expect(matchesArguments(args, { command: "*'test.pattern'*" })).toBe(
277 true,
278 );
279 expect(matchesArguments(args, { regex: "test[0-9]+" })).toBe(true);
280 expect(matchesArguments(args, { special: "file(1).txt" })).toBe(true);
281 expect(matchesArguments(args, { special: "file(*).txt" })).toBe(true);
282
283 // These should not match due to regex escaping
284 expect(matchesArguments(args, { command: "*test_pattern*" })).toBe(
285 false,
286 );
287 expect(matchesArguments(args, { regex: "test*" })).toBe(true); // * is wildcard, + is literal
288 });
289
290 it("should handle mixed exact and glob patterns", () => {
291 const args = {
292 tool: "bash",
293 command: "cd projects && npm install",
294 flag: "--verbose",
295 };
296
297 // Mix of exact and glob matching
298 expect(
299 matchesArguments(args, {
300 tool: "bash", // exact match
301 command: "cd*install", // glob match
302 flag: "--verbose", // exact match
303 }),
304 ).toBe(true);
305
306 expect(
307 matchesArguments(args, {
308 tool: "bash", // exact match
309 command: "cd*test", // glob no match
310 flag: "--verbose", // exact match
311 }),
312 ).toBe(false);
313 });
314
315 it("should convert non-string values to strings for pattern matching", () => {
316 const args = {
317 port: 3000,
318 enabled: true,
319 count: null,
320 items: [1, 2, 3],
321 };
322
323 expect(matchesArguments(args, { port: "30*" })).toBe(true);
324 expect(matchesArguments(args, { enabled: "tr*" })).toBe(true);
325 expect(matchesArguments(args, { count: "*" })).toBe(true); // null -> ""
326 expect(matchesArguments(args, { items: "*,*,*" })).toBe(true); // array toString
327
328 expect(matchesArguments(args, { port: "40*" })).toBe(false);
329 expect(matchesArguments(args, { enabled: "fa*" })).toBe(false);
330 });
331
332 it("should handle empty and undefined argument values", () => {
333 const args = {
334 empty: "",
335 undef: undefined,
336 zero: 0,
337 false_val: false,
338 };
339
340 expect(matchesArguments(args, { empty: "*" })).toBe(true);
341 expect(matchesArguments(args, { undef: "*" })).toBe(true); // undefined -> ""
342 expect(matchesArguments(args, { zero: "*" })).toBe(true); // 0 -> "0"
343 expect(matchesArguments(args, { false_val: "*" })).toBe(true); // false -> "false"
344
345 expect(matchesArguments(args, { empty: "nonempty*" })).toBe(false);
346 expect(matchesArguments(args, { zero: "1*" })).toBe(false);
347 });
348 });
349 });
350
351 describe("checkToolPermission", () => {
352 it("should allow tools with allow permission", () => {
353 const permissions: ToolPermissions = {
354 policies: [{ tool: "readFile", permission: "allow" }],
355 };
356
357 const result = checkToolPermission(
358 { name: "readFile", arguments: { path: "/test.txt" } },
359 permissions,
360 );
361
362 expect(result.permission).toBe("allow");
363 expect(result.matchedPolicy?.tool).toBe("readFile");
364 });
365
366 it("should ask for tools with ask permission", () => {
367 const permissions: ToolPermissions = {
368 policies: [{ tool: "writeFile", permission: "ask" }],
369 };
370
371 const result = checkToolPermission(
372 {
373 name: "writeFile",
374 arguments: { path: "/test.txt", content: "hello" },
375 },
376 permissions,
377 );
378
379 expect(result.permission).toBe("ask");
380 expect(result.matchedPolicy?.tool).toBe("writeFile");
381 });
382
383 it("should exclude tools with exclude permission", () => {
384 const permissions: ToolPermissions = {
385 policies: [{ tool: "runTerminalCommand", permission: "exclude" }],
386 };
387
388 const result = checkToolPermission(
389 { name: "runTerminalCommand", arguments: { command: "rm -rf /" } },
390 permissions,
391 );
392
393 expect(result.permission).toBe("exclude");
394 expect(result.matchedPolicy?.tool).toBe("runTerminalCommand");
395 });
396
397 it("should match wildcard patterns", () => {
398 const permissions: ToolPermissions = {
399 policies: [
400 { tool: "mcp__*", permission: "ask" },
401 { tool: "*", permission: "allow" },
402 ],
403 };
404
405 const mcpResult = checkToolPermission(
406 { name: "mcp__ide__getDiagnostics", arguments: {} },
407 permissions,
408 );
409 expect(mcpResult.permission).toBe("ask");
410 expect(mcpResult.matchedPolicy?.tool).toBe("mcp__*");
411
412 const builtinResult = checkToolPermission(
413 { name: "readFile", arguments: { path: "/test.txt" } },
414 permissions,
415 );
416 expect(builtinResult.permission).toBe("allow");
417 expect(builtinResult.matchedPolicy?.tool).toBe("*");
418 });
419
420 it("should match based on arguments", () => {
421 const permissions: ToolPermissions = {
422 policies: [
423 {
424 tool: "writeFile",
425 permission: "exclude",
426 argumentMatches: { path: "/sensitive.txt" },
427 },
428 { tool: "writeFile", permission: "allow" },
429 ],
430 };
431
432 const sensitiveResult = checkToolPermission(
433 {
434 name: "writeFile",
435 arguments: { path: "/sensitive.txt", content: "data" },
436 },
437 permissions,
438 );
439 expect(sensitiveResult.permission).toBe("exclude");
440
441 const normalResult = checkToolPermission(
442 {
443 name: "writeFile",
444 arguments: { path: "/normal.txt", content: "data" },
445 },
446 permissions,
447 );
448 expect(normalResult.permission).toBe("allow");
449 });
450
451 it("should use default policies when no custom permissions provided", () => {
452 const result = checkToolPermission({
453 name: "Read",
454 arguments: { path: "/test.txt" },
455 });
456
457 // Should match the default policies (Read should be "allow")
458 expect(result.permission).toBe("allow");
459 });
460
461 it("should fall back to ask when no policy matches", () => {
462 const permissions: ToolPermissions = {
463 policies: [{ tool: "specificTool", permission: "allow" }],
464 };
465
466 const result = checkToolPermission(
467 { name: "unknownTool", arguments: {} },
468 permissions,
469 );
470
471 expect(result.permission).toBe("ask");
472 });
473
474 it("should match Bash command patterns in checkToolPermission", () => {
475 const permissions: ToolPermissions = {
476 policies: [
477 { tool: "Bash(ls*)", permission: "allow" },
478 { tool: "Bash(git*)", permission: "ask" },
479 { tool: "Bash", permission: "ask" }, // Fallback for other commands
480 ],
481 };
482
483 // Should match "Bash(ls*)" pattern and allow
484 const lsResult = checkToolPermission(
485 { name: "Bash", arguments: { command: "ls -la" } },
486 permissions,
487 );
488 expect(lsResult.permission).toBe("allow");
489 expect(lsResult.matchedPolicy?.tool).toBe("Bash(ls*)");
490
491 // Should match "Bash(git*)" pattern and ask
492 const gitResult = checkToolPermission(
493 { name: "Bash", arguments: { command: "git status" } },
494 permissions,
495 );
496 expect(gitResult.permission).toBe("ask");
497 expect(gitResult.matchedPolicy?.tool).toBe("Bash(git*)");
498
499 // Should match general fallback for other commands
500 const npmResult = checkToolPermission(
501 { name: "Bash", arguments: { command: "npm install" } },
502 permissions,
503 );
504 expect(npmResult.permission).toBe("ask");
505 expect(npmResult.matchedPolicy?.tool).toBe("Bash");
506 });
507
508 it("should match argument patterns with glob patterns", () => {
509 const permissions: ToolPermissions = {
510 policies: [
511 {
512 tool: "Bash",
513 permission: "exclude",
514 argumentMatches: { command: "rm*" },
515 },
516 {
517 tool: "Write",
518 permission: "ask",
519 argumentMatches: { file_path: "**/*.ts" },
520 },
521 {
522 tool: "Write",
523 permission: "allow",
524 },
525 ],
526 };
527
528 // Should exclude dangerous rm commands
529 const rmResult = checkToolPermission(
530 { name: "Bash", arguments: { command: "rm -rf /" } },
531 permissions,
532 );
533 expect(rmResult.permission).toBe("exclude");
534 expect(rmResult.matchedPolicy?.argumentMatches?.command).toBe("rm*");
535
536 // Should ask for TypeScript files
537 const tsResult = checkToolPermission(
538 {
539 name: "Write",
540 arguments: { file_path: "/src/components/Button.ts" },
541 },
542 permissions,
543 );
544 expect(tsResult.permission).toBe("ask");
545 expect(tsResult.matchedPolicy?.argumentMatches?.file_path).toBe(
546 "**/*.ts",
547 );
548
549 // Should allow other file writes
550 const jsResult = checkToolPermission(
551 { name: "Write", arguments: { file_path: "/src/utils/helper.js" } },
552 permissions,
553 );
554 expect(jsResult.permission).toBe("allow");
555 expect(jsResult.matchedPolicy?.argumentMatches).toBeUndefined();
556 });
557 });
558
559 describe("filterExcludedTools", () => {
560 it("should filter out excluded tools", () => {
561 const permissions: ToolPermissions = {
562 policies: [
563 { tool: "runTerminalCommand", permission: "exclude" },
564 { tool: "writeFile", permission: "ask" },
565 { tool: "*", permission: "allow" },
566 ],
567 };
568
569 const tools = [
570 "readFile",
571 "writeFile",
572 "runTerminalCommand",
573 "searchCode",
574 ];
575 const filtered = filterExcludedTools(tools, permissions);
576
577 expect(filtered).toEqual(["readFile", "writeFile", "searchCode"]);
578 expect(filtered).not.toContain("runTerminalCommand");
579 });
580
581 it("should return all tools when none are excluded", () => {
582 const permissions: ToolPermissions = {
583 policies: [{ tool: "*", permission: "allow" }],
584 };
585
586 const tools = ["readFile", "writeFile", "runTerminalCommand"];
587 const filtered = filterExcludedTools(tools, permissions);
588
589 expect(filtered).toEqual(tools);
590 });
591
592 it("should use default policies when no permissions provided", () => {
593 const tools = ["readFile", "writeFile", "runTerminalCommand"];
594 const filtered = filterExcludedTools(tools);
595
596 // All tools should be included (none excluded by default)
597 expect(filtered).toEqual(tools);
598 });
599 });
600
601 describe("Hybrid Permission Model with Dynamic Evaluation", () => {
602 // Mock the runTerminalCommand tool with evaluateToolCallPolicy
603 const mockBashTool = {
604 name: "Bash",
605 displayName: "Bash",
606 description: "Execute bash commands",
607 parameters: {
608 type: "object" as const,
609 properties: {},
610 },
611 isBuiltIn: true,
612 evaluateToolCallPolicy: vi.fn(),
613 run: vi.fn(),
614 };
615
616 beforeEach(() => {
617 vi.clearAllMocks();
618 // Mock getAllBuiltinTools to return our test tool
619 vi.spyOn(toolsModule, "getAllBuiltinTools").mockReturnValue([
620 mockBashTool,
621 ]);
622
623 // Reset mock between tests
624 mockBashTool.evaluateToolCallPolicy.mockClear();
625 });
626
627 afterEach(() => {
628 vi.restoreAllMocks();
629 });
630
631 describe("User has Bash in 'allow' mode", () => {
632 const permissions: ToolPermissions = {
633 policies: [
634 { tool: "Bash", permission: "allow" },
635 { tool: "*", permission: "ask" },
636 ],
637 };
638
639 it("should allow safe commands (echo hello)", () => {
640 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
641 "allowedWithoutPermission",
642 );
643
644 const result = checkToolPermission(
645 { name: "Bash", arguments: { command: "echo hello" } },
646 permissions,
647 );
648
649 expect(result.permission).toBe("allow"); // User preference wins
650 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
651 "allowedWithoutPermission", // converted from "allow"
652 { command: "echo hello" },
653 );
654 });
655
656 it("should allow risky commands based on user preference (curl)", () => {
657 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
658 "allowedWithPermission",
659 );
660
661 const result = checkToolPermission(
662 { name: "Bash", arguments: { command: "curl https://example.com" } },
663 permissions,
664 );
665
666 expect(result.permission).toBe("allow"); // User preference wins over "ask"
667 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
668 "allowedWithoutPermission", // converted from "allow"
669 { command: "curl https://example.com" },
670 );
671 });
672
673 it("should block dangerous commands despite user preference (eval)", () => {
674 mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
675
676 const result = checkToolPermission(
677 { name: "Bash", arguments: { command: "eval 'echo safe'" } },
678 permissions,
679 );
680
681 expect(result.permission).toBe("exclude"); // Security wins
682 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
683 "allowedWithoutPermission", // converted from "allow"
684 { command: "eval 'echo safe'" },
685 );
686 });
687
688 it("should block sudo commands despite user preference", () => {
689 mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
690
691 const result = checkToolPermission(
692 { name: "Bash", arguments: { command: "sudo rm -rf /" } },
693 permissions,
694 );
695
696 expect(result.permission).toBe("exclude"); // Security wins
697 });
698 });
699
700 describe("User has Bash in 'ask' mode (default)", () => {
701 const permissions: ToolPermissions = {
702 policies: [
703 { tool: "Bash", permission: "ask" },
704 { tool: "*", permission: "ask" },
705 ],
706 };
707
708 it("should ask for safe commands based on user preference (echo)", () => {
709 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
710 "allowedWithoutPermission",
711 );
712
713 const result = checkToolPermission(
714 { name: "Bash", arguments: { command: "echo hello" } },
715 permissions,
716 );
717
718 expect(result.permission).toBe("ask"); // User preference wins
719 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
720 "allowedWithPermission", // converted from "ask"
721 { command: "echo hello" },
722 );
723 });
724
725 it("should ask for risky commands (curl)", () => {
726 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
727 "allowedWithPermission",
728 );
729
730 const result = checkToolPermission(
731 { name: "Bash", arguments: { command: "curl https://example.com" } },
732 permissions,
733 );
734
735 expect(result.permission).toBe("ask"); // Both agree on "ask"
736 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
737 "allowedWithPermission", // converted from "ask"
738 { command: "curl https://example.com" },
739 );
740 });
741
742 it("should block dangerous commands (eval)", () => {
743 mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
744
745 const result = checkToolPermission(
746 { name: "Bash", arguments: { command: "eval 'echo safe'" } },
747 permissions,
748 );
749
750 expect(result.permission).toBe("exclude"); // Security wins
751 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
752 "allowedWithPermission", // converted from "ask"
753 { command: "eval 'echo safe'" },
754 );
755 });
756
757 it("should block rm -rf commands", () => {
758 mockBashTool.evaluateToolCallPolicy.mockReturnValue("disabled");
759
760 const result = checkToolPermission(
761 { name: "Bash", arguments: { command: "rm -rf /tmp/important" } },
762 permissions,
763 );
764
765 expect(result.permission).toBe("exclude"); // Security wins
766 });
767 });
768
769 describe("User has Bash in 'exclude' mode", () => {
770 const permissions: ToolPermissions = {
771 policies: [{ tool: "Bash", permission: "exclude" }],
772 };
773
774 it("should always exclude regardless of dynamic evaluation", () => {
775 // Even if dynamic evaluation would allow it
776 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
777 "allowedWithoutPermission",
778 );
779
780 const result = checkToolPermission(
781 { name: "Bash", arguments: { command: "echo hello" } },
782 permissions,
783 );
784
785 expect(result.permission).toBe("exclude"); // User excluded the tool entirely
786 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
787 "disabled", // converted from "exclude"
788 { command: "echo hello" },
789 );
790 });
791 });
792
793 describe("Comprehensive command testing", () => {
794 const permissions: ToolPermissions = {
795 policies: [{ tool: "Bash", permission: "allow" }],
796 };
797
798 const testCases = [
799 // Safe commands
800 {
801 command: "ls",
802 dynamicResult: "allowedWithoutPermission",
803 expected: "allow",
804 },
805 {
806 command: "pwd",
807 dynamicResult: "allowedWithoutPermission",
808 expected: "allow",
809 },
810 {
811 command: "date",
812 dynamicResult: "allowedWithoutPermission",
813 expected: "allow",
814 },
815 {
816 command: "echo test",
817 dynamicResult: "allowedWithoutPermission",
818 expected: "allow",
819 },
820 {
821 command: "git status",
822 dynamicResult: "allowedWithoutPermission",
823 expected: "allow",
824 },
825
826 // Risky commands (user preference wins when not disabled)
827 {
828 command: "npm install pkg",
829 dynamicResult: "allowedWithPermission",
830 expected: "allow",
831 },
832 {
833 command: "rm file.txt",
834 dynamicResult: "allowedWithPermission",
835 expected: "allow",
836 },
837 {
838 command: "curl https://api.example.com",
839 dynamicResult: "allowedWithPermission",
840 expected: "allow",
841 },
842 {
843 command: "wget https://example.com/file",
844 dynamicResult: "allowedWithPermission",
845 expected: "allow",
846 },
847
848 // Dangerous commands (always blocked)
849 {
850 command: "sudo rm -rf /",
851 dynamicResult: "disabled",
852 expected: "exclude",
853 },
854 {
855 command: "exec bash",
856 dynamicResult: "disabled",
857 expected: "exclude",
858 },
859 {
860 command: "eval 'malicious code'",
861 dynamicResult: "disabled",
862 expected: "exclude",
863 },
864 { command: "rm -rf /", dynamicResult: "disabled", expected: "exclude" },
865 ];
866
867 testCases.forEach(({ command, dynamicResult, expected }) => {
868 it(`should handle '${command}' correctly`, () => {
869 mockBashTool.evaluateToolCallPolicy.mockReturnValue(dynamicResult);
870
871 const result = checkToolPermission(
872 { name: "Bash", arguments: { command } },
873 permissions,
874 );
875
876 expect(result.permission).toBe(expected);
877 });
878 });
879 });
880
881 describe("Edge cases", () => {
882 it("should handle tools without dynamic evaluation", () => {
883 // Mock a Read tool without evaluateToolCallPolicy
884 const mockReadTool = {
885 name: "Read",
886 displayName: "Read",
887 description: "Read files",
888 parameters: {
889 type: "object" as const,
890 properties: {},
891 },
892 isBuiltIn: true,
893 run: vi.fn(),
894 // No evaluateToolCallPolicy
895 };
896 vi.mocked(toolsModule.getAllBuiltinTools).mockReturnValue([
897 mockReadTool,
898 mockBashTool,
899 ]);
900
901 const permissions: ToolPermissions = {
902 policies: [{ tool: "Read", permission: "allow" }],
903 };
904
905 const result = checkToolPermission(
906 { name: "Read", arguments: { path: "/tmp/file.txt" } },
907 permissions,
908 );
909
910 expect(result.permission).toBe("allow");
911 expect(mockBashTool.evaluateToolCallPolicy).not.toHaveBeenCalled();
912 });
913
914 it("should use default 'ask' when no policy matches", () => {
915 const permissions: ToolPermissions = {
916 policies: [],
917 };
918
919 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
920 "allowedWithPermission",
921 );
922
923 const result = checkToolPermission(
924 { name: "Bash", arguments: { command: "echo test" } },
925 permissions,
926 );
927
928 expect(result.permission).toBe("ask"); // Default fallback, user preference wins
929 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
930 "allowedWithPermission", // converted from default "ask"
931 { command: "echo test" },
932 );
933 });
934
935 it("should handle null/undefined arguments gracefully", () => {
936 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
937 "allowedWithPermission",
938 );
939
940 const permissions: ToolPermissions = {
941 policies: [{ tool: "Bash", permission: "allow" }],
942 };
943
944 const result = checkToolPermission(
945 { name: "Bash", arguments: {} },
946 permissions,
947 );
948
949 expect(result.permission).toBe("allow");
950 expect(mockBashTool.evaluateToolCallPolicy).toHaveBeenCalledWith(
951 "allowedWithoutPermission",
952 {},
953 );
954 });
955
956 it("should maintain matched policy information", () => {
957 mockBashTool.evaluateToolCallPolicy.mockReturnValue(
958 "allowedWithoutPermission",
959 );
960
961 const policy = { tool: "Bash", permission: "allow" as const };
962 const permissions: ToolPermissions = {
963 policies: [policy],
964 };
965
966 const result = checkToolPermission(
967 { name: "Bash", arguments: { command: "ls" } },
968 permissions,
969 );
970
971 expect(result.matchedPolicy).toBe(policy);
972 });
973 });
974 });
975});