Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

policy.test.ts

72 lines2.6 KB

1import { describe, expect, it } from 'vitest'
2import { defineSandboxPolicy, evaluateCommand } from '../src/policy'
3​
4describe('evaluateCommand', () => {
5 const policy = defineSandboxPolicy({
6 commands: {
7 allow: ['pnpm test', 'pnpm typecheck', 'git diff'],
8 ask: ['pnpm install', 'curl *', 'wget *'],
9 deny: ['sudo *', 'rm -rf *'],
10 },
11 default: 'ask',
12 })
13​
14 it('allows exact allow matches', () => {
15 expect(evaluateCommand('pnpm test', policy)).toBe('allow')
16 expect(evaluateCommand('git diff', policy)).toBe('allow')
17 })
18​
19 it('asks for ask matches incl. globs', () => {
20 expect(evaluateCommand('pnpm install', policy)).toBe('ask')
21 expect(evaluateCommand('curl https://example.com', policy)).toBe('ask')
22 })
23​
24 it('denies deny matches incl. globs', () => {
25 expect(evaluateCommand('sudo apt-get update', policy)).toBe('deny')
26 expect(evaluateCommand('rm -rf /', policy)).toBe('deny')
27 })
28​
29 it('deny beats ask beats allow (precedence)', () => {
30 const overlap = defineSandboxPolicy({
31 commands: {
32 allow: ['git *'],
33 ask: ['git push *'],
34 deny: ['git push --force*'],
35 },
36 })
37 expect(evaluateCommand('git status', overlap)).toBe('allow')
38 expect(evaluateCommand('git push origin main', overlap)).toBe('ask')
39 expect(evaluateCommand('git push --force origin main', overlap)).toBe(
40 'deny',
41 )
42 })
43​
44 it('falls back to default for unmatched commands', () => {
45 expect(evaluateCommand('node script.js', policy)).toBe('ask')
46 expect(evaluateCommand('node script.js', { default: 'deny' })).toBe('deny')
47 expect(evaluateCommand('node script.js', undefined)).toBe('ask')
48 })
49​
50 it('does not let glob metachars leak across command boundaries', () => {
51 // 'rm -rf *' must not match an unrelated 'confirm -rf safe' string.
52 expect(evaluateCommand('confirm -rf safe', policy)).toBe('ask')
53 })
54​
55 it('matches policy patterns against script names and expanded values', () => {
56 const scripts = { test: 'pnpm test', build: 'pnpm build' }
57 const scriptPolicy = defineSandboxPolicy({
58 commands: {
59 allow: ['test', 'pnpm build'],
60 deny: ['deploy'],
61 },
62 default: 'ask',
63 })
64​
65 expect(evaluateCommand('test', scriptPolicy, scripts)).toBe('allow')
66 expect(evaluateCommand('pnpm test', scriptPolicy, scripts)).toBe('allow')
67 expect(evaluateCommand('build', scriptPolicy, scripts)).toBe('allow')
68 expect(evaluateCommand('pnpm build', scriptPolicy, scripts)).toBe('allow')
69 expect(evaluateCommand('deploy', scriptPolicy, scripts)).toBe('deny')
70 expect(evaluateCommand('pnpm deploy', scriptPolicy, scripts)).toBe('ask')
71 })
72})