import { afterAll, describe, expect, test } from "bun:test" import { Effect, Exit } from "effect" import fs from "fs" import os from "os" import path from "path" import { ShellParse } from "../../src/shell/parse.js" import { ShellScan } from "../../src/shell/scan.js" const shellCandidates = ["/bin/bash", "/opt/homebrew/bin/bash", "/usr/local/bin/bash", "bash", "zsh", "dash"] const shells = [ ...new Set( shellCandidates .map((item) => (item.startsWith("/") ? (fs.existsSync(item) ? item : undefined) : Bun.which(item))) .filter((item): item is string => Boolean(item)), ), ] // Fixtures target specific shells and versions (bash 3.2 and 5.3, zsh, dash). Set SHELL_ORACLE_STRICT=1 on a // machine with all of them to also verify that every fixture still executes somewhere. const strict = process.env.SHELL_ORACLE_STRICT === "1" const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-shell-oracle-")) const bin = path.join(root, "bin") const target = path.join(root, "target") const log = path.join(root, "log") fs.mkdirSync(bin) fs.mkdirSync(target) fs.writeFileSync( path.join(bin, "scan_probe"), '#!/bin/sh\nprintf \'%s\\n\' "scan_probe${1:+ $*}" >> "$SCAN_PROBE_LOG"\n', { mode: 0o755, }, ) // Dash runs `scan_probe[x y]=1` as the command `scan_probe[x`. fs.copyFileSync(path.join(bin, "scan_probe"), path.join(bin, "scan_probe[x")) // Zsh treats a trailing parenthesized group after an existing file name as glob qualifiers. fs.writeFileSync(path.join(root, "a="), "") afterAll(() => fs.rmSync(root, { recursive: true, force: true })) function shellFlags(executable: string) { if (executable.endsWith("/bash")) return ["--noprofile", "--norc"] if (executable.endsWith("/zsh")) return ["-f"] return [] } // Runs source in a real shell and returns the lines it logged. function observe(executable: string, source: string) { fs.writeFileSync(log, "") Bun.spawnSync([executable, ...shellFlags(executable), "-c", source], { cwd: root, env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root, LC_ALL: "C", SCAN_PROBE_LOG: log }, timeout: 2_000, }) return fs .readFileSync(log, "utf8") .split("\n") .map((line) => line.trim()) .filter(Boolean) } // Each dialect must report what its shells run; posix, the default, covers every shell. const dialects = { bash: (executable: string) => path.basename(executable) === "bash", zsh: (executable: string) => path.basename(executable) === "zsh", posix: () => true, } satisfies Record boolean> function expectProbesReported(source: string) { const runs = shells.map((executable) => [executable, observe(executable, source)] as const) if (strict) expect( runs.some(([, invocations]) => invocations.length > 0), `Fixture never executed scan_probe in any real shell: ${source}`, ).toBe(true) expect(ShellScan.scan(source)).toEqual(ShellScan.scan(source, "posix")) for (const [dialect, runsIn] of Object.entries(dialects)) { const result = ShellScan.scan(source, dialect as ShellScan.Dialect) if (result.kind === "opaque") continue const reported = result.commands.filter((command) => !command.declaration).map((command) => command.words.join(" ")) for (const [executable, invocations] of runs.filter(([executable]) => runsIn(executable))) for (const invocation of invocations) expect(reported, `${executable} executed ${invocation} with ${dialect} in: ${source}`).toContain(invocation) } } // Each fixture runs scan_probe in at least one real shell, which the scanner must report or reject. const fixtures = [ "a=(1)scan_probe", "a=(\n1)scan_probe; ", "a=(1)'scan_probe'", "alias p=scan_probe\np", "command alias p=scan_probe\np", "x='*(e:scan_probe:)'; echo $^~x", "x='$(scan_probe)'; echo \"${\\\n(e)x}\"", "x='$(scan_probe)'; echo ${(j:):e)x}", "x='*(e:scan_probe:)'; echo ${(f)~x}", "x='*(e:scan_probe:)'; echo ${=~x}", "x='*(e:scan_probe:)'; echo $=~x", "x='$(scan_probe)'; echo ${(%e)x}", "x='$(scan_probe)'; echo ${(s.:.e)x}", "x='$(scan_probe)'; echo ${(s(:)e)x}", "x='$(scan_probe)'; echo ${(ej: :)x}", "x='*(e:scan_probe:)'; echo ${(s: :)~x}", "x='*(e:scan_probe:)'; echo ${^~x}", "printf -v x 'a[$(scan_probe)]'; echo $((x))", "a=(1); getopts a: x -a 'a[$(scan_probe)]'; echo $((OPTARG))", "command -- declare 'a[$(scan_probe)]=1'", "a=(1); unset 'a[b[$\\\n(scan_probe)0]]'", 'declare \'a["\\"]"$(scan_probe)0]=1\'', "declare -a 'a=(+ [$(scan_probe)]=1)'", "a=(1); echo ${a[b[\\$(scan_probe)]]}", 'a["b[\\$(scan_probe)]"]=1', 'b=1; a["b[\\$(scan_probe)1]"]=1', "a=(1); echo $[ ${x:-a[\\$(scan_probe)1]} ]", "a=(1); s=abc; echo ${s:'a[$(scan_probe)0]'}", "a=(1); s=abc; echo ${s:${x:-'a[$(scan_probe)1]'}}", "read x <<< 'a[$(scan_probe f)]'; echo $((x))", "mapfile -t a <<< 'b[$(scan_probe g)]'; echo $((a[0]))", "x=1; echo $(( x[\\$(scan_probe i)] ))", "a=(1); echo ${a[@]:'a[$(scan_probe k)]'}", "builtin -- declare 'a[$(scan_probe)]=1'", "command -p declare 'a[$(scan_probe)]=1'", 'echo "${unset:+${x[\'"\']}}"]}} \'$(scan_probe)\' " # "', "echo \"${unset:+${x['}}\"']}}'; scan_probe # \"", "echo \"${x:-$'\\''}\"; scan_probe # '\"", "cat </dev/null scan_probe", "2>&1 scan_probe", "A=1 >/dev/null B=2 scan_probe", 'export A=1 B="$(scan_probe)"', 'declare -a arr=(1 "$(scan_probe)")', "export X=$'a'\\\n; scan_probe", "case x in \\\nx) \\\nscan_probe;; \\\nesac", "if true; then \\\nscan_probe; fi", '() { :; } "$(scan_probe)"', "function f() ( scan_probe ); f", "{ export X=1 } && scan_probe", "{ export X=1 } ; scan_probe ; }", // Dialects disagree about reserved words after redirects and operators split by line continuations. "if true; then >/dev/null fi; scan_probe; fi", "if true; then >/dev/null fi; scan_probe", "case x in x) >/dev/null esac; scan_probe; esac", "true &>/dev/null scan_probe", "true &>>/dev/null scan_probe", "true &\\\n>/dev/null scan_probe", "cat <<\\\n-EOF\nEOF\nscan_probe h1\n-EOF", "cat <<\\\n-EOF\n-EOF\nscan_probe z\nEOF", "cat <\\\n(scan_probe i)", "[[ -n <\\\n(scan_probe c1) ]]", "a=(<\\\n(scan_probe a1))", "cat <(scan_probe g)}", "x=${y:-<(scan_probe p4)}", "[[ x == ${y:-<(scan_probe p5)} ]]", "echo $(( $'$(scan_probe a)' ))", "(( x = $'$(scan_probe b)' ))", "echo $(( ${x:-'$(scan_probe a)'} ))", "(( ${x:-'$(scan_probe b)'} ))", "a[${x:-'$(scan_probe c)'}]=1", "echo $[ ${x:-'$(scan_probe d)'} ]", "echo $[ $'$(scan_probe h)' ]", "echo ${a[${x:-'$(scan_probe e)'}]}", "echo \"${a[${x:-'$(scan_probe f)'}]}\"", "cat <*(e:'scan_probe f':)", "cat <*(e:'scan_probe g':)", "echo $x*(e:'scan_probe h':)", "echo \"\"*(e:'scan_probe i':)", "echo {a,*(e:'scan_probe m':)}", // Builtins and arithmetic evaluate subscripts in decoded literal text. "declare -i x='a[$(scan_probe)]'", "declare 'a[$(scan_probe)]=1'", "declare -a 'a=([$(scan_probe)]=1)'", "a=(1); unset 'a[$(scan_probe)]'", 'a=(1); unset "a[\\$(scan_probe)]"', "[[ 'a[$(scan_probe)]' -eq 1 ]]", "[[ -v 'a[$(scan_probe)]' ]]", "read 'a[$(scan_probe)]' /dev/null", "READNULLCMD=scan_probe; /dev/null", "x=${READNULLCMD::=scan_probe}; /dev/null", ": ${^NULLCMD::=scan_probe}; >/dev/null", ": ${(f)NULLCMD::=scan_probe}; >/dev/null", "print -vNULLCMD scan_probe; >/dev/null", "(( ${NULLCMD::=scan_probe} )); >/dev/null", "[[ -n ${NULLCMD::=scan_probe} ]]; >/dev/null", "a=(${NULLCMD::=scan_probe}); >/dev/null", ": </dev/null", "PS4='$(scan_probe)'; set -x; x=1", "PS4='$(scan_probe)'; set -o xtrace; x=1", "export PS4='$(scan_probe)'; set -x; x=1", "setopt -m 'glob*'; x='*(e:scan_probe:)'; echo $x", "setopt -m '*subst*'; x='*(e:scan_probe:)'; echo $x", "emulate sh; unsetopt shglob; setopt bareglobqual; x='*(e:scan_probe:)'; echo $x", "emulate ksh; unsetopt shglob; setopt bareglobqual; x='*(e:scan_probe:)'; echo $x", "a=(1); zregexparse 'a[$(scan_probe)]' 'a[$(scan_probe)]' x /x/", "a=(1); private 'a[$(scan_probe)]=1'", "a=(1); [[ x =~ (a )(b)]] || 0 -eq 'a[$(scan_probe)]' ]]", "a=(1); [[ x =~ (a )(b)]] || -v 'a[$(scan_probe)]' ]]", "a=(1); [[ -t 'a[$(scan_probe)]' ]]", "a=(1); x='a[$(scan_probe)]'; [[ -t x ]]", "a=(1); x='a[$(scan_probe)]'; [[ -t $x ]]", "a=(1); test -t 'a[$(scan_probe)]'", "a=(1); [ -t 'a[$(scan_probe)]' ]", "a=(1); x='a[$(scan_probe)]'; test -t x", "a=(1); x='a[$(scan_probe)]'; [ -t x ]", "echo $\\\n'a\\''; scan_probe; : \\'", ": <<$\\\n'EOF'\nEOF\nscan_probe\n$EOF", ': <<$\\\n"EOF"\nEOF\nscan_probe\n$EOF', "$\\\n'scan_probe'", '$\\\n"scan_probe"', "a=(1); unset $\\\n'a[\\x24(scan_probe)]'", "echo \"${x:-$\\\n'\\x24(scan_probe)'}\"", "[[ -n x ]\\\n] && scan_probe && [[ -n y ]]", "a=(1); (\\\n( 'a[$(scan_probe)]' ))", "a=(1); (\\\n( 1 + 'a[$(scan_probe)]' ))", "a=(1); echo $(\\\n( 'a[$(scan_probe)]' ))", "a=(1); x='a[$(scan_probe)]'; echo $(( x )\\\n)", "a=(1); [\\\n[ -v 'a[$(scan_probe)]' ]]", "a=(1); [\\\n[ 0 -eq 'a[$(scan_probe)]' ]]", "a[0]\\\n=1 scan_probe", "a[0]+\\\n=1 scan_probe", "a=(); a[0]\\\n='a[$(scan_probe)]'; echo $((a[0]))", "x='x y'; scan_probe[$x]\\\n=1", "a=(1); x='a[$_1]'; y='(scan_probe)'; unset \"${x/_1/$y}\"", "a=(1); x='a[$_1]'; y='(scan_probe)'; echo $(( ${x/_1/$y} ))", "a=(1); x='a[$1'; y='(scan_probe)]'; echo $(( ${x%1}$y ))", "a=(1); x='a[$1\n(scan_probe)]'; unset \"${x/1?/}\"", "printf -v x 'a[\\x24\\x28scan_probe\\x29]'; echo $((x))", "printf -v x 'a[\\044\\050scan_probe\\051]'; echo $((x))", "a=(1); printf -v x 'a[\\u0024(scan_probe)]'; echo $((x))", "a=(1); printf -v x 'a[\\U00000024(scan_probe)]'; echo $((x))", "typeset -a a; print -v x 'a[\\x24\\x28scan_probe\\x29]'; echo $((x))", "typeset -a a; print -v x 'a[\\044\\050scan_probe\\051]'; echo $((x))", "typeset -a a; print -v x 'a[\\u0024\\u0028scan_probe\\u0029]'; echo $((x))", "typeset -a a; print -v x 'a[\\U00000024\\U00000028scan_probe\\U00000029]'; echo $((x))", 'a=(1); x="$\'a[\\\\x24\\\\x28scan_probe\\\\x29]\'"; unset "${x:Q}"', 'a=(1); x="$\'a[\\\\x24\\\\x28scan_probe\\\\x29]\'"; unset "$x:Q"', "a=(1); x=\"$'a[\\\\x24\\\\x28scan_probe\\\\x29]'\"; y=${x:Q}; echo $((y))", "a=(1); read x <<'EOF'\na[$(scan_probe)]\nEOF\necho $((x))", "a=(1); read x < string]> = [ ["$(...)", (inner) => `export OUTER=$( ${inner}\n)`], ['"$(...)"', (inner) => `export OUTER="$( ${inner}\n)"`], ["backticks", (inner) => `export OUTER=\` ${inner}\n\``], ["heredoc", (inner) => `: < `case x in x) ${inner}\n;; esac`], ["for loop", (inner) => `for k in 1; do ${inner}\ndone`], ["function", (inner) => `wrap_fn() {\n${inner}\n}; wrap_fn`], ["brace group", (inner) => `{ ${inner}\n}`], ] describe.skipIf(process.platform === "win32")("real-shell soundness oracle", () => { test("discovers at least bash on PATH", () => { expect(shells.some((item) => item.endsWith("/bash"))).toBe(true) }) test.each([...fixtures, ...nestedFixtures])("reports or rejects real-shell execution: %j", (source) => { expectProbesReported(source) }) test.each(wrappers.flatMap(([name, wrap]) => nestedFixtures.map((source) => [name, source, wrap(source)])))( "reports or rejects in %s: %j", (_, __, source) => { expectProbesReported(source) }, ) }) describe.skipIf(process.platform === "win32")("real-shell directory oracle", () => { test.each(["cd >/dev/null TARGET", "cd 2>/dev/null TARGET", "cd $'TARGET'", 'cd "TARGET"'])( "reports the directory a real shell changes to: %s", async (template) => { const source = template.replace("TARGET", target) const targets = [target, fs.realpathSync(target)] const changed = shells.filter((executable) => targets.includes(observe(executable, `${source}\npwd >> "$SCAN_PROBE_LOG"`).at(-1) ?? ""), ) expect(changed.length, `Fixture never changed directory in any real shell: ${source}`).toBeGreaterThan(0) for (const executable of changed) { const parsed = await Effect.runPromiseExit(ShellParse.scan(source, executable, root)) if (Exit.isSuccess(parsed)) expect(parsed.value.directories, `${executable} in: ${source}`).toContain(target) } }, ) })