Skip to content

Commit 38aa34a

Browse files
anandgupta42claude
andcommitted
fix: cover mixed operand spellings, symbolic chmod modes and numeric cd in bash permission aliases
- chmod: symbolic modes such as `-w` are the mode operand, not options - cd: numeric targets are tracked; the directory cap keeps the straight-line cwd - aliases: enumerate mixed authored/absolute/symlink-resolved operand spellings Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent 6d44159 commit 38aa34a

2 files changed

Lines changed: 87 additions & 34 deletions

File tree

‎packages/opencode/src/tool/bash.ts‎

Lines changed: 61 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ function literalWord(node: Node | null): string | undefined {
5252

5353
// Cap on tracked directories so pathological scripts cannot blow up alias generation.
5454
const MAX_TRACKED_DIRECTORIES = 32
55+
// Operand-spelling combinations are enumerated in full up to this many operands.
56+
const MAX_MIXED_OPERANDS = 3
57+
const MAX_ALIAS_VARIANTS = 512
5558

5659
// Options that take a separate non-path value; the value must not be read as an operand.
5760
const VALUE_OPTIONS: Record<string, string[]> = {
@@ -76,12 +79,10 @@ function afterCd(cwds: string[], words: Node[]): string[] {
7679
if (args[i] === "--") i++
7780
const target = i < args.length ? args[i] : homedir()
7881
if (target === undefined || target === "-") return cwds
79-
const next = new Set(cwds)
80-
for (const cwd of cwds) {
81-
if (next.size >= MAX_TRACKED_DIRECTORIES) break
82-
next.add(path.resolve(cwd, target))
83-
}
84-
return [...next]
82+
// Newly reachable directories come first so the cap drops the oldest speculative
83+
// branches, never the directory a straight-line script actually enters.
84+
const fresh = cwds.map((cwd) => path.resolve(cwd, target))
85+
return [...new Set([...fresh, ...cwds])].slice(0, MAX_TRACKED_DIRECTORIES)
8586
}
8687

8788
// Walk commands in source order, tracking every directory a command could run in.
@@ -91,7 +92,7 @@ function* shellCommands(node: Node | null, cwds: string[]): Generator<{ node: No
9192
if (node.type === "command") {
9293
yield { node, cwds }
9394
for (const child of node.namedChildren) yield* shellCommands(child, cwds)
94-
const words = shellWords(node)
95+
const words = shellWords(node, true)
9596
return words[0] && literalWord(words[0]) === "cd" ? afterCd(cwds, words) : cwds
9697
}
9798
const local = ["subshell", "command_substitution"].includes(node.type)
@@ -119,7 +120,9 @@ function pathOperands(name: string, words: Node[]): PathOperand[] {
119120
skipNext = false
120121
continue
121122
}
122-
if (!terminated && arg?.startsWith("-")) {
123+
// chmod symbolic modes such as `-w` or `-rwx` are the mode operand, not options.
124+
const symbolicMode = name === "chmod" && arg !== undefined && /^-[ugoa]*[rwxXst]+[ugoa,rwxXst=+-]*$/.test(arg)
125+
if (!terminated && !symbolicMode && arg?.startsWith("-")) {
123126
if (arg === "--") terminated = true
124127
else {
125128
const option = PATH_OPTIONS.find((candidate) => arg.startsWith(candidate + "="))
@@ -317,36 +320,60 @@ export const BashTool = Tool.define("bash", async () => {
317320
directories.add(dir)
318321
}
319322
}
320-
// One spelling keeps the operand's quoting, one is bare, one follows symlinks.
321-
const spellings: ((item: (typeof targets)[number], real: string) => string)[] = [
322-
(item) => item.operand.prefix + quoteLike(item.operand.word, item.target),
323-
(item) => item.operand.prefix + item.target,
324-
(item, real) => item.operand.prefix + (real || item.target),
325-
]
323+
// Each operand can be written as authored, absolute (keeping its quoting), bare
324+
// absolute or symlink-resolved, and the rule may mix them (`cp a /abs/b`).
325+
const written = targets.flatMap((item, index) => (item.operand ? [{ item, real: reals[index] }] : []))
326+
const choices = written.map(({ item, real }) =>
327+
item.operand
328+
? [
329+
item.operand.word.text,
330+
item.operand.prefix + quoteLike(item.operand.word, item.target),
331+
item.operand.prefix + item.target,
332+
item.operand.prefix + (real || item.target),
333+
].filter((value, i, all) => all.indexOf(value) === i)
334+
: [],
335+
)
336+
const combos: number[][] = []
337+
if (written.length <= MAX_MIXED_OPERANDS) {
338+
const expand = (prefix: number[]) => {
339+
if (prefix.length === choices.length) return void combos.push(prefix)
340+
choices[prefix.length].forEach((_, i) => expand([...prefix, i]))
341+
}
342+
expand([])
343+
} else {
344+
for (let i = 0; i < 4; i++) combos.push(choices.map((options) => Math.min(i, options.length - 1)))
345+
}
326346
// `cat -- x` and `cat x` read the same file, so also alias the form without `--`.
327347
const terminator =
328348
name === "cd" ? undefined : operandWords.slice(1).find((word) => literalWord(word) === "--")
329-
for (const spell of spellings.flatMap((fn) =>
330-
terminator ? [[fn, false] as const, [fn, true] as const] : [[fn, false] as const],
331-
)) {
332-
const [fn, dropTerminator] = spell
333-
const replacements = targets
334-
.filter((item) => item.operand)
335-
.map((item) => ({
336-
start: item.operand.word.startIndex,
337-
end: item.operand.word.endIndex,
338-
text: fn(item, reals[targets.indexOf(item)]),
339-
}))
340-
if (listing) replacements.push({ start: node.endIndex, end: node.endIndex, text: ` ${commandCwd}` })
341-
if (terminator && dropTerminator)
342-
replacements.push({ start: terminator.startIndex - 1, end: terminator.endIndex, text: "" })
343-
let text = original
344-
for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
345-
const start = replacement.start - source.startIndex
346-
const end = replacement.end - source.startIndex
347-
text = text.slice(0, start) + replacement.text + text.slice(end)
349+
for (const combo of combos) {
350+
for (const dropTerminator of terminator ? [false, true] : [false]) {
351+
if (variants.size >= MAX_ALIAS_VARIANTS) break
352+
const replacements = written
353+
.map(({ item }, index) => ({
354+
start: item.operand?.word.startIndex ?? 0,
355+
end: item.operand?.word.endIndex ?? 0,
356+
text: choices[index][combo[index]],
357+
skip: !item.operand,
358+
}))
359+
.filter((replacement) => !replacement.skip)
360+
if (listing)
361+
replacements.push({ start: node.endIndex, end: node.endIndex, text: ` ${commandCwd}`, skip: false })
362+
if (terminator && dropTerminator)
363+
replacements.push({
364+
start: terminator.startIndex - 1,
365+
end: terminator.endIndex,
366+
text: "",
367+
skip: false,
368+
})
369+
let text = original
370+
for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
371+
const start = replacement.start - source.startIndex
372+
const end = replacement.end - source.startIndex
373+
text = text.slice(0, start) + replacement.text + text.slice(end)
374+
}
375+
variants.add(text)
348376
}
349-
variants.add(text)
350377
}
351378
}
352379
}

‎packages/opencode/test/tool/bash.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ describe("tool.bash permissions", () => {
102102
["cd -P ../sibling && cat output.md", "cat", "sibling/output.md"],
103103
["cd ../sibling && cat output.md &", "cat", "sibling/output.md"],
104104
["cat -- ../sibling/output.md", "cat", "sibling/output.md"],
105+
["chmod -w ../sibling/output.md", "chmod -w", "sibling/output.md"],
106+
["cd ../sibling; cd a; cd b; cd c; cd d; cd e; cd f; cat output.md", "cat", "sibling/a/b/c/d/e/f/output.md"],
105107
["cd missing; cd ../sibling; cat output.md", "cat", "sibling/output.md"],
106108
])("denies normalized paths in %s", async (command, executable, target) => {
107109
await using tmp = await tmpdir({ git: true })
@@ -180,6 +182,30 @@ describe("tool.bash permissions", () => {
180182
})
181183
})
182184

185+
test("denies mixed authored and absolute operand spellings and numeric cd targets", async () => {
186+
await using tmp = await tmpdir({ git: true })
187+
await provideInstance(tmp.path, async () => {
188+
const bash = await initTool(BashTool)
189+
const deny = async (rule: string, command: string) => {
190+
const ruleset: PermissionNext.Ruleset = [
191+
{ permission: "*", pattern: "*", action: "allow" },
192+
{ permission: "bash", pattern: rule, action: "deny" },
193+
]
194+
const testCtx = {
195+
...ctx,
196+
ask: async (request: Omit<PermissionNext.Request, "id" | "sessionID" | "tool">) => {
197+
for (const pattern of request.patterns) {
198+
if (evaluateRequest(request, pattern, ruleset).action === "deny") throw new Error("Path denied")
199+
}
200+
},
201+
}
202+
await expect(bash.execute({ command, description: "Probe" }, testCtx)).rejects.toThrow("Path denied")
203+
}
204+
await deny(`cp public.txt ${path.join(tmp.path, "private.txt")}`, "cp public.txt private.txt")
205+
await deny(`cat ${path.join(tmp.path, "123", "secret")}`, "cd 123 && cat secret")
206+
})
207+
})
208+
183209
test("denies a symlinked operand by its resolved destination", async () => {
184210
await using tmp = await tmpdir({ git: true })
185211
await fs.mkdir(path.join(tmp.path, "real"))

0 commit comments

Comments
 (0)