Debian Codegraph @

interp/handler_test.go

raw
1 // Copyright (c) 2017, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 package interp_test
5
6 import (
7 "bufio"
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "io"
13 "io/fs"
14 "os"
15 "path/filepath"
16 "runtime"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "testing"
22 "testing/fstest"
23 "time"
24
25 "mvdan.cc/sh/v3/interp"
26 "mvdan.cc/sh/v3/syntax"
27 )
28
29 func blocklistOneExec(name string) func(interp.ExecHandlerFunc) interp.ExecHandlerFunc {
30 return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
31 return func(ctx context.Context, args []string) error {
32 if args[0] == name {
33 return fmt.Errorf("%s: blocklisted program", name)
34 }
35 return next(ctx, args)
36 }
37 }
38 }
39
40 func blocklistAllExec(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
41 return func(ctx context.Context, args []string) error {
42 return fmt.Errorf("blocklisted: %s", args[0])
43 }
44 }
45
46 func blocklistNondevOpen(ctx context.Context, path string, flags int, mode os.FileMode) (io.ReadWriteCloser, error) {
47 if path != "/dev/null" {
48 return nil, fmt.Errorf("non-dev: %s", path)
49 }
50
51 return interp.DefaultOpenHandler()(ctx, path, flags, mode)
52 }
53
54 func mockFileOpen(ctx context.Context, path string, flags int, mode os.FileMode) (io.ReadWriteCloser, error) {
55 return nopWriterCloser{strings.NewReader(fmt.Sprintf("body of %s", path))}, nil
56 }
57
58 func blocklistGlob(ctx context.Context, path string) ([]fs.FileInfo, error) {
59 return nil, fmt.Errorf("blocklisted: glob")
60 }
61
62 func blocklistWriteAccess(ctx context.Context, path string, mode interp.AccessMode) error {
63 if mode == interp.AccessWrite {
64 return fmt.Errorf("blocklisted: write access")
65 }
66 return interp.DefaultAccessHandler()(ctx, path, mode)
67 }
68
69 // virtualDirStat and virtualDirAccess pretend that a "vdir" directory
70 // exists, as a minimal virtual filesystem; see issue #1318.
71 func virtualDirStat(ctx context.Context, path string, followSymlinks bool) (fs.FileInfo, error) {
72 if filepath.Base(path) == "vdir" {
73 return fstest.MapFS{"vdir": &fstest.MapFile{Mode: fs.ModeDir | 0o755}}.Stat("vdir")
74 }
75 return interp.DefaultStatHandler()(ctx, path, followSymlinks)
76 }
77
78 func virtualDirAccess(ctx context.Context, path string, mode interp.AccessMode) error {
79 if filepath.Base(path) == "vdir" {
80 return nil
81 }
82 return interp.DefaultAccessHandler()(ctx, path, mode)
83 }
84
85 func execPrint(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
86 return func(ctx context.Context, args []string) error {
87 hc := interp.HandlerCtx(ctx)
88 fmt.Fprintf(hc.Stdout, "would run: %s\n", args)
89 return nil
90 }
91 }
92
93 func execExitStatus5(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
94 return func(ctx context.Context, args []string) error {
95 return interp.ExitStatus(5)
96 }
97 }
98
99 func execCustomError(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
100 return func(ctx context.Context, args []string) error {
101 return fmt.Errorf("custom error")
102 }
103 }
104
105 func execCustomExitStatus5(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
106 return func(ctx context.Context, args []string) error {
107 return fmt.Errorf("custom error: %w", interp.ExitStatus(5))
108 }
109 }
110
111 func execDotRunnerBuiltin(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
112 return func(ctx context.Context, args []string) error {
113 if name, ok := strings.CutPrefix(args[0], "."); ok {
114 hc := interp.HandlerCtx(ctx)
115 args[0] = name
116 err := hc.Builtin(ctx, args)
117 fmt.Fprintf(hc.Stdout, "ran builtin: %s\n", args)
118 return err
119 }
120 return next(ctx, args)
121 }
122 }
123
124 // runnerCtx allows us to give handler functions access to the Runner, if needed.
125 var runnerCtx = new(int)
126
127 func execPrintWouldExec(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
128 return func(ctx context.Context, args []string) error {
129 runner, ok := ctx.Value(runnerCtx).(*interp.Runner)
130 if ok && runner.Exited() {
131 return fmt.Errorf("would exec via builtin: %s", args)
132 }
133 return nil
134 }
135 }
136
137 // modCases stays separate from TestRunnerOpts as it exercises the handlers,
138 // which requires the default handlers as a base rather than testExecHandler,
139 // and its options are applied to an existing runner rather than via New.
140 var modCases = []struct {
141 name string
142 opts []interp.RunnerOption
143 src string
144 want string
145 }{
146 {
147 name: "ExecBlocklistOne",
148 opts: []interp.RunnerOption{
149 interp.ExecHandlers(blocklistOneExec("sleep")),
150 },
151 src: "echo foo; sleep 1",
152 want: "foo\nRunner.Run error: sleep: blocklisted program",
153 },
154 {
155 name: "ExecBlocklistOneSubshell",
156 opts: []interp.RunnerOption{
157 interp.ExecHandlers(
158 blocklistOneExec("faa"),
159 testExecHandler, // sed is used below
160 ),
161 },
162 src: "a=$(echo foo | sed 's/o/a/g'); echo $a; $a args",
163 want: "faa\nRunner.Run error: faa: blocklisted program",
164 },
165 {
166 name: "ExecBlocklistAllSubshell",
167 opts: []interp.RunnerOption{
168 interp.ExecHandlers(blocklistAllExec),
169 },
170 src: "(malicious)",
171 want: "Runner.Run error: blocklisted: malicious",
172 },
173 {
174 name: "ExecPipe",
175 opts: []interp.RunnerOption{
176 interp.ExecHandlers(blocklistAllExec),
177 },
178 src: "malicious | echo foo",
179 want: "foo\nRunner.Run error: blocklisted: malicious",
180 },
181 {
182 name: "ExecPipeFail",
183 opts: []interp.RunnerOption{
184 interp.ExecHandlers(blocklistAllExec),
185 },
186 src: "set -o pipefail; malicious | echo foo",
187 want: "foo\nRunner.Run error: blocklisted: malicious",
188 },
189 {
190 name: "ExecCmdSubst",
191 opts: []interp.RunnerOption{
192 interp.ExecHandlers(blocklistAllExec),
193 },
194 src: "a=$(malicious)",
195 want: "blocklisted: malicious\nRunner.Run error: blocklisted: malicious",
196 },
197 {
198 name: "ExecBackground",
199 opts: []interp.RunnerOption{
200 interp.ExecHandlers(blocklistAllExec),
201 },
202 src: "{ malicious; true; } & { malicious; true; } & wait",
203 // Note that "wait" with no arguments always succeeds.
204 want: "",
205 },
206 {
207 name: "ExecPrintWouldExec",
208 opts: []interp.RunnerOption{
209 interp.ExecHandlers(execPrintWouldExec),
210 },
211 src: "exec /bin/sh",
212 want: "Runner.Run error: would exec via builtin: [/bin/sh]",
213 },
214 {
215 name: "ExecPrintAndBlocklist",
216 opts: []interp.RunnerOption{
217 interp.ExecHandlers(
218 execPrint,
219 blocklistOneExec("foo"),
220 ),
221 },
222 src: "foo",
223 want: "would run: [foo]\n",
224 },
225 {
226 name: "ExecPrintAndBlocklistSeparate",
227 opts: []interp.RunnerOption{
228 interp.ExecHandlers(execPrint),
229 interp.ExecHandlers(blocklistOneExec("foo")),
230 },
231 src: "foo",
232 want: "would run: [foo]\n",
233 },
234 {
235 name: "ExecBlocklistAndPrint",
236 opts: []interp.RunnerOption{
237 interp.ExecHandlers(
238 blocklistOneExec("foo"),
239 execPrint,
240 ),
241 },
242 src: "foo",
243 want: "Runner.Run error: foo: blocklisted program",
244 },
245 {
246 name: "ExecExitStatus5",
247 opts: []interp.RunnerOption{
248 interp.ExecHandlers(execExitStatus5),
249 },
250 src: "foo",
251 want: "Runner.Run error: exit status 5",
252 },
253 {
254 name: "ExecCustomError",
255 opts: []interp.RunnerOption{
256 interp.ExecHandlers(execCustomError),
257 },
258 src: "foo",
259 want: "Runner.Run error: custom error",
260 },
261 {
262 name: "ExecCustomErrorContinuation",
263 opts: []interp.RunnerOption{
264 interp.ExecHandlers(execCustomError),
265 },
266 src: "foo; echo next",
267 want: "Runner.Run error: custom error",
268 },
269 {
270 name: "ExecCustomExitStatus5",
271 opts: []interp.RunnerOption{
272 interp.ExecHandlers(execCustomExitStatus5),
273 },
274 src: "foo",
275 want: "Runner.Run error: custom error: exit status 5",
276 },
277 {
278 name: "ExecCustomExitStatus5Continuation",
279 opts: []interp.RunnerOption{
280 interp.ExecHandlers(execCustomExitStatus5),
281 },
282 src: "foo; echo next",
283 want: "next\n",
284 },
285 {
286 name: "ExecCustomExitStatus5Pipefail",
287 opts: []interp.RunnerOption{
288 interp.ExecHandlers(execCustomExitStatus5),
289 },
290 src: "set -o pipefail; foo | true",
291 want: "Runner.Run error: custom error: exit status 5",
292 },
293 {
294 name: "ExecCustomExitStatus5ErrExit",
295 opts: []interp.RunnerOption{
296 interp.ExecHandlers(execCustomExitStatus5),
297 },
298 src: "set -o errexit; foo",
299 want: "Runner.Run error: custom error: exit status 5",
300 },
301 {
302 name: "ExecCustomExitStatus5Exec",
303 opts: []interp.RunnerOption{
304 interp.ExecHandlers(execCustomExitStatus5),
305 },
306 src: "exec foo; echo never-run",
307 want: "Runner.Run error: custom error: exit status 5",
308 },
309 {
310 name: "ExecCustomExitStatus5Negated",
311 opts: []interp.RunnerOption{
312 interp.ExecHandlers(execCustomExitStatus5),
313 },
314 src: "! foo; echo custom-error-wiped; exit 1",
315 want: "custom-error-wiped\nRunner.Run error: exit status 1",
316 },
317 {
318 name: "ExecCustomExitStatus5CmdSubst",
319 opts: []interp.RunnerOption{
320 interp.ExecHandlers(execCustomExitStatus5),
321 },
322 src: "x=$(foo)",
323 want: "Runner.Run error: custom error: exit status 5",
324 },
325 {
326 name: "ExecCustomExitStatus5Subshell",
327 opts: []interp.RunnerOption{
328 interp.ExecHandlers(execCustomExitStatus5),
329 },
330 src: "(foo)",
331 want: "Runner.Run error: custom error: exit status 5",
332 },
333 {
334 name: "ExecCustomExitStatus5Wait",
335 opts: []interp.RunnerOption{
336 interp.ExecHandlers(execCustomExitStatus5),
337 },
338 src: "foo & bg=$!; wait $bg",
339 want: "Runner.Run error: custom error: exit status 5",
340 },
341 {
342 name: "ExecCustomExitStatus5Exit",
343 opts: []interp.RunnerOption{
344 interp.ExecHandlers(execCustomExitStatus5),
345 },
346 src: "foo; exit",
347 want: "Runner.Run error: custom error: exit status 5",
348 },
349 {
350 name: "ExecCustomExitStatus5Source",
351 opts: []interp.RunnerOption{
352 interp.ExecHandlers(execCustomExitStatus5),
353 },
354 src: "echo 'foo' >a; source ./a",
355 want: "Runner.Run error: custom error: exit status 5",
356 },
357 {
358 name: "ExecDotRunnerBuiltin",
359 opts: []interp.RunnerOption{
360 interp.ExecHandlers(execDotRunnerBuiltin, execExitStatus5),
361 },
362 src: ".true; foo; echo $?; .false",
363 want: "ran builtin: [true]\n5\nran builtin: [false]\nRunner.Run error: exit status 1",
364 },
365 {
366 name: "ExecDotRunnerBuiltinExiting",
367 opts: []interp.RunnerOption{
368 interp.ExecHandlers(execDotRunnerBuiltin, execExitStatus5),
369 },
370 src: "echo before; .exit 0; echo after",
371 want: "before\nran builtin: [exit 0]\n",
372 },
373 {
374 name: "NonExecBuiltin",
375 opts: []interp.RunnerOption{
376 interp.CallHandler(func(ctx context.Context, args []string) ([]string, error) {
377 hc := interp.HandlerCtx(ctx)
378 err := hc.Builtin(ctx, append([]string{"echo"}, args...))
379 return nil, err
380 }),
381 },
382 src: "foo; bar",
383 want: "Runner.Run error: HandlerContext.Builtin can only be called via an ExecHandlerFunc",
384 },
385 {
386 name: "OpenForbidNonDev",
387 opts: []interp.RunnerOption{
388 interp.OpenHandler(blocklistNondevOpen),
389 },
390 src: "echo foo >/dev/null; echo bar >/tmp/x",
391 want: "Runner.Run error: non-dev: /tmp/x",
392 },
393 {
394 name: "OpenMockFile",
395 opts: []interp.RunnerOption{
396 interp.OpenHandler(mockFileOpen),
397 },
398 src: "echo $(<foo); echo $(< <(echo bar))",
399 want: "body of foo\nbar\n",
400 },
401 {
402 name: "CallReplaceWithBlank",
403 opts: []interp.RunnerOption{
404 interp.OpenHandler(blocklistNondevOpen),
405 interp.CallHandler(func(ctx context.Context, args []string) ([]string, error) {
406 return []string{"echo", "blank"}, nil
407 }),
408 },
409 src: "echo foo >/dev/null; { bar; } && baz",
410 want: "blank\nblank\n",
411 },
412 {
413 name: "CallDryRun",
414 opts: []interp.RunnerOption{
415 interp.CallHandler(func(ctx context.Context, args []string) ([]string, error) {
416 return append([]string{"echo", "run:"}, args...), nil
417 }),
418 },
419 src: "cd some-dir; cat foo; exit 1",
420 want: "run: cd some-dir\nrun: cat foo\nrun: exit 1\n",
421 },
422 {
423 name: "CallError",
424 opts: []interp.RunnerOption{
425 interp.CallHandler(func(ctx context.Context, args []string) ([]string, error) {
426 if args[0] == "echo" && len(args) > 2 {
427 return nil, fmt.Errorf("refusing to run echo builtin with multiple args")
428 }
429 return args, nil
430 }),
431 },
432 src: "echo foo; echo foo bar",
433 want: "foo\nRunner.Run error: refusing to run echo builtin with multiple args",
434 },
435 {
436 name: "GlobForbid",
437 opts: []interp.RunnerOption{
438 interp.ReadDirHandler(blocklistGlob),
439 },
440 src: "echo *",
441 want: "blocklisted: glob\n",
442 },
443 {
444 name: "AccessForbidWrite",
445 opts: []interp.RunnerOption{
446 interp.AccessHandler(blocklistWriteAccess),
447 },
448 src: ">file; [ -w file ] && echo writable; [ -r file ] && echo readable",
449 want: "readable\n",
450 },
451 {
452 name: "AccessVirtualCd",
453 opts: []interp.RunnerOption{
454 interp.StatHandler(virtualDirStat),
455 interp.AccessHandler(virtualDirAccess),
456 },
457 src: "cd vdir && echo ok",
458 want: "ok\n",
459 },
460 }
461
462 func TestRunnerHandlers(t *testing.T) {
463 t.Parallel()
464
465 p := syntax.NewParser()
466 for _, tc := range modCases {
467 t.Run(tc.name, func(t *testing.T) {
468 skipIfUnsupported(t, tc.src)
469 file := parse(t, p, tc.src)
470 tdir := t.TempDir()
471 var cb concBuffer
472 r, err := interp.New(interp.Dir(tdir), interp.StdIO(nil, &cb, &cb))
473 if err != nil {
474 t.Fatal(err)
475 }
476 for _, opt := range tc.opts {
477 opt(r)
478 }
479 ctx := context.WithValue(t.Context(), runnerCtx, r)
480 if err := r.Run(ctx, file); err != nil {
481 fmt.Fprintf(&cb, "Runner.Run error: %v", err)
482 }
483 got := cb.String()
484 if got != tc.want {
485 t.Fatalf("want:\n%q\ngot:\n%q", tc.want, got)
486 }
487 })
488 }
489 }
490
491 type readyBuffer struct {
492 buf bytes.Buffer
493 seenReady sync.WaitGroup
494 }
495
496 func (b *readyBuffer) Write(p []byte) (n int, err error) {
497 if string(p) == "ready\n" {
498 b.seenReady.Done()
499 return len(p), nil
500 }
501 return b.buf.Write(p)
502 }
503
504 func TestKillTimeout(t *testing.T) {
505 if testing.Short() {
506 t.Skip("sleeps and timeouts are slow")
507 }
508 if runtime.GOOS == "windows" {
509 t.Skip("skipping trap tests on windows")
510 }
511 if !canExec {
512 t.Skipf("skipping test needing subprocesses on %s", runtime.GOOS)
513 }
514 t.Parallel()
515
516 tests := []struct {
517 src string
518 want string
519 killTimeout time.Duration
520 forcedKill bool
521 }{
522 // killed immediately
523 {
524 `sh -c "trap 'echo trapped; exit 0' INT; echo ready; for i in \$(seq 1 100); do sleep 0.01; done"`,
525 "",
526 -1,
527 true,
528 },
529 // interrupted first, and stops itself in time
530 {
531 `sh -c "trap 'echo trapped; exit 0' INT; echo ready; for i in \$(seq 1 100); do sleep 0.01; done"`,
532 "trapped\n",
533 time.Second,
534 false,
535 },
536 // interrupted first, but does not stop itself in time
537 {
538 `sh -c "trap 'echo trapped; for i in \$(seq 1 100); do sleep 0.01; done' INT; echo ready; for i in \$(seq 1 100); do sleep 0.01; done"`,
539 "trapped\n",
540 20 * time.Millisecond,
541 true,
542 },
543 }
544
545 for _, test := range tests {
546 t.Run("", func(t *testing.T) {
547 t.Parallel()
548 file := parse(t, nil, test.src)
549 attempt := 0
550 for {
551 var rbuf readyBuffer
552 rbuf.seenReady.Add(1)
553 ctx, cancel := context.WithCancel(t.Context())
554 r, err := interp.New(
555 interp.StdIO(nil, &rbuf, &rbuf),
556 interp.ExecHandler(interp.DefaultExecHandler(test.killTimeout)),
557 )
558 if err != nil {
559 t.Fatal(err)
560 }
561 go func() {
562 rbuf.seenReady.Wait()
563 cancel()
564 }()
565 err = r.Run(ctx, file)
566 if test.forcedKill {
567 if _, ok := errors.AsType[interp.ExitStatus](err); ok || err == nil {
568 t.Error("command was not force-killed")
569 }
570 } else {
571 if err != nil && err != context.Canceled && err != context.DeadlineExceeded {
572 t.Errorf("execution errored: %v", err)
573 }
574 }
575 got := rbuf.buf.String()
576 if got != test.want {
577 if attempt < 3 && got == "" && test.killTimeout > 0 {
578 attempt++
579 test.killTimeout *= 2
580 continue
581 }
582 t.Fatalf("want:\n%s\ngot:\n%s", test.want, got)
583 }
584 break
585 }
586 })
587 }
588 }
589
590 func TestKillSignal(t *testing.T) {
591 if runtime.GOOS == "windows" {
592 t.Skip("skipping signal tests on windows")
593 }
594 if !canExec {
595 t.Skipf("skipping test needing subprocesses on %s", runtime.GOOS)
596 }
597 tests := []struct {
598 signal os.Signal
599 want error
600 }{
601 {syscall.SIGINT, interp.ExitStatus(130)}, // 128 + 2
602 {syscall.SIGKILL, interp.ExitStatus(137)}, // 128 + 9
603 {syscall.SIGTERM, interp.ExitStatus(143)}, // 128 + 15
604 }
605
606 // pid_and_hang is implemented in TestMain; we use it to have the
607 // interpreter spawn a process, and easily grab its PID to send it a
608 // signal directly. The program prints its PID and hangs forever.
609 file := parse(t, nil, "GOSH_CMD=pid_and_hang $GOSH_PROG")
610 for _, test := range tests {
611 t.Run(fmt.Sprintf("signal-%d", test.signal), func(t *testing.T) {
612 t.Parallel()
613
614 ctx, cancel := context.WithTimeout(t.Context(), time.Second)
615 defer cancel()
616
617 outReader, outWriter := io.Pipe()
618 stderr := new(bytes.Buffer)
619 r, _ := interp.New(interp.StdIO(nil, outWriter, stderr))
620 errch := make(chan error, 1)
621 go func() {
622 errch <- r.Run(ctx, file)
623 outWriter.Close()
624 }()
625
626 br := bufio.NewReader(outReader)
627 line, err := br.ReadString('\n')
628 if err != nil {
629 t.Fatal(err)
630 }
631 pid, err := strconv.Atoi(strings.TrimSpace(line))
632 if err != nil {
633 t.Fatal(err)
634 }
635
636 proc, err := os.FindProcess(pid)
637 if err != nil {
638 t.Fatal(err)
639 }
640 if err := proc.Signal(test.signal); err != nil {
641 t.Fatal(err)
642 }
643 if got := <-errch; got != test.want {
644 t.Fatalf("want error %v, got %v. stderr: %s", test.want, got, stderr)
645 }
646 })
647 }
648 }