shell.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Package shell provides cross-platform shell execution capabilities.
  2. //
  3. // This package offers two main types:
  4. // - Shell: A general-purpose shell executor for one-off or managed commands
  5. // - PersistentShell: A singleton shell that maintains state across the application
  6. //
  7. // WINDOWS COMPATIBILITY:
  8. // This implementation provides both POSIX shell emulation (mvdan.cc/sh/v3),
  9. // even on Windows. Some caution has to be taken: commands should have forward
  10. // slashes (/) as path separators to work, even on Windows.
  11. package shell
  12. import (
  13. "bytes"
  14. "context"
  15. "errors"
  16. "fmt"
  17. "os"
  18. "strings"
  19. "sync"
  20. "mvdan.cc/sh/moreinterp/coreutils"
  21. "mvdan.cc/sh/v3/expand"
  22. "mvdan.cc/sh/v3/interp"
  23. "mvdan.cc/sh/v3/syntax"
  24. )
  25. // ShellType represents the type of shell to use
  26. type ShellType int
  27. const (
  28. ShellTypePOSIX ShellType = iota
  29. ShellTypeCmd
  30. ShellTypePowerShell
  31. )
  32. // Logger interface for optional logging
  33. type Logger interface {
  34. InfoPersist(msg string, keysAndValues ...any)
  35. }
  36. // noopLogger is a logger that does nothing
  37. type noopLogger struct{}
  38. func (noopLogger) InfoPersist(msg string, keysAndValues ...any) {}
  39. // BlockFunc is a function that determines if a command should be blocked
  40. type BlockFunc func(args []string) bool
  41. // Shell provides cross-platform shell execution with optional state persistence
  42. type Shell struct {
  43. env []string
  44. cwd string
  45. mu sync.Mutex
  46. logger Logger
  47. blockFuncs []BlockFunc
  48. }
  49. // Options for creating a new shell
  50. type Options struct {
  51. WorkingDir string
  52. Env []string
  53. Logger Logger
  54. BlockFuncs []BlockFunc
  55. }
  56. // NewShell creates a new shell instance with the given options
  57. func NewShell(opts *Options) *Shell {
  58. if opts == nil {
  59. opts = &Options{}
  60. }
  61. cwd := opts.WorkingDir
  62. if cwd == "" {
  63. cwd, _ = os.Getwd()
  64. }
  65. env := opts.Env
  66. if env == nil {
  67. env = os.Environ()
  68. }
  69. logger := opts.Logger
  70. if logger == nil {
  71. logger = noopLogger{}
  72. }
  73. return &Shell{
  74. cwd: cwd,
  75. env: env,
  76. logger: logger,
  77. blockFuncs: opts.BlockFuncs,
  78. }
  79. }
  80. // Exec executes a command in the shell
  81. func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
  82. s.mu.Lock()
  83. defer s.mu.Unlock()
  84. return s.execPOSIX(ctx, command)
  85. }
  86. // GetWorkingDir returns the current working directory
  87. func (s *Shell) GetWorkingDir() string {
  88. s.mu.Lock()
  89. defer s.mu.Unlock()
  90. return s.cwd
  91. }
  92. // SetWorkingDir sets the working directory
  93. func (s *Shell) SetWorkingDir(dir string) error {
  94. s.mu.Lock()
  95. defer s.mu.Unlock()
  96. // Verify the directory exists
  97. if _, err := os.Stat(dir); err != nil {
  98. return fmt.Errorf("directory does not exist: %w", err)
  99. }
  100. s.cwd = dir
  101. return nil
  102. }
  103. // GetEnv returns a copy of the environment variables
  104. func (s *Shell) GetEnv() []string {
  105. s.mu.Lock()
  106. defer s.mu.Unlock()
  107. env := make([]string, len(s.env))
  108. copy(env, s.env)
  109. return env
  110. }
  111. // SetEnv sets an environment variable
  112. func (s *Shell) SetEnv(key, value string) {
  113. s.mu.Lock()
  114. defer s.mu.Unlock()
  115. // Update or add the environment variable
  116. keyPrefix := key + "="
  117. for i, env := range s.env {
  118. if strings.HasPrefix(env, keyPrefix) {
  119. s.env[i] = keyPrefix + value
  120. return
  121. }
  122. }
  123. s.env = append(s.env, keyPrefix+value)
  124. }
  125. // SetBlockFuncs sets the command block functions for the shell
  126. func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
  127. s.mu.Lock()
  128. defer s.mu.Unlock()
  129. s.blockFuncs = blockFuncs
  130. }
  131. // CommandsBlocker creates a BlockFunc that blocks exact command matches
  132. func CommandsBlocker(bannedCommands []string) BlockFunc {
  133. bannedSet := make(map[string]bool)
  134. for _, cmd := range bannedCommands {
  135. bannedSet[cmd] = true
  136. }
  137. return func(args []string) bool {
  138. if len(args) == 0 {
  139. return false
  140. }
  141. return bannedSet[args[0]]
  142. }
  143. }
  144. // ArgumentsBlocker creates a BlockFunc that blocks specific subcommands
  145. func ArgumentsBlocker(blockedSubCommands [][]string) BlockFunc {
  146. return func(args []string) bool {
  147. for _, blocked := range blockedSubCommands {
  148. if len(args) >= len(blocked) {
  149. match := true
  150. for i, part := range blocked {
  151. if args[i] != part {
  152. match = false
  153. break
  154. }
  155. }
  156. if match {
  157. return true
  158. }
  159. }
  160. }
  161. return false
  162. }
  163. }
  164. func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  165. return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  166. return func(ctx context.Context, args []string) error {
  167. if len(args) == 0 {
  168. return next(ctx, args)
  169. }
  170. for _, blockFunc := range s.blockFuncs {
  171. if blockFunc(args) {
  172. return fmt.Errorf("command is not allowed for security reasons: %s", strings.Join(args, " "))
  173. }
  174. }
  175. return next(ctx, args)
  176. }
  177. }
  178. }
  179. // execPOSIX executes commands using POSIX shell emulation (cross-platform)
  180. func (s *Shell) execPOSIX(ctx context.Context, command string) (string, string, error) {
  181. line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
  182. if err != nil {
  183. return "", "", fmt.Errorf("could not parse command: %w", err)
  184. }
  185. var stdout, stderr bytes.Buffer
  186. runner, err := interp.New(
  187. interp.StdIO(nil, &stdout, &stderr),
  188. interp.Interactive(false),
  189. interp.Env(expand.ListEnviron(s.env...)),
  190. interp.Dir(s.cwd),
  191. interp.ExecHandlers(s.blockHandler(), coreutils.ExecHandler),
  192. )
  193. if err != nil {
  194. return "", "", fmt.Errorf("could not run command: %w", err)
  195. }
  196. err = runner.Run(ctx, line)
  197. s.cwd = runner.Dir
  198. s.env = []string{}
  199. for name, vr := range runner.Vars {
  200. s.env = append(s.env, fmt.Sprintf("%s=%s", name, vr.Str))
  201. }
  202. s.logger.InfoPersist("POSIX command finished", "command", command, "err", err)
  203. return stdout.String(), stderr.String(), err
  204. }
  205. // IsInterrupt checks if an error is due to interruption
  206. func IsInterrupt(err error) bool {
  207. return errors.Is(err, context.Canceled) ||
  208. errors.Is(err, context.DeadlineExceeded)
  209. }
  210. // ExitCode extracts the exit code from an error
  211. func ExitCode(err error) int {
  212. if err == nil {
  213. return 0
  214. }
  215. var exitErr interp.ExitStatus
  216. if errors.As(err, &exitErr) {
  217. return int(exitErr)
  218. }
  219. return 1
  220. }