on main help sign in
feat(shell): shebang/binary/in-process dispatch handler
commit2e8e5365a2d20cc75c93b6e064efecf2edf4a1e7 authorChristian Rocha <christian@rocha.is> dateSun 26 Apr 2026, 23:12 (6 months ago) parentf6ef43e
4 files changed+1069−3
internal/shell/dispatch.go+426 internal/shell/dispatch_test.go+594 internal/shell/dispatch_windows_test.go+40 internal/shell/run.go+9−3
internal/shell/dispatch.gonew file+426
@@ -0,0 +1,426 @@
1+package shell
2+
3+import (
4+ "bytes"
5+ "context"
6+ "errors"
7+ "fmt"
8+ "io"
9+ "io/fs"
10+ "log/slog"
11+ "os"
12+ "os/exec"
13+ "path/filepath"
14+ "runtime"
15+ "strings"
16+
17+ "mvdan.cc/sh/v3/expand"
18+ "mvdan.cc/sh/v3/interp"
19+ "mvdan.cc/sh/v3/syntax"
20+)
21+
22+// probeWindow is how many bytes we read from the head of a file to decide
23+// how to dispatch it. 128 is plenty for a shebang line and for magic-byte
24+// inspection, while small enough to make the probe cheap for users whose
25+// hooks invoke many scripts.
26+const probeWindow = 128
27+
28+// scriptDispatchHandler returns middleware that intercepts exec of a
29+// path-prefixed argv[0] (e.g. ./foo.sh, /opt/bin/tool, C:\foo\bar.exe) and
30+// dispatches based on the file's contents:
31+//
32+// 1. Shebang line (#!...) → exec the named interpreter via os/exec. The
33+// interpreter is resolved literally first, then via PATH on the
34+// basename as a permissive fallback (so #!/bin/bash works on Windows
35+// boxes where Git for Windows puts bash.exe on PATH).
36+// 2. Known binary magic (MZ, ELF, Mach-O) or a NUL byte in the probe
37+// window → pass through to the next handler (mvdan's default exec).
38+// 3. Otherwise → treat the file as shell source and run it in-process via
39+// a nested interp.Runner that reuses the same handler stack.
40+//
41+// Non-path-prefixed argv[0] and empty args are passed straight through; this
42+// handler is a no-op for ordinary commands like `echo` or `jq`.
43+//
44+// blockFuncs is the block list used when building the nested runner for the
45+// shell-source case, so deny rules apply recursively to commands invoked
46+// from in-process scripts.
47+func scriptDispatchHandler(blockFuncs []BlockFunc) func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
48+ return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
49+ return func(ctx context.Context, args []string) error {
50+ if len(args) == 0 || !isPathPrefixed(args[0]) {
51+ return next(ctx, args)
52+ }
53+
54+ scriptPath := args[0]
55+ // Resolve relative paths against the interpreter's cwd, not
56+ // the process cwd — hook commands are authored with the hook
57+ // Runner's cwd in mind and sub-shells can cd before an exec.
58+ if !filepath.IsAbs(scriptPath) {
59+ scriptPath = filepath.Join(interp.HandlerCtx(ctx).Dir, scriptPath)
60+ }
61+ probe, err := probeFile(scriptPath)
62+ if err != nil {
63+ return err
64+ }
65+
66+ switch {
67+ case hasShebang(probe):
68+ return dispatchShebang(ctx, scriptPath, probe, args)
69+ case isBinary(probe):
70+ return next(ctx, args)
71+ default:
72+ return runShellSource(ctx, scriptPath, args, blockFuncs)
73+ }
74+ }
75+ }
76+}
77+
78+// isPathPrefixed reports whether argv[0] is a file reference (as opposed
79+// to a bare command to be resolved via PATH). A path reference starts with
80+// `./`, `../`, `/`, or — on Windows — a drive-letter prefix.
81+//
82+// Note: mvdan already performs tilde expansion during word expansion, so
83+// `~/script.sh` arrives here as an absolute path. We still call the helper
84+// on the raw string to stay robust if a future change ever bypasses that
85+// expansion; cover that path with a regression test.
86+func isPathPrefixed(arg string) bool {
87+ switch {
88+ case strings.HasPrefix(arg, "./"),
89+ strings.HasPrefix(arg, "../"),
90+ strings.HasPrefix(arg, "/"):
91+ return true
92+ }
93+ if runtime.GOOS == "windows" {
94+ // Drive-letter paths: C:\foo or C:/foo (length check avoids
95+ // accidentally matching a single letter followed by a colon).
96+ if len(arg) >= 3 && isDriveLetter(arg[0]) && arg[1] == ':' &&
97+ (arg[2] == '\\' || arg[2] == '/') {
98+ return true
99+ }
100+ // Also treat backslash-prefixed UNC-like paths as path-prefixed.
101+ if strings.HasPrefix(arg, "\\") {
102+ return true
103+ }
104+ }
105+ return false
106+}
107+
108+func isDriveLetter(b byte) bool {
109+ return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z')
110+}
111+
112+// probeFile reads the first probeWindow bytes of the target path. It
113+// deliberately does not slurp the whole file: callers that need the full
114+// contents (only the shell-source branch) re-open via os.ReadFile. This
115+// keeps memory bounded when argv[0] turns out to be a large binary.
116+//
117+// Returns errors surfaced by os.Open/os.Stat directly so callers see the
118+// real reason: ENOENT, EACCES, EISDIR, ELOOP, etc.
119+func probeFile(path string) ([]byte, error) {
120+ f, err := os.Open(path)
121+ if err != nil {
122+ return nil, err
123+ }
124+ defer f.Close()
125+ fi, err := f.Stat()
126+ if err != nil {
127+ return nil, err
128+ }
129+ if fi.IsDir() {
130+ return nil, fmt.Errorf("%s: is a directory", path)
131+ }
132+ probe := make([]byte, probeWindow)
133+ n, err := io.ReadFull(f, probe)
134+ if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
135+ return nil, err
136+ }
137+ return probe[:n], nil
138+}
139+
140+// hasShebang reports whether probe starts with the `#!` marker. A
141+// one-byte file that happens to be `#` is not a shebang.
142+func hasShebang(probe []byte) bool {
143+ return len(probe) >= 2 && probe[0] == '#' && probe[1] == '!'
144+}
145+
146+// isBinary heuristically classifies probe as an executable or otherwise
147+// non-text file. A NUL byte in the first probeWindow bytes is the classic
148+// Unix-y text-vs-binary signal; we additionally recognize known magic
149+// numbers so we can fast-path well-formed binaries that happen to have no
150+// NUL in the first 128 bytes (rare but possible for small binaries).
151+func isBinary(probe []byte) bool {
152+ if bytes.IndexByte(probe, 0) >= 0 {
153+ return true
154+ }
155+ magics := [][]byte{
156+ {'M', 'Z'}, // Windows PE / DOS MZ.
157+ {0x7F, 'E', 'L', 'F'}, // ELF.
158+ {0xFE, 0xED, 0xFA, 0xCE}, // Mach-O 32-bit BE.
159+ {0xFE, 0xED, 0xFA, 0xCF}, // Mach-O 64-bit BE.
160+ {0xCF, 0xFA, 0xED, 0xFE}, // Mach-O 64-bit LE.
161+ {0xCE, 0xFA, 0xED, 0xFE}, // Mach-O 32-bit LE.
162+ {0xCA, 0xFE, 0xBA, 0xBE}, // Mach-O fat binary.
163+ }
164+ for _, m := range magics {
165+ if bytes.HasPrefix(probe, m) {
166+ return true
167+ }
168+ }
169+ return false
170+}
171+
172+// dispatchShebang parses probe's shebang line and execs the resolved
173+// interpreter via os/exec, inheriting the parent runner's cwd, env, and
174+// stdio. Returns interp.ExitStatus on non-zero interpreter exit so the
175+// parent interpreter sees it as a normal non-zero status.
176+func dispatchShebang(ctx context.Context, scriptPath string, probe []byte, args []string) error {
177+ sb, err := parseShebang(probe)
178+ if err != nil {
179+ hc := interp.HandlerCtx(ctx)
180+ fmt.Fprintf(hc.Stderr, "crush: %s: %s\n", scriptPath, err)
181+ return interp.ExitStatus(126)
182+ }
183+
184+ interpreter, err := resolveInterpreter(sb.interpreter)
185+ if err != nil {
186+ hc := interp.HandlerCtx(ctx)
187+ fmt.Fprintf(hc.Stderr, "crush: %s: %s\n", scriptPath, err)
188+ return interp.ExitStatus(127)
189+ }
190+
191+ cmdArgs := append([]string{}, sb.args...)
192+ cmdArgs = append(cmdArgs, scriptPath)
193+ cmdArgs = append(cmdArgs, args[1:]...)
194+
195+ cmd := exec.CommandContext(ctx, interpreter, cmdArgs...)
196+ hc := interp.HandlerCtx(ctx)
197+ cmd.Dir = hc.Dir
198+ cmd.Env = execEnvList(hc.Env)
199+ cmd.Stdin = hc.Stdin
200+ cmd.Stdout = hc.Stdout
201+ cmd.Stderr = hc.Stderr
202+
203+ if err := cmd.Run(); err != nil {
204+ var exitErr *exec.ExitError
205+ if errors.As(err, &exitErr) {
206+ code := exitErr.ExitCode()
207+ if code < 0 {
208+ code = 1
209+ }
210+ return interp.ExitStatus(uint8(code))
211+ }
212+ return err
213+ }
214+ return nil
215+}
216+
217+// resolveInterpreter tries the literal shebang path first, then falls back
218+// to PATH-lookup on its basename — but only when the literal path is
219+// genuinely missing. A file that exists but fails stat for another reason
220+// (EACCES, ELOOP, etc.) surfaces the real error: silently resolving a
221+// different binary off PATH in that case would hide a real problem and
222+// produce surprising behavior for the user.
223+//
224+// The permissive fallback is what makes #!/bin/bash portable to Windows
225+// boxes where Git for Windows puts bash.exe on PATH but there is no
226+// /bin/bash on disk.
227+func resolveInterpreter(path string) (string, error) {
228+ _, statErr := os.Stat(path)
229+ if statErr == nil {
230+ return path, nil
231+ }
232+ if !errors.Is(statErr, fs.ErrNotExist) {
233+ return "", statErr
234+ }
235+
236+ base := filepath.Base(path)
237+ if base == "" || base == path && !strings.ContainsAny(path, `/\`) {
238+ // Already a bare name — just do a PATH lookup.
239+ resolved, err := exec.LookPath(path)
240+ if err != nil {
241+ return "", fmt.Errorf("interpreter %q not found in PATH", path)
242+ }
243+ return resolved, nil
244+ }
245+ resolved, err := exec.LookPath(base)
246+ if err != nil {
247+ return "", fmt.Errorf("interpreter %q not found and %q not in PATH", path, base)
248+ }
249+ slog.Debug("Shebang interpreter not found; falling back to PATH",
250+ "requested", path, "resolved", resolved)
251+ return resolved, nil
252+}
253+
254+// shebang captures the parsed `#!` line. interpreter is the program to
255+// invoke; args is the list of extra arguments to pass before the script
256+// path. The kernel's single-arg semantics (for literal paths and for env
257+// without `-S`) is encoded by returning a single-element args slice
258+// containing the un-tokenized remainder.
259+type shebang struct {
260+ interpreter string
261+ args []string
262+}
263+
264+// parseShebang extracts the interpreter invocation from probe. It tolerates
265+// CRLF line endings and a single leading space between `#!` and the path.
266+// env special-cases: `/usr/bin/env NAME [args...]` unwraps to NAME with
267+// kernel single-arg semantics; `-S` enables tokenized argument splitting.
268+func parseShebang(probe []byte) (*shebang, error) {
269+ if !hasShebang(probe) {
270+ return nil, errors.New("not a shebang")
271+ }
272+ line := probe[2:]
273+ // Take up to the first newline.
274+ if idx := bytes.IndexByte(line, '\n'); idx >= 0 {
275+ line = line[:idx]
276+ }
277+ // Strip trailing CR (CRLF-authored scripts).
278+ line = bytes.TrimRight(line, "\r")
279+ // Strip leading whitespace ("#! /usr/bin/env bash" is legal).
280+ line = bytes.TrimLeft(line, " \t")
281+ if len(line) == 0 {
282+ return nil, errors.New("empty shebang")
283+ }
284+
285+ var pathStr, rest string
286+ if idx := bytes.IndexAny(line, " \t"); idx >= 0 {
287+ pathStr = string(line[:idx])
288+ rest = strings.TrimLeft(string(line[idx+1:]), " \t")
289+ } else {
290+ pathStr = string(line)
291+ }
292+
293+ if isEnvShebang(pathStr) {
294+ return parseEnvShebang(rest)
295+ }
296+
297+ // Literal-path shebang: kernel semantics pass the remainder as a
298+ // single argv[1], not tokenized.
299+ sb := &shebang{interpreter: pathStr}
300+ if rest != "" {
301+ sb.args = []string{rest}
302+ }
303+ return sb, nil
304+}
305+
306+// isEnvShebang reports whether the shebang path targets `env`. We accept
307+// both common absolute paths and a bare `env` so that unusual setups
308+// (NixOS, BSDs) still work.
309+func isEnvShebang(p string) bool {
310+ if p == "/usr/bin/env" || p == "/bin/env" {
311+ return true
312+ }
313+ return filepath.Base(p) == "env"
314+}
315+
316+// parseEnvShebang handles `/usr/bin/env` rewriting. Without `-S`, the
317+// remainder after the program name is a single argv[1] (kernel
318+// single-arg semantics via env, even though real env would fail to find a
319+// program named "bash -x"). With `-S`, the remainder is tokenized on
320+// whitespace. Any other `env` flag is rejected — forwarding unknown flags
321+// to a /usr/bin/env on disk is a subtle portability footgun we don't want.
322+func parseEnvShebang(rest string) (*shebang, error) {
323+ if rest == "" {
324+ return nil, errors.New("env: missing program name")
325+ }
326+
327+ useSplit := false
328+ if strings.HasPrefix(rest, "-") {
329+ var flag, after string
330+ if idx := strings.IndexAny(rest, " \t"); idx >= 0 {
331+ flag = rest[:idx]
332+ after = strings.TrimLeft(rest[idx+1:], " \t")
333+ } else {
334+ flag = rest
335+ after = ""
336+ }
337+ if flag != "-S" {
338+ return nil, fmt.Errorf("unsupported env flag: %s", flag)
339+ }
340+ useSplit = true
341+ rest = after
342+ if rest == "" {
343+ return nil, errors.New("env -S requires a program")
344+ }
345+ }
346+
347+ if rest == "" {
348+ return nil, errors.New("env: missing program name")
349+ }
350+
351+ var prog, remainder string
352+ if idx := strings.IndexAny(rest, " \t"); idx >= 0 {
353+ prog = rest[:idx]
354+ remainder = strings.TrimLeft(rest[idx+1:], " \t")
355+ } else {
356+ prog = rest
357+ }
358+
359+ sb := &shebang{interpreter: prog}
360+ if remainder != "" {
361+ if useSplit {
362+ sb.args = strings.Fields(remainder)
363+ } else {
364+ sb.args = []string{remainder}
365+ }
366+ }
367+ return sb, nil
368+}
369+
370+// runShellSource parses path's contents as POSIX shell and runs it
371+// in-process via a nested interp.Runner. It reuses the parent runner's cwd,
372+// env, and stdio, and rebuilds the Crush handler stack so builtins and the
373+// dispatch handler itself remain available to anything the script invokes.
374+// Positional parameters ($1, $2, …) come from args[1:].
375+//
376+// This is the only branch that reads the full file; probeFile keeps its
377+// read to probeWindow bytes so the binary/shebang paths never touch more
378+// than 128 bytes of I/O.
379+func runShellSource(ctx context.Context, path string, args []string, blockFuncs []BlockFunc) error {
380+ data, err := os.ReadFile(path)
381+ if err != nil {
382+ return err
383+ }
384+
385+ file, err := syntax.NewParser().Parse(bytes.NewReader(data), path)
386+ if err != nil {
387+ return fmt.Errorf("could not parse %s: %w", path, err)
388+ }
389+
390+ hc := interp.HandlerCtx(ctx)
391+
392+ opts := []interp.RunnerOption{
393+ interp.StdIO(hc.Stdin, hc.Stdout, hc.Stderr),
394+ interp.Interactive(false),
395+ interp.Env(hc.Env),
396+ interp.Dir(hc.Dir),
397+ interp.ExecHandlers(standardHandlers(blockFuncs)...),
398+ }
399+ if len(args) > 1 {
400+ // Params with a leading "--" avoids any of args[1:] being
401+ // misinterpreted as set-options (e.g. a user passing "-e" as
402+ // a positional arg to their script).
403+ params := append([]string{"--"}, args[1:]...)
404+ opts = append(opts, interp.Params(params...))
405+ }
406+
407+ runner, err := interp.New(opts...)
408+ if err != nil {
409+ return fmt.Errorf("could not build runner for %s: %w", path, err)
410+ }
411+ return runner.Run(ctx, file)
412+}
413+
414+// execEnvList converts an expand.Environ to the []string form that
415+// os/exec.Cmd.Env expects. Only exported string variables are included,
416+// matching what a real shell would pass to a child process.
417+func execEnvList(env expand.Environ) []string {
418+ var out []string
419+ env.Each(func(name string, vr expand.Variable) bool {
420+ if vr.Exported && vr.Kind == expand.String {
421+ out = append(out, name+"="+vr.Str)
422+ }
423+ return true
424+ })
425+ return out
426+}
internal/shell/dispatch_test.gonew file+594
@@ -0,0 +1,594 @@
1+package shell
2+
3+import (
4+ "bytes"
5+ "crypto/rand"
6+ "encoding/hex"
7+ "os"
8+ "os/exec"
9+ "path/filepath"
10+ "reflect"
11+ "runtime"
12+ "strings"
13+ "testing"
14+)
15+
16+// writeScript is a small helper that drops a file with the given contents
17+// and executable mode into dir. Tests that need exec semantics rely on the
18+// 0o755 mode on Unix; Windows ignores file modes but doesn't need them
19+// because dispatch decides what to do from file contents, not permissions.
20+func writeScript(t *testing.T, dir, name, contents string) string {
21+ t.Helper()
22+ path := filepath.Join(dir, name)
23+ if err := os.WriteFile(path, []byte(contents), 0o755); err != nil {
24+ t.Fatalf("write %s: %v", name, err)
25+ }
26+ return path
27+}
28+
29+// randSuffix returns a short random hex string, used to build
30+// intentionally-unique paths that won't collide with anything on disk.
31+func randSuffix() string {
32+ var b [4]byte
33+ _, _ = rand.Read(b[:])
34+ return hex.EncodeToString(b[:])
35+}
36+
37+// TestIsPathPrefixed covers the classification rules used by the dispatch
38+// handler to decide whether argv[0] is a file reference.
39+func TestIsPathPrefixed(t *testing.T) {
40+ cases := []struct {
41+ in string
42+ want bool
43+ }{
44+ {"./foo.sh", true},
45+ {"../foo.sh", true},
46+ {"/usr/bin/foo", true},
47+ {"foo", false},
48+ {"foo.sh", false},
49+ {"jq", false},
50+ {"", false},
51+ }
52+ for _, c := range cases {
53+ if got := isPathPrefixed(c.in); got != c.want {
54+ t.Errorf("isPathPrefixed(%q) = %v, want %v", c.in, got, c.want)
55+ }
56+ }
57+
58+ if runtime.GOOS == "windows" {
59+ winCases := []struct {
60+ in string
61+ want bool
62+ }{
63+ {`C:\foo\bar.exe`, true},
64+ {`C:/foo/bar.exe`, true},
65+ {`c:\foo`, true},
66+ {`Z:/x`, true},
67+ {`C:`, false}, // just a drive, no path.
68+ {`\\server\share`, true},
69+ }
70+ for _, c := range winCases {
71+ if got := isPathPrefixed(c.in); got != c.want {
72+ t.Errorf("isPathPrefixed(%q) = %v, want %v", c.in, got, c.want)
73+ }
74+ }
75+ }
76+}
77+
78+// TestParseShebang covers the shebang grammar: literal paths, env,
79+// env -S, kernel single-arg semantics, CRLF tolerance, and every
80+// enumerated error case.
81+func TestParseShebang(t *testing.T) {
82+ type want struct {
83+ interp string
84+ args []string
85+ errSub string // substring expected in error message (empty → no error)
86+ }
87+ cases := []struct {
88+ name string
89+ in string
90+ want want
91+ }{
92+ {
93+ name: "literal-no-args",
94+ in: "#!/bin/bash\necho body\n",
95+ want: want{interp: "/bin/bash"},
96+ },
97+ {
98+ name: "literal-kernel-single-arg",
99+ in: "#!/bin/bash -x -y\n",
100+ want: want{interp: "/bin/bash", args: []string{"-x -y"}},
101+ },
102+ {
103+ name: "env-basic",
104+ in: "#!/usr/bin/env bash\n",
105+ want: want{interp: "bash"},
106+ },
107+ {
108+ name: "env-kernel-single-arg",
109+ in: "#!/usr/bin/env bash -x\n",
110+ want: want{interp: "bash", args: []string{"-x"}},
111+ },
112+ {
113+ name: "env-dash-S-splits",
114+ in: "#!/usr/bin/env -S bash -x\n",
115+ want: want{interp: "bash", args: []string{"-x"}},
116+ },
117+ {
118+ name: "env-dash-S-multi-args",
119+ in: "#!/usr/bin/env -S bash -x --noprofile\n",
120+ want: want{interp: "bash", args: []string{"-x", "--noprofile"}},
121+ },
122+ {
123+ name: "leading-space",
124+ in: "#! /usr/bin/env bash\n",
125+ want: want{interp: "bash"},
126+ },
127+ {
128+ name: "crlf",
129+ in: "#!/bin/bash\r\n",
130+ want: want{interp: "/bin/bash"},
131+ },
132+ {
133+ name: "bare-env-name",
134+ in: "#!env bash\n",
135+ want: want{interp: "bash"},
136+ },
137+ {
138+ name: "empty-after-hashbang",
139+ in: "#!\n",
140+ want: want{errSub: "empty shebang"},
141+ },
142+ {
143+ name: "env-alone",
144+ in: "#!/usr/bin/env\n",
145+ want: want{errSub: "missing program name"},
146+ },
147+ {
148+ name: "env-dash-S-alone",
149+ in: "#!/usr/bin/env -S\n",
150+ want: want{errSub: "env -S requires a program"},
151+ },
152+ {
153+ name: "env-unknown-flag",
154+ in: "#!/usr/bin/env -x bash\n",
155+ want: want{errSub: "unsupported env flag"},
156+ },
157+ }
158+ for _, c := range cases {
159+ t.Run(c.name, func(t *testing.T) {
160+ sb, err := parseShebang([]byte(c.in))
161+ if c.want.errSub != "" {
162+ if err == nil || !strings.Contains(err.Error(), c.want.errSub) {
163+ t.Fatalf("expected error containing %q, got: %v", c.want.errSub, err)
164+ }
165+ return
166+ }
167+ if err != nil {
168+ t.Fatalf("unexpected error: %v", err)
169+ }
170+ if sb.interpreter != c.want.interp {
171+ t.Errorf("interpreter = %q, want %q", sb.interpreter, c.want.interp)
172+ }
173+ if !equalStringSlice(sb.args, c.want.args) {
174+ t.Errorf("args = %v, want %v", sb.args, c.want.args)
175+ }
176+ })
177+ }
178+}
179+
180+func equalStringSlice(a, b []string) bool {
181+ if len(a) == 0 && len(b) == 0 {
182+ return true
183+ }
184+ return reflect.DeepEqual(a, b)
185+}
186+
187+// TestIsBinary covers the NUL-byte and magic-byte classification used to
188+// keep compiled executables off the in-process shell-source path.
189+func TestIsBinary(t *testing.T) {
190+ cases := []struct {
191+ name string
192+ in []byte
193+ want bool
194+ }{
195+ {"shell", []byte("echo hi\n"), false},
196+ {"nul", []byte("hello\x00world"), true},
197+ {"elf", []byte{0x7F, 'E', 'L', 'F', 0x02, 0x01}, true},
198+ {"mz", []byte("MZ\x90\x00"), true},
199+ {"macho-64-le", []byte{0xCF, 0xFA, 0xED, 0xFE}, true},
200+ {"short-non-binary", []byte("a"), false},
201+ }
202+ for _, c := range cases {
203+ if got := isBinary(c.in); got != c.want {
204+ t.Errorf("%s: isBinary = %v, want %v", c.name, got, c.want)
205+ }
206+ }
207+}
208+
209+// TestDispatch_ShellSourceNoShebang exercises the in-process shell-source
210+// branch: a file without a shebang runs via a nested runner and sees
211+// positional params from argv[1:].
212+func TestDispatch_ShellSourceNoShebang(t *testing.T) {
213+ dir := t.TempDir()
214+ script := writeScript(t, dir, "args.sh", `echo "$1 $2"`)
215+
216+ var stdout bytes.Buffer
217+ err := Run(t.Context(), RunOptions{
218+ Command: script + " alpha beta",
219+ Cwd: dir,
220+ Stdout: &stdout,
221+ })
222+ if err != nil {
223+ t.Fatalf("Run returned error: %v", err)
224+ }
225+ if got := stdout.String(); got != "alpha beta\n" {
226+ t.Fatalf("stdout = %q, want %q", got, "alpha beta\n")
227+ }
228+}
229+
230+// TestDispatch_EmptyFile confirms a zero-byte script runs as empty shell
231+// source (exit 0, no output).
232+func TestDispatch_EmptyFile(t *testing.T) {
233+ dir := t.TempDir()
234+ script := writeScript(t, dir, "empty.sh", "")
235+
236+ var stdout, stderr bytes.Buffer
237+ err := Run(t.Context(), RunOptions{
238+ Command: script,
239+ Cwd: dir,
240+ Stdout: &stdout,
241+ Stderr: &stderr,
242+ })
243+ if err != nil {
244+ t.Fatalf("Run returned error: %v (stderr=%q)", err, stderr.String())
245+ }
246+ if stdout.Len() != 0 || stderr.Len() != 0 {
247+ t.Fatalf("expected empty output, got stdout=%q stderr=%q", stdout.String(), stderr.String())
248+ }
249+}
250+
251+// TestDispatch_ShellSourceComposesWithPipe confirms the dispatch handler
252+// plays nicely with mvdan's pipeline logic: a shell-source script on the
253+// left feeds the jq builtin on the right.
254+func TestDispatch_ShellSourceComposesWithPipe(t *testing.T) {
255+ dir := t.TempDir()
256+ script := writeScript(t, dir, "emit.sh", `printf '"value"'`)
257+
258+ var stdout bytes.Buffer
259+ err := Run(t.Context(), RunOptions{
260+ Command: script + ` | jq -r .`,
261+ Cwd: dir,
262+ Stdout: &stdout,
263+ })
264+ if err != nil {
265+ t.Fatalf("Run returned error: %v", err)
266+ }
267+ if got := stdout.String(); got != "value\n" {
268+ t.Fatalf("stdout = %q, want %q", got, "value\n")
269+ }
270+}
271+
272+// TestDispatch_MissingFile returns a clean error for a non-existent path.
273+func TestDispatch_MissingFile(t *testing.T) {
274+ dir := t.TempDir()
275+ missing := filepath.Join(dir, "nope.sh")
276+ err := Run(t.Context(), RunOptions{
277+ Command: missing,
278+ Cwd: dir,
279+ })
280+ if err == nil {
281+ t.Fatal("expected error for missing script, got nil")
282+ }
283+}
284+
285+// TestDispatch_DirectoryNotFile surfaces a distinct error when the path
286+// resolves to a directory.
287+func TestDispatch_DirectoryNotFile(t *testing.T) {
288+ dir := t.TempDir()
289+ subDir := filepath.Join(dir, "adir")
290+ if err := os.MkdirAll(subDir, 0o755); err != nil {
291+ t.Fatalf("mkdir: %v", err)
292+ }
293+
294+ var stderr bytes.Buffer
295+ err := Run(t.Context(), RunOptions{
296+ Command: "./adir",
297+ Cwd: dir,
298+ Stderr: &stderr,
299+ })
300+ if err == nil {
301+ t.Fatal("expected error when invoking a directory, got nil")
302+ }
303+ if !strings.Contains(err.Error(), "is a directory") {
304+ t.Fatalf("expected 'is a directory' in error, got: %v", err)
305+ }
306+}
307+
308+// TestDispatch_BashShebang runs a #!/bin/bash script via os/exec. Skipped
309+// if bash isn't available (rare in CI, but keep the test robust).
310+func TestDispatch_BashShebang(t *testing.T) {
311+ bash, err := exec.LookPath("bash")
312+ if err != nil {
313+ t.Skipf("bash not in PATH: %v", err)
314+ }
315+ _ = bash
316+
317+ dir := t.TempDir()
318+ script := writeScript(t, dir, "bash-echo.sh", "#!/usr/bin/env bash\necho bashout\n")
319+
320+ var stdout, stderr bytes.Buffer
321+ err = Run(t.Context(), RunOptions{
322+ Command: script,
323+ Cwd: dir,
324+ Stdout: &stdout,
325+ Stderr: &stderr,
326+ })
327+ if err != nil {
328+ t.Fatalf("Run returned error: %v (stderr=%q)", err, stderr.String())
329+ }
330+ if got := stdout.String(); got != "bashout\n" {
331+ t.Fatalf("stdout = %q, want %q", got, "bashout\n")
332+ }
333+}
334+
335+// TestDispatch_ShebangPassesExitCode maps interpreter exit codes through to
336+// interp.ExitStatus so the caller can inspect them with ExitCode.
337+func TestDispatch_ShebangPassesExitCode(t *testing.T) {
338+ if _, err := exec.LookPath("bash"); err != nil {
339+ t.Skipf("bash not in PATH: %v", err)
340+ }
341+ dir := t.TempDir()
342+ script := writeScript(t, dir, "fail.sh", "#!/usr/bin/env bash\nexit 5\n")
343+
344+ err := Run(t.Context(), RunOptions{
345+ Command: script,
346+ Cwd: dir,
347+ })
348+ if err == nil {
349+ t.Fatal("expected non-nil error from exit 5")
350+ }
351+ if code := ExitCode(err); code != 5 {
352+ t.Fatalf("ExitCode = %d, want 5", code)
353+ }
354+}
355+
356+// TestDispatch_MissingInterpreter surfaces a clear error (and non-zero
357+// exit) when the shebang points to a binary that doesn't exist and has
358+// no PATH fallback.
359+func TestDispatch_MissingInterpreter(t *testing.T) {
360+ dir := t.TempDir()
361+ script := writeScript(t, dir, "bad.sh", "#!/no/such/interpreter-"+randSuffix()+"\n:\n")
362+
363+ var stderr bytes.Buffer
364+ err := Run(t.Context(), RunOptions{
365+ Command: script,
366+ Cwd: dir,
367+ Stderr: &stderr,
368+ })
369+ if err == nil {
370+ t.Fatal("expected error for missing interpreter, got nil")
371+ }
372+ if ExitCode(err) == 0 {
373+ t.Fatalf("expected non-zero exit code, got 0")
374+ }
375+ if !strings.Contains(stderr.String(), "not found") {
376+ t.Fatalf("expected 'not found' in stderr, got: %q", stderr.String())
377+ }
378+}
379+
380+// TestDispatch_BarePathNotHandled confirms the handler ignores
381+// non-path-prefixed argv[0] entirely: a benign bare `true` command must
382+// not try to open a file in cwd. If dispatch were (incorrectly) firing
383+// on bare commands, this test would see probeFile's ENOENT.
384+func TestDispatch_BarePathNotHandled(t *testing.T) {
385+ dir := t.TempDir()
386+ err := Run(t.Context(), RunOptions{
387+ Command: "true",
388+ Cwd: dir,
389+ })
390+ if err != nil {
391+ t.Fatalf("bare `true` should not trigger dispatch: %v", err)
392+ }
393+}
394+
395+// TestDispatch_ProbeWindowClassifiesByHead confirms that classification is
396+// done on the first probeWindow bytes even when the file is much larger;
397+// a file whose head is shell source but whose tail contains NUL bytes is
398+// classified as shell source, not binary.
399+func TestDispatch_ProbeWindowClassifiesByHead(t *testing.T) {
400+ dir := t.TempDir()
401+ head := "echo prefix\n"
402+ // Pad past probeWindow, then append some NULs.
403+ padding := strings.Repeat(" ", probeWindow)
404+ contents := head + padding + "\x00\x00\x00"
405+ script := writeScript(t, dir, "long.sh", contents)
406+
407+ var stdout bytes.Buffer
408+ err := Run(t.Context(), RunOptions{
409+ Command: script,
410+ Cwd: dir,
411+ Stdout: &stdout,
412+ })
413+ if err != nil {
414+ t.Fatalf("Run returned error: %v", err)
415+ }
416+ if got := stdout.String(); !strings.HasPrefix(got, "prefix\n") {
417+ t.Fatalf("stdout = %q, want prefix %q", got, "prefix\n")
418+ }
419+}
420+
421+// TestDispatch_BinaryPassthroughExecutes copies a real binary from PATH
422+// into a tempdir, invokes it via a path-prefixed argv[0], and verifies it
423+// ran — i.e. the binary branch correctly returns through `next` to the
424+// default exec handler. We use whichever of `true`/`echo` is available on
425+// PATH so the test works on any Unix-y system; it skips on Windows where
426+// the stock binaries don't share names and the Go test binary approach
427+// is heavier than this test deserves.
428+func TestDispatch_BinaryPassthroughExecutes(t *testing.T) {
429+ if runtime.GOOS == "windows" {
430+ t.Skip("relies on a Unix-style PATH binary")
431+ }
432+ src, err := exec.LookPath("true")
433+ if err != nil {
434+ t.Skipf("no `true` binary on PATH: %v", err)
435+ }
436+ data, err := os.ReadFile(src)
437+ if err != nil {
438+ t.Fatalf("read %s: %v", src, err)
439+ }
440+ dir := t.TempDir()
441+ dst := filepath.Join(dir, "copied-true")
442+ if err := os.WriteFile(dst, data, 0o755); err != nil {
443+ t.Fatalf("write %s: %v", dst, err)
444+ }
445+
446+ runErr := Run(t.Context(), RunOptions{
447+ Command: dst,
448+ Cwd: dir,
449+ // Default handler needs PATH to resolve dynamic linker / loader
450+ // helpers on some systems; inherit the process env so the copy
451+ // can actually start.
452+ Env: os.Environ(),
453+ })
454+ if runErr != nil {
455+ t.Fatalf("expected copy of /bin/true to exit 0, got: %v", runErr)
456+ }
457+}
458+
459+// TestDispatch_UnreadableFile confirms an EACCES on the script surfaces
460+// as a clean error rather than a silent fallback or a mis-classified
461+// shell-source attempt. POSIX-only: Windows doesn't have the same
462+// permission model and running as root would bypass the check anyway.
463+func TestDispatch_UnreadableFile(t *testing.T) {
464+ if runtime.GOOS == "windows" {
465+ t.Skip("POSIX permission model")
466+ }
467+ if os.Geteuid() == 0 {
468+ t.Skip("root bypasses file mode permission checks")
469+ }
470+ dir := t.TempDir()
471+ script := writeScript(t, dir, "unreadable.sh", "echo nope\n")
472+ if err := os.Chmod(script, 0o000); err != nil {
473+ t.Fatalf("chmod: %v", err)
474+ }
475+ t.Cleanup(func() { _ = os.Chmod(script, 0o644) })
476+
477+ err := Run(t.Context(), RunOptions{
478+ Command: script,
479+ Cwd: dir,
480+ })
481+ if err == nil {
482+ t.Fatal("expected permission error, got nil")
483+ }
484+ if !strings.Contains(err.Error(), "permission") {
485+ t.Fatalf("expected 'permission' in error, got: %v", err)
486+ }
487+}
488+
489+// TestDispatch_SymlinkLoop confirms that an ELOOP-returning path surfaces
490+// cleanly. POSIX-only: creating symlinks reliably on Windows requires
491+// elevated privileges or developer mode, and neither is guaranteed in CI.
492+func TestDispatch_SymlinkLoop(t *testing.T) {
493+ if runtime.GOOS == "windows" {
494+ t.Skip("symlink creation requires special privileges on Windows")
495+ }
496+ dir := t.TempDir()
497+ a := filepath.Join(dir, "a")
498+ b := filepath.Join(dir, "b")
499+ if err := os.Symlink(b, a); err != nil {
500+ t.Fatalf("symlink a→b: %v", err)
501+ }
502+ if err := os.Symlink(a, b); err != nil {
503+ t.Fatalf("symlink b→a: %v", err)
504+ }
505+
506+ err := Run(t.Context(), RunOptions{
507+ Command: a,
508+ Cwd: dir,
509+ })
510+ if err == nil {
511+ t.Fatal("expected loop error, got nil")
512+ }
513+ // The exact error varies by OS; any of these message fragments is
514+ // acceptable evidence that the loop was detected.
515+ msg := err.Error()
516+ if !strings.Contains(msg, "too many") &&
517+ !strings.Contains(msg, "loop") &&
518+ !strings.Contains(msg, "level") {
519+ t.Fatalf("expected symlink-loop-ish error, got: %v", err)
520+ }
521+}
522+
523+// TestResolveInterpreter_PermissiveFallback confirms the key portability
524+// behavior: a literal shebang path that doesn't exist falls back to a
525+// PATH-lookup on its basename. This is what makes #!/bin/bash work on a
526+// Windows box where bash.exe lives somewhere else on PATH. We construct a
527+// fake PATH in a tempdir rather than depending on what the host has
528+// installed so the test is deterministic everywhere.
529+func TestResolveInterpreter_PermissiveFallback(t *testing.T) {
530+ if runtime.GOOS == "windows" {
531+ // exec.LookPath on Windows requires a recognized extension
532+ // (.exe/.bat/.cmd). Producing one of those without a compiler
533+ // run is more ceremony than this smoke test deserves; the
534+ // logic under test is exercised by the Unix run.
535+ t.Skip("Windows PATH lookup requires an extension-matched binary")
536+ }
537+ dir := t.TempDir()
538+ fake := filepath.Join(dir, "bash")
539+ if err := os.WriteFile(fake, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
540+ t.Fatalf("write fake bash: %v", err)
541+ }
542+ t.Setenv("PATH", dir)
543+
544+ // Basename must match the fake we planted on PATH; the directory
545+ // prefix must not exist so the literal stat fails.
546+ missingDir := filepath.Join(dir, "definitely-not-here-"+randSuffix())
547+ resolved, err := resolveInterpreter(filepath.Join(missingDir, "bash"))
548+ if err != nil {
549+ t.Fatalf("expected fallback to succeed, got: %v", err)
550+ }
551+ if resolved != fake {
552+ t.Fatalf("resolved = %q, want %q", resolved, fake)
553+ }
554+}
555+
556+// TestResolveInterpreter_NonENOENTErrorsSurface guards against silently
557+// falling back to PATH when stat fails for a reason other than the file
558+// being missing. With a directory at the shebang path, os.Stat succeeds
559+// (no fallback needed), but with an EACCES'd file it fails with a non-
560+// ENOENT error that must be surfaced — otherwise we'd silently resolve a
561+// different binary off PATH and hide the real problem.
562+func TestResolveInterpreter_NonENOENTErrorsSurface(t *testing.T) {
563+ if runtime.GOOS == "windows" {
564+ t.Skip("POSIX permission model")
565+ }
566+ if os.Geteuid() == 0 {
567+ t.Skip("root bypasses dir mode permission checks")
568+ }
569+ dir := t.TempDir()
570+ // Put a candidate interpreter inside an unreadable/untraversable dir.
571+ inner := filepath.Join(dir, "private")
572+ if err := os.Mkdir(inner, 0o755); err != nil {
573+ t.Fatalf("mkdir: %v", err)
574+ }
575+ interp := filepath.Join(inner, "bash")
576+ if err := os.WriteFile(interp, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
577+ t.Fatalf("write interpreter: %v", err)
578+ }
579+ // Drop search permission on inner so os.Stat(interp) returns EACCES.
580+ if err := os.Chmod(inner, 0o000); err != nil {
581+ t.Fatalf("chmod: %v", err)
582+ }
583+ t.Cleanup(func() { _ = os.Chmod(inner, 0o755) })
584+
585+ _, err := resolveInterpreter(interp)
586+ if err == nil {
587+ t.Fatal("expected error for unreadable interpreter, got nil")
588+ }
589+ // Must NOT have silently fallen back — the returned path shouldn't
590+ // be a valid resolution; either way, the error has to surface.
591+ if !strings.Contains(err.Error(), "permission") {
592+ t.Fatalf("expected permission-denied error to surface, got: %v", err)
593+ }
594+}
internal/shell/dispatch_windows_test.gonew file+40
@@ -0,0 +1,40 @@
1+//go:build windows
2+
3+package shell
4+
5+import (
6+ "os"
7+ "path/filepath"
8+ "testing"
9+)
10+
11+// TestResolveInterpreter_PermissiveFallback_Windows is the Windows-native
12+// counterpart to the POSIX permissive-fallback test. It proves the one
13+// behavior that makes `#!/bin/bash` hooks work on a stock Windows box
14+// with Git for Windows installed: when the literal interpreter path does
15+// not exist, we fall back to a PATH-lookup on the basename and that
16+// lookup accepts any executable extension Windows honors (here, `.bat`).
17+//
18+// We plant a bash.bat in a tempdir rather than a .exe because producing
19+// a .exe would require a toolchain step; LookPath on Windows resolves
20+// PATHEXT extensions, so .bat is just as valid for the lookup codepath.
21+func TestResolveInterpreter_PermissiveFallback_Windows(t *testing.T) {
22+ dir := t.TempDir()
23+ fake := filepath.Join(dir, "bash.bat")
24+ contents := "@echo off\r\nexit /b 0\r\n"
25+ if err := os.WriteFile(fake, []byte(contents), 0o755); err != nil {
26+ t.Fatalf("write fake bash.bat: %v", err)
27+ }
28+ t.Setenv("PATH", dir)
29+ t.Setenv("PATHEXT", ".BAT;.CMD;.EXE")
30+
31+ // Literal path must be absent so the stat fails with ENOENT.
32+ missing := filepath.Join(dir, "definitely-not-here-"+randSuffix(), "bash")
33+ resolved, err := resolveInterpreter(missing)
34+ if err != nil {
35+ t.Fatalf("expected fallback to succeed, got: %v", err)
36+ }
37+ if resolved != fake {
38+ t.Fatalf("resolved = %q, want %q", resolved, fake)
39+ }
40+}
internal/shell/run.go+9−3
@@ -99,12 +99,18 @@ func newRunner(cwd string, env []string, stdin io.Reader, stdout, stderr io.Writ
9999}
100100
101101// standardHandlers returns the exec-handler middleware chain used by both
102−// [Run] and [Shell]. Order matters: builtins first (so Crush's in-process
103−// jq wins over any PATH binary), then the block list, then optional Go
104−// coreutils. Future middleware (shebang dispatch, etc.) inserts here.
102+// [Run] and [Shell]. Order matters:
103+// 1. builtins first (so Crush's in-process jq wins over any PATH binary);
104+// 2. script dispatch (shebang / binary / shell-source for path-prefixed
105+// argv[0], no-op for bare commands) — runs before the block list so
106+// that deny rules see the already-resolved argv of anything the
107+// script exec's rather than the outer path-prefixed wrapper;
108+// 3. block list;
109+// 4. optional Go coreutils (only when useGoCoreUtils is on).
105110func standardHandlers(blockFuncs []BlockFunc) []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
106111 handlers := []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc{
107112 builtinHandler(),
113+ scriptDispatchHandler(blockFuncs),
108114 blockHandler(blockFuncs),
109115 }
110116 if useGoCoreUtils {