Repository navigation
Expand file tree
/
Copy pathclassifier.ts
More file actions
454 lines (385 loc) · 16.3 KB
/
Copy pathclassifier.ts
File metadata and controls
454 lines (385 loc) · 16.3 KB
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
/**
* Shell Command Classifier
*
* Tiers:
* - readonly: positive allowlist of read-only commands
* - normal: everything else that isn't mass-destructive/forbidden
* - mass-destructive: bulk/recursive deletion operations
* - forbidden: catastrophic patterns + non-allowlisted git commands
*/
import { resolve } from 'path'
import { parseShellCommand, type SimpleCommand } from './parser'
import { isGitReadOnly } from './tools/git'
import { isContainerForbidden } from './tools/container'
import { isKubectlForbidden, isHelmForbidden } from './tools/kubernetes'
import { isCloudCliForbidden } from './tools/cloud-cli'
import { isIacForbidden } from './tools/iac'
import { isDatabaseForbidden, isDatabaseUtilityForbidden } from './tools/database'
import {
SYSADMIN_ALWAYS_FORBIDDEN,
SYSADMIN_BLOCKLIST,
PACKAGE_MANAGERS,
isSysadminForbidden,
getSysadminAlwaysForbiddenReason,
isPackageManagerForbidden,
} from './tools/sysadmin'
import { isLangPackageManagerForbidden } from './tools/package-managers'
import type { ClassificationResult, ShellSafetyTier } from './types'
export function classifyShellCommand(command: string): ClassificationResult {
const commands = parseShellCommand(command)
let worst: ShellSafetyTier = 'readonly'
let forbiddenReason: string | null = null
for (const cmd of commands) {
const result = classifyCommand(cmd)
worst = worstTier(worst, result.tier)
if (result.reason) forbiddenReason = result.reason
if (worst === 'forbidden') return { tier: 'forbidden', reason: forbiddenReason }
}
return { tier: worst, reason: null }
}
export function isGitAllowed(command: string): boolean {
const commands = parseShellCommand(command)
for (const cmd of commands) {
if (!cmd.name) continue
const name = baseName(cmd.name)
if (name !== 'git') continue
if (!isGitReadOnly(cmd.args)) return false
}
return true
}
export function writesStayWithin(command: string, env: Record<string, string>, ...allowedRoots: string[]): boolean {
const commands = parseShellCommand(command)
const initialCwd = allowedRoots[0] ?? process.cwd()
let effectiveCwd = initialCwd
let previousCwd: string | null = null
for (const cmd of commands) {
if (cmd.name) {
const name = baseName(cmd.name)
if (name === 'cd') {
const oldCwd = effectiveCwd
const target = cmd.args[0]
let resolvedTarget: string
if (!target) {
const home = env.HOME ?? env.USERPROFILE
if (!home) return false
resolvedTarget = expandAndResolve(home, env, effectiveCwd)
} else if (target === '-') {
if (!previousCwd) return false
resolvedTarget = previousCwd
} else {
if (hasUndefinedEnvVars(target, env)) return false
if (target.startsWith('~') && !env.HOME && !env.USERPROFILE) return false
resolvedTarget = expandAndResolve(target, env, effectiveCwd)
}
previousCwd = oldCwd
effectiveCwd = resolvedTarget
continue
}
}
for (const redir of cmd.redirects) {
const resolvedTarget = expandAndResolve(redir.target, env, effectiveCwd)
if (!isPathWithin(resolvedTarget, env, ...allowedRoots)) return false
}
if (cmd.name) {
const name = baseName(cmd.name)
if (WRITE_PATH_COMMANDS.has(name)) {
for (const arg of cmd.args) {
if (arg.startsWith('-')) continue
const resolvedArg = expandAndResolve(arg, env, effectiveCwd)
if (!isPathWithin(resolvedArg, env, ...allowedRoots)) return false
}
}
}
}
return true
}
// ─── Classification ─────────────────────────────────────────
const TIER_ORDER: Record<ShellSafetyTier, number> = {
readonly: 0,
normal: 1,
'mass-destructive': 2,
forbidden: 3
}
function worstTier(a: ShellSafetyTier, b: ShellSafetyTier): ShellSafetyTier {
return TIER_ORDER[a] >= TIER_ORDER[b] ? a : b
}
function classifyCommand(cmd: SimpleCommand): ClassificationResult {
if (!cmd.name) {
if (cmd.assignments.length === 0) return { tier: 'readonly', reason: null }
let worst: ShellSafetyTier = 'readonly'
let forbiddenReason: string | null = null
for (const a of cmd.assignments) {
const assignmentResult = classifyAssignmentValue(a.value)
worst = worstTier(worst, assignmentResult.tier)
if (assignmentResult.reason) forbiddenReason = assignmentResult.reason
if (worst === 'forbidden') return { tier: 'forbidden', reason: forbiddenReason }
}
return { tier: worst, reason: null }
}
if (cmd.assignments.length > 0) return { tier: 'normal', reason: null }
const hasRedirects = cmd.redirects.length > 0
const name = baseName(cmd.name)
const args = cmd.args
if ((name === 'bash' || name === 'sh' || name === 'zsh') && isShellCInvocation(name, args)) {
const innerCommand = extractShellCCommand(args)
if (innerCommand) return classifyShellCommand(innerCommand)
return { tier: 'normal', reason: null }
}
if (name === 'sudo') {
const innerCmd: SimpleCommand = { assignments: [], name: args[0] ?? null, args: args.slice(1), redirects: cmd.redirects }
const innerResult = classifyCommand(innerCmd)
if (innerResult.tier === 'forbidden' || innerResult.tier === 'mass-destructive') return innerResult
return { tier: 'normal', reason: null }
}
const forbiddenReason = isForbidden(name, args)
if (forbiddenReason) return { tier: 'forbidden', reason: forbiddenReason }
if (isMassDestructive(name, args)) return { tier: 'mass-destructive', reason: null }
if (isReadOnly(name, args)) return { tier: hasRedirects ? 'normal' : 'readonly', reason: null }
return { tier: 'normal', reason: null }
}
function classifyAssignmentValue(value: string): ClassificationResult {
const subs = extractCommandSubstitutions(value)
if (subs.length === 0) return { tier: 'readonly', reason: null }
let worst: ShellSafetyTier = 'readonly'
let forbiddenReason: string | null = null
for (const sub of subs) {
const result = classifyShellCommand(sub)
worst = worstTier(worst, result.tier)
if (result.reason) forbiddenReason = result.reason
if (worst === 'forbidden') return { tier: 'forbidden', reason: forbiddenReason }
}
return { tier: worst, reason: null }
}
function extractCommandSubstitutions(value: string): string[] {
const results: string[] = []
let i = 0
while (i < value.length) {
if (value[i] === '$' && value[i + 1] === '(') {
let depth = 1
const start = i + 2
let j = start
while (j < value.length && depth > 0) {
if (value[j] === '(') depth++
else if (value[j] === ')') depth--
if (depth > 0) j++
}
if (depth === 0) results.push(value.slice(start, j))
i = j + 1
} else {
i++
}
}
return results
}
function isShellCInvocation(_name: string, args: string[]): boolean {
if (args.length < 2) return false
if (args[0] === '-lc' || args[0] === '-c') return true
if (args[0] === '-l' && args[1] === '-c') return true
return false
}
function extractShellCCommand(args: string[]): string | null {
if (args[0] === '-lc' || args[0] === '-c') return args[1] ?? null
if (args[0] === '-l' && args[1] === '-c') return args[2] ?? null
return null
}
const READONLY_COMMANDS = new Set([
'cat', 'cd', 'cut', 'echo', 'expr', 'false', 'grep', 'head', 'id', 'ls',
'nl', 'paste', 'pwd', 'rev', 'seq', 'stat', 'tail', 'tr', 'true', 'uname',
'uniq', 'wc', 'which', 'whoami', 'tac', 'numfmt', 'less', 'more', 'file',
'du', 'df', 'env', 'printenv', 'date', 'hostname', 'sort', 'dirname',
'basename', 'realpath', 'readlink', 'test', '[', 'type', 'command',
'jq', 'awk', 'gawk', 'mawk', 'nawk',
'column', 'fmt', 'fold', 'comm', 'diff', 'strings', 'od', 'hexdump', 'tree',
])
function isMassDestructive(cmd: string, args: string[]): boolean {
if (cmd === 'rm') return hasRecursiveRmFlag(args)
if (cmd === 'find') return isFindMassDestructive(args)
if (cmd === 'rsync') return isRsyncMassDestructive(args)
return false
}
function hasRecursiveRmFlag(args: string[]): boolean {
let optionsEnded = false
for (const arg of args) {
if (optionsEnded) continue
if (arg === '--') {
optionsEnded = true
continue
}
if (arg === '--recursive') return true
if (!arg.startsWith('-') || arg === '-') continue
if (arg.startsWith('--')) continue
const flags = arg.slice(1)
if (flags.includes('r') || flags.includes('R')) return true
}
return false
}
function isFindMassDestructive(args: string[]): boolean {
for (let i = 0; i < args.length; i++) {
const arg = args[i]
if (arg === '-delete') return true
if (arg !== '-exec' && arg !== '-execdir') continue
const command = args[i + 1]
if (!command) continue
if (baseName(command) === 'rm') return true
}
return false
}
function isRsyncMassDestructive(args: string[]): boolean {
return args.some(arg =>
arg === '--delete' ||
arg === '--delete-before' ||
arg === '--delete-during' ||
arg === '--delete-delay' ||
arg === '--delete-after'
)
}
function isReadOnly(cmd: string, args: string[]): boolean {
if (READONLY_COMMANDS.has(cmd)) return true
if (cmd === 'find') return isFindSafe(args)
if (cmd === 'git') return isGitReadOnly(args)
if (cmd === 'rg') return isRipgrepSafe(args)
if (cmd === 'sed') return isSedSafe(args)
if (cmd === 'base64') return isBase64Safe(args)
if (cmd === 'yq') return isYqSafe(args)
if (cmd === 'fd' || cmd === 'fdfind') return isFdSafe(args)
if (cmd === 'ag') return true
return false
}
function isFindSafe(args: string[]): boolean {
const unsafeOptions = new Set(['-exec', '-execdir', '-ok', '-okdir', '-delete', '-fls', '-fprint', '-fprint0', '-fprintf'])
return !args.some(arg => unsafeOptions.has(arg))
}
function isRipgrepSafe(args: string[]): boolean {
const unsafeNoArg = new Set(['--search-zip', '-z'])
const unsafeWithArg = ['--pre', '--hostname-bin']
return !args.some(arg =>
unsafeNoArg.has(arg) ||
unsafeWithArg.some(opt => arg === opt || arg.startsWith(`${opt}=`))
)
}
function isSedSafe(args: string[]): boolean {
for (const arg of args) {
if (!arg.startsWith('-')) continue
if (arg === '--in-place' || arg.startsWith('--in-place=')) return false
if (arg === '--file' || arg.startsWith('--file=')) return false
if (arg.startsWith('--')) continue
const flags = arg.slice(1)
if (containsUnsafeSedFlag(flags)) return false
}
return true
}
function containsUnsafeSedFlag(flags: string): boolean {
for (let i = 0; i < flags.length; i++) {
const ch = flags[i]
if (ch === 'i') return true
if (ch === 'f') return true
if (ch === 'e') return false
}
return false
}
function isBase64Safe(args: string[]): boolean {
return !args.some(arg =>
arg === '-o' || arg === '--output' ||
arg.startsWith('--output=') ||
(arg.startsWith('-o') && arg !== '-o')
)
}
function isYqSafe(args: string[]): boolean {
return !args.some(arg => arg === '-i' || arg === '--inplace' || arg.startsWith('--inplace='))
}
function isFdSafe(args: string[]): boolean {
const unsafeOptions = new Set(['-x', '--exec', '-X', '--exec-batch'])
return !args.some(arg => unsafeOptions.has(arg))
}
const SYSTEM_DIRS = new Set(['/etc', '/usr', '/System', '/bin', '/sbin', '/boot', '/var', '/lib', '/dev', '/proc', '/sys'])
const CONTAINER_TOOLS = new Set(['docker', 'podman', 'nerdctl'])
const CLOUD_CLIS = new Set(['aws', 'gcloud', 'az'])
const IAC_TOOLS = new Set(['terraform', 'terragrunt', 'pulumi', 'sst', 'cdk'])
const DB_SHELLS_FORBIDDEN = new Set(['psql', 'mysql', 'mariadb', 'mongosh', 'mongo', 'redis-cli', 'sqlcmd'])
const DB_UTILITY_TOOLS = new Set(['pg_dump', 'mysqldump', 'createdb', 'createuser', 'dropdb', 'dropuser', 'pg_restore'])
const LANG_PACKAGE_MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun', 'twine', 'poetry', 'uv', 'cargo', 'gem', 'mvn', 'gradle', 'gradlew', 'dotnet', 'mix', 'swift'])
function isForbidden(cmd: string, args: string[]): string | null {
if (cmd === ':') return 'This command is blocked as a shell-control sentinel, not a useful task action. Use a read-only check like `pwd` or `ls` instead.'
if (cmd === 'mkfs') return 'Formatting filesystems can irreversibly erase disk data. Use read-only disk inspection like `lsblk` or `diskutil list` instead.'
if (cmd === 'dd' && args.some(a => a.startsWith('if=') || a.startsWith('of=/dev'))) {
return 'Raw device copy/write can destroy entire disks quickly. Use file-level copy commands on workspace files only.'
}
if (cmd === 'rm') {
const hasForce = args.some(a => a === '-rf' || a === '-fr' || a === '-f')
const targetsSystem = args.some(a => {
if (a.startsWith('-')) return false
return a === '/' || SYSTEM_DIRS.has(a) || Array.from(SYSTEM_DIRS).some(d => a.startsWith(d + '/'))
})
if (hasForce && targetsSystem) {
return 'Force-deleting system paths can break the host environment irrecoverably. Delete only explicit project-local paths after listing them first.'
}
}
if (cmd === 'git' && !isGitReadOnly(args)) {
return 'Mutating git actions can permanently discard or rewrite history. Use read-only git commands like `git status`, `git log`, or `git diff`.'
}
return isForbiddenByToolPolicy(cmd, args)
}
function isForbiddenByToolPolicy(base: string, args: readonly string[]): string | null {
if (CONTAINER_TOOLS.has(base)) return isContainerForbidden(base, args)
if (base === 'kubectl') return isKubectlForbidden(args)
if (base === 'helm') return isHelmForbidden(args)
if (CLOUD_CLIS.has(base)) return isCloudCliForbidden(base, args)
if (IAC_TOOLS.has(base)) return isIacForbidden(base, args)
if (DB_SHELLS_FORBIDDEN.has(base)) return isDatabaseForbidden(base, args)
if (DB_UTILITY_TOOLS.has(base)) return isDatabaseUtilityForbidden(base, args)
if (SYSADMIN_ALWAYS_FORBIDDEN.has(base)) return getSysadminAlwaysForbiddenReason(base)
if (SYSADMIN_BLOCKLIST.has(base)) return isSysadminForbidden(base, args)
if (LANG_PACKAGE_MANAGERS.has(base)) {
const result = isLangPackageManagerForbidden(base, args)
if (result) return result
}
if (PACKAGE_MANAGERS.has(base)) return isPackageManagerForbidden(base, args)
return null
}
const WRITE_PATH_COMMANDS = new Set(['rm', 'cp', 'mv', 'tee', 'mkdir', 'touch', 'chmod', 'chown', 'ln', 'install', 'rsync'])
function baseName(cmd: string): string {
const i = cmd.lastIndexOf('/')
return i === -1 ? cmd : cmd.slice(i + 1)
}
const ALLOWED_OUTSIDE_PREFIXES = ['/tmp/', '/dev/null']
function hasUndefinedEnvVars(str: string, env: Record<string, string>): boolean {
const refs = str.matchAll(/\$\{(\w+)\}|\$(\w+)/g)
for (const match of refs) {
const key = match[1] ?? match[2]
if (!(key in env)) return true
}
return false
}
function expandEnvVars(p: string, env: Record<string, string>): string {
return p.replace(/\$\{(\w+)\}|\$(\w+)/g, (_, braced, bare) => {
const key = braced ?? bare
return env[key] ?? ''
})
}
function expandAndResolve(path: string, env: Record<string, string>, baseCwd: string): string {
const expanded = expandEnvVars(path, env)
if (expanded.startsWith('~')) {
const home = env.HOME ?? env.USERPROFILE ?? ''
return resolve(home, expanded.slice(expanded.startsWith('~/') ? 2 : 1))
}
const baseCwdNoSlash = baseCwd.endsWith('/') ? baseCwd.slice(0, -1) : baseCwd
return resolve(baseCwdNoSlash, expanded)
}
export function isPathWithin(path: string, env: Record<string, string>, ...allowedRoots: string[]): boolean {
if (!path || path.startsWith('-')) return true
const [primaryRoot, ...additionalRoots] = allowedRoots
const cwd = primaryRoot ?? process.cwd()
const normalizedCwd = cwd.endsWith('/') ? cwd : cwd + '/'
const cwdNoSlash = cwd.endsWith('/') ? cwd.slice(0, -1) : cwd
const resolved = expandAndResolve(path, env, cwdNoSlash)
if (resolved === cwdNoSlash || resolved.startsWith(normalizedCwd)) return true
const explicitRoots = [cwd, ...additionalRoots]
if (explicitRoots.some(root => {
const normalizedRoot = root.endsWith('/') ? root : `${root}/`
const rootNoSlash = root.endsWith('/') ? root.slice(0, -1) : root
return resolved === rootNoSlash || resolved.startsWith(normalizedRoot)
})) return true
const builtInAllowlist = ALLOWED_OUTSIDE_PREFIXES
if (builtInAllowlist.some(p => resolved === p.slice(0, -1) || resolved.startsWith(p))) return true
return false
}