diff --git a/hack/ci/suites.yaml b/hack/ci/suites.yaml index cf29fd96d..90d1a0528 100644 --- a/hack/ci/suites.yaml +++ b/hack/ci/suites.yaml @@ -101,6 +101,14 @@ unit: run: '^(TestInvocationSuite|TestProviderDaemonOverrides.*|TestStdioTransportSuite|TestLaunch.*|TestEnvBlock.*)$' args: [-race, -count=1, -v, -timeout=5m] + - name: windows-provider-launch + description: native Windows provider executable launch and launch failure reporting + os: [windows] + packages: [./pkg/shell, ./pkg/client/clientimplementation] + run: '^(TestExecutablePathTestSuite|TestProviderCommandErrorTestSuite)$' + require_tests: [TestExecutablePathTestSuite, TestProviderCommandErrorTestSuite] + args: [-race, -count=1, -v, -timeout=5m] + - name: windows-wslg-boundaries description: WSLg preflight, discovery and Compose environment boundaries on native Windows os: [windows] diff --git a/pkg/client/clientimplementation/process_other.go b/pkg/client/clientimplementation/process_other.go new file mode 100644 index 000000000..f007d2a5c --- /dev/null +++ b/pkg/client/clientimplementation/process_other.go @@ -0,0 +1,7 @@ +//go:build !windows + +package clientimplementation + +func isInvalidProcessParameter(error) bool { + return false +} diff --git a/pkg/client/clientimplementation/process_windows.go b/pkg/client/clientimplementation/process_windows.go new file mode 100644 index 000000000..ba98cf2e2 --- /dev/null +++ b/pkg/client/clientimplementation/process_windows.go @@ -0,0 +1,17 @@ +//go:build windows + +package clientimplementation + +import ( + "errors" + "io/fs" + + "golang.org/x/sys/windows" +) + +func isInvalidProcessParameter(err error) bool { + var pathErr *fs.PathError + return errors.As(err, &pathErr) && + pathErr.Op == "fork/exec" && + errors.Is(pathErr.Err, windows.ERROR_INVALID_PARAMETER) +} diff --git a/pkg/client/clientimplementation/provider_command_error_test.go b/pkg/client/clientimplementation/provider_command_error_test.go new file mode 100644 index 000000000..b265a5078 --- /dev/null +++ b/pkg/client/clientimplementation/provider_command_error_test.go @@ -0,0 +1,45 @@ +package clientimplementation + +import ( + "errors" + "io/fs" + "testing" + + "github.com/devsy-org/devsy/pkg/provider" + "github.com/stretchr/testify/suite" +) + +type ProviderCommandErrorTestSuite struct { + suite.Suite +} + +func TestProviderCommandErrorTestSuite(t *testing.T) { + suite.Run(t, new(ProviderCommandErrorTestSuite)) +} + +func (s *ProviderCommandErrorTestSuite) TestOmitsEmptyAction() { + cause := errors.New("exit status 255") + + err := providerCommandError("${SSH_PROVIDER} init", nil, cause) + + s.Equal(`run provider command "${SSH_PROVIDER} init": exit status 255`, err.Error()) + s.ErrorIs(err, cause) +} + +func (s *ProviderCommandErrorTestSuite) TestIncludesAction() { + cause := errors.New("exit status 1") + environ := []string{"UNRELATED=value", provider.CommandEnv + "=ls"} + + err := providerCommandError("${SSH_PROVIDER} command", environ, cause) + + s.Equal(`run provider command "${SSH_PROVIDER} command" (ls): exit status 1`, err.Error()) +} + +func (s *ProviderCommandErrorTestSuite) TestPlainStartFailureHasNoWindowsHint() { + cause := &fs.PathError{Op: "fork/exec", Path: "provider", Err: fs.ErrPermission} + + err := providerCommandError("provider", nil, cause) + + s.NotContains(err.Error(), "ERROR_INVALID_PARAMETER") + s.ErrorIs(err, fs.ErrPermission) +} diff --git a/pkg/client/clientimplementation/provider_command_error_windows_test.go b/pkg/client/clientimplementation/provider_command_error_windows_test.go new file mode 100644 index 000000000..6bd3efaa9 --- /dev/null +++ b/pkg/client/clientimplementation/provider_command_error_windows_test.go @@ -0,0 +1,38 @@ +//go:build windows + +package clientimplementation + +import ( + "io/fs" + "os" + "os/exec" + "syscall" + + "golang.org/x/sys/windows" +) + +func (s *ProviderCommandErrorTestSuite) TestRealInvalidParameterStartFailureGetsHint() { + self, err := os.Executable() + s.Require().NoError(err) + cmd := exec.Command(self) + cmd.SysProcAttr = &syscall.SysProcAttr{ + CreationFlags: windows.DETACHED_PROCESS | windows.CREATE_NEW_CONSOLE, + } + startErr := cmd.Start() + s.Require().ErrorIs(startErr, windows.ERROR_INVALID_PARAMETER) + + err = providerCommandError(self, nil, startErr) + + s.ErrorIs(err, windows.ERROR_INVALID_PARAMETER) + s.Contains(err.Error(), invalidProcessParameterHint) + s.Contains(err.Error(), "The parameter is incorrect") +} + +func (s *ProviderCommandErrorTestSuite) TestInvalidParameterFromOutputWriterGetsNoHint() { + writeErr := &fs.PathError{Op: "write", Path: "stdout", Err: windows.ERROR_INVALID_PARAMETER} + + err := providerCommandError("provider", nil, writeErr) + + s.ErrorIs(err, windows.ERROR_INVALID_PARAMETER) + s.NotContains(err.Error(), invalidProcessParameterHint) +} diff --git a/pkg/client/clientimplementation/workspace_client.go b/pkg/client/clientimplementation/workspace_client.go index 54d4e44c0..06226e4c8 100644 --- a/pkg/client/clientimplementation/workspace_client.go +++ b/pkg/client/clientimplementation/workspace_client.go @@ -245,12 +245,13 @@ func (s *workspaceClient) Command(ctx context.Context, opt client.CommandOptions } return RunCommand(ctx, RunCommandOptions{ - Command: s.providerConfig.Exec.Command, - Environ: environ, - Stdin: opt.Stdin, - Stdout: opt.Stdout, - Stderr: opt.Stderr, - RawStdout: opt.RawStdout, + Command: s.providerConfig.Exec.Command, + Environ: environ, + ProviderBinaries: s.providerConfig.Binaries, + Stdin: opt.Stdin, + Stdout: opt.Stdout, + Stderr: opt.Stderr, + RawStdout: opt.RawStdout, }) } @@ -266,9 +267,10 @@ func (s *workspaceClient) OpenCommandTransport( ctx, func(ctx context.Context, stdin io.Reader, stdout io.Writer) error { return RunCommand(ctx, RunCommandOptions{ - Command: s.providerConfig.Exec.Command, - Environ: environ, - Stdin: stdin, Stdout: stdout, Stderr: opt.Stderr, + Command: s.providerConfig.Exec.Command, + Environ: environ, + ProviderBinaries: s.providerConfig.Binaries, + Stdin: stdin, Stdout: stdout, Stderr: opt.Stderr, RawStdout: true, }) }, @@ -810,22 +812,41 @@ func RunCommandWithBinaries(ctx context.Context, cfg WorkspaceCommandConfig) err } return RunCommand(ctx, RunCommandOptions{ - Command: cfg.Command, - Environ: environ, - Stdin: cfg.Stdin, - Stdout: cfg.Stdout, - Stderr: cfg.Stderr, - RawStdout: cfg.RawStdout, + Command: cfg.Command, + Environ: environ, + ProviderBinaries: cfg.Config.Binaries, + Stdin: cfg.Stdin, + Stdout: cfg.Stdout, + Stderr: cfg.Stderr, + RawStdout: cfg.RawStdout, }) } type RunCommandOptions struct { - Command types.StrArray - Environ []string - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer - RawStdout bool + Command types.StrArray + Environ []string + ProviderBinaries map[string][]*provider.ProviderBinary + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer + RawStdout bool +} + +func providerBinaryPaths( + environ []string, + binaries map[string][]*provider.ProviderBinary, +) map[string]string { + if len(binaries) == 0 { + return nil + } + paths := make(map[string]string, len(binaries)) + for _, entry := range environ { + name, value, ok := strings.Cut(entry, "=") + if _, exists := binaries[name]; ok && exists { + paths[name] = value + } + } + return paths } func RunCommand(ctx context.Context, opts RunCommandOptions) (retErr error) { @@ -857,18 +878,14 @@ func RunCommand(ctx context.Context, opts RunCommandOptions) (retErr error) { if len(opts.Command) == 1 { if err := shell.RunEmulatedShell(ctx, &shell.CommandRunner{ - Command: opts.Command[0], - Stdin: opts.Stdin, - Stdout: stdout, - Stderr: stderr, - Environ: opts.Environ, + Command: opts.Command[0], + Stdin: opts.Stdin, + Stdout: stdout, + Stderr: stderr, + Environ: opts.Environ, + ExecutablePaths: providerBinaryPaths(opts.Environ, opts.ProviderBinaries), }); err != nil { - return fmt.Errorf( - "run provider command %q (%s): %w", - opts.Command[0], - providerAction(opts.Environ), - err, - ) + return providerCommandError(opts.Command[0], opts.Environ, err) } return nil } @@ -879,10 +896,7 @@ func RunCommand(ctx context.Context, opts RunCommandOptions) (retErr error) { cmd.Stderr = stderr cmd.Env = opts.Environ if err := cmd.Run(); err != nil { - return fmt.Errorf( - "run provider command %q (%s): %w", - strings.Join(opts.Command, " "), providerAction(opts.Environ), err, - ) + return providerCommandError(strings.Join(opts.Command, " "), opts.Environ, err) } return nil } @@ -901,6 +915,25 @@ func flushCommandOutput(stdout, stderr *subprocess.StreamingRedactingWriter) err return errors.Join(stdoutErr, stderrErr) } +const invalidProcessParameterHint = "Windows rejected starting the provider executable " + + "(ERROR_INVALID_PARAMETER) before it ran, so this is a local process-launch failure " + + "rather than a remote host error; the cause is unconfirmed, so please report the Windows " + + "version and whether running the executable directly from a terminal works" + +func providerCommandError(command string, environ []string, err error) error { + action := "" + if name := providerAction(environ); name != "" { + action = fmt.Sprintf(" (%s)", name) + } + if isInvalidProcessParameter(err) { + return fmt.Errorf( + "run provider command %q%s: %w; %s", + command, action, err, invalidProcessParameterHint, + ) + } + return fmt.Errorf("run provider command %q%s: %w", command, action, err) +} + // providerAction extracts the provider action from the environment variables. func providerAction(environ []string) string { for _, kv := range environ { diff --git a/pkg/shell/executable_path_test.go b/pkg/shell/executable_path_test.go new file mode 100644 index 000000000..4147b6734 --- /dev/null +++ b/pkg/shell/executable_path_test.go @@ -0,0 +1,308 @@ +package shell + +import ( + "bytes" + "context" + "io" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/stretchr/testify/suite" +) + +const helperProcessEnv = "DEVSY_SHELL_TEST_HELPER_PROCESS" + +func TestMain(m *testing.M) { + if os.Getenv(helperProcessEnv) == "1" { + _, _ = os.Stdout.WriteString("helper ran with " + os.Args[len(os.Args)-1]) + os.Exit(0) + } + os.Exit(m.Run()) +} + +type ExecutablePathTestSuite struct { + suite.Suite + executable string + executablePaths map[string]string +} + +func TestExecutablePathTestSuite(t *testing.T) { + suite.Run(t, new(ExecutablePathTestSuite)) +} + +func (s *ExecutablePathTestSuite) SetupTest() { + dir := filepath.Join(s.T().TempDir(), "Jane Doe", "binaries") + s.Require().NoError(os.MkdirAll(dir, 0o750)) + + name := "provider" + if runtime.GOOS == "windows" { + name += ".exe" + } + s.executable = filepath.Join(dir, name) + + s.copyTestBinary(s.executable) + s.executablePaths = map[string]string{ + "SSH_PROVIDER": s.executable, + "CMD": s.executable, + "PROVIDER": s.executable, + } +} + +func (s *ExecutablePathTestSuite) TestCommandVariableWithSpacesInPathIsNotSplit() { + output, err := s.run( + "${SSH_PROVIDER} init", + "SSH_PROVIDER="+s.executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestShortVariableFormWithSpacesInPathIsNotSplit() { + output, err := s.run( + "$SSH_PROVIDER init", + "SSH_PROVIDER="+s.executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestCommandVariableWithCustomIFSIsNotSplit() { + output, err := s.run( + "IFS=a; ${SSH_PROVIDER} init", + "SSH_PROVIDER="+s.executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestCustomIFSAlsoSplitsPathsWithoutSpaces() { + executable := filepath.Join(s.T().TempDir(), "a-provider"+filepath.Ext(s.executable)) + s.copyTestBinary(executable) + s.executablePaths["CMD"] = executable + + output, err := s.run( + "IFS=a; $CMD init", + "CMD="+executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestWindowsProviderVariableCaseIsNotSignificant() { + if runtime.GOOS != "windows" { + s.T().Skip() + } + output, err := s.run( + "$ssh_provider init", + "SSH_PROVIDER="+s.executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestCommandVariableWithArgumentsStillSplits() { + output, err := s.run("${CMD} world", "CMD=echo hello") + + s.Require().NoError(err) + s.Equal("hello world\n", output) +} + +func (s *ExecutablePathTestSuite) TestReassignedCommandVariableStillSplits() { + output, err := s.run("CMD='echo hello'; $CMD world", "CMD="+s.executable) + + s.Require().NoError(err) + s.Equal("hello world\n", output) +} + +func (s *ExecutablePathTestSuite) TestLiteralCommandIsNotJoinedWithUnrelatedVariable() { + dir := s.T().TempDir() + ext := filepath.Ext(s.executable) + tool := filepath.Join(dir, "tool"+ext) + spacedTool := tool + " status" + ext + s.copyTestBinary(tool) + s.copyTestBinary(spacedTool) + + s.executablePaths["CMD"] = spacedTool + output, err := s.run( + "'"+tool+"' status"+ext+"; $CMD", + "CMD="+spacedTool, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with status"+ext+"helper ran with "+spacedTool, output) +} + +func (s *ExecutablePathTestSuite) TestRelativePathIsResolvedAgainstShellDirectory() { + shellDir := s.T().TempDir() + relative := filepath.Join("spaced dir", filepath.Base(s.executable)) + s.Require().NoError(os.MkdirAll(filepath.Join(shellDir, "spaced dir"), 0o750)) + s.copyTestBinary(filepath.Join(shellDir, relative)) + s.executablePaths["PROVIDER"] = relative + + output, err := s.run( + "cd '"+shellDir+"'; ${PROVIDER} init", + "PROVIDER="+relative, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestRelativePathExistingOnlyInProcessDirectoryIsNotJoined() { + processDir := s.T().TempDir() + shellDir := s.T().TempDir() + name := "spaced" + filepath.Ext(s.executable) + relative := "." + string(filepath.Separator) + name + " dir" + + string(filepath.Separator) + "provider" + s.Require().NoError(os.MkdirAll(filepath.Join(processDir, name+" dir"), 0o750)) + s.copyTestBinary(filepath.Join(processDir, name+" dir", "provider")) + s.copyTestBinary(filepath.Join(shellDir, name)) + s.T().Chdir(processDir) + s.executablePaths["PROVIDER"] = relative + + output, err := s.run( + "cd '"+shellDir+"'; ${PROVIDER} init", + "PROVIDER="+relative, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestNonBreakingSpaceStaysInsideTheJoinedPath() { + dir := filepath.Join(s.T().TempDir(), "Jane\u00a0Doe and co") + s.Require().NoError(os.MkdirAll(dir, 0o750)) + executable := filepath.Join(dir, filepath.Base(s.executable)) + s.copyTestBinary(executable) + s.executablePaths["PROVIDER"] = executable + + output, err := s.run( + "${PROVIDER} init", + "PROVIDER="+executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestVariableArgumentWithSpacesStillSplits() { + output, err := s.run("echo ${ARGS}", "ARGS=a b") + + s.Require().NoError(err) + s.Equal("a b\n", output) +} + +func (s *ExecutablePathTestSuite) TestSourcedLiteralCommandKeepsItsOwnExecutable() { + dir := s.T().TempDir() + ext := filepath.Ext(s.executable) + tool := filepath.Join(dir, "tool"+ext) + spacedTool := tool + " status" + ext + s.copyTestBinary(tool) + s.copyTestBinary(spacedTool) + source := filepath.Join(dir, "source.sh") + s.Require().NoError(os.WriteFile(source, []byte("'"+tool+"' status"+ext+"\n"), 0o600)) + s.executablePaths["CMD"] = spacedTool + + output, err := s.run( + "$CMD first; source '"+source+"'", + "CMD="+spacedTool, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with firsthelper ran with status"+ext, output) +} + +func (s *ExecutablePathTestSuite) TestGenericShellDoesNotReinterpretSpacedFile() { + dir := s.T().TempDir() + ext := filepath.Ext(s.executable) + tool := filepath.Join(dir, "tool"+ext) + spacedTool := tool + " status" + ext + s.copyTestBinary(tool) + s.copyTestBinary(spacedTool) + s.executablePaths = nil + + output, err := s.run( + "$CMD init", + "CMD="+spacedTool, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestProviderVariableReassignedToNonExecutableFileStillSplits() { + dir := s.T().TempDir() + ext := filepath.Ext(s.executable) + tool := filepath.Join(dir, "tool"+ext) + spacedTool := tool + " status" + ext + s.copyTestBinary(tool) + s.Require().NoError(os.WriteFile(spacedTool, []byte("not executable"), 0o600)) + + output, err := s.run( + "CMD='"+spacedTool+"'; $CMD init", + "CMD="+s.executable, + helperProcessEnv+"=1", + ) + + s.Require().NoError(err) + s.Equal("helper ran with init", output) +} + +func (s *ExecutablePathTestSuite) TestEmptyProviderVariableDoesNotRunMarker() { + output, err := s.run( + "CMD=''; $CMD; echo done", + "CMD="+s.executable, + ) + + s.Require().NoError(err) + s.Equal("done\n", output) +} + +func (s *ExecutablePathTestSuite) run(command string, environ ...string) (string, error) { + var stdout, stderr bytes.Buffer + err := RunEmulatedShell(context.Background(), &CommandRunner{ + Command: command, + Stdout: &stdout, + Stderr: &stderr, + Environ: append(os.Environ(), environ...), + ExecutablePaths: s.executablePaths, + }) + return stdout.String(), err +} + +func (s *ExecutablePathTestSuite) copyTestBinary(target string) { + self, err := os.Executable() + s.Require().NoError(err) + sourceRoot, err := os.OpenRoot(filepath.Dir(self)) + s.Require().NoError(err) + defer func() { _ = sourceRoot.Close() }() + source, err := sourceRoot.Open(filepath.Base(self)) + s.Require().NoError(err) + defer func() { _ = source.Close() }() + targetRoot, err := os.OpenRoot(filepath.Dir(target)) + s.Require().NoError(err) + defer func() { _ = targetRoot.Close() }() + file, err := targetRoot.OpenFile(filepath.Base(target), os.O_CREATE|os.O_WRONLY, 0o700) + s.Require().NoError(err) + _, err = io.Copy(file, source) + s.Require().NoError(err) + s.Require().NoError(file.Close()) +} diff --git a/pkg/shell/shell.go b/pkg/shell/shell.go index 6be8172ba..d6e3530c1 100644 --- a/pkg/shell/shell.go +++ b/pkg/shell/shell.go @@ -2,6 +2,7 @@ package shell import ( "context" + "crypto/rand" "errors" "fmt" "io" @@ -10,6 +11,7 @@ import ( "os/user" "path/filepath" "runtime" + "slices" "strings" "time" @@ -19,11 +21,12 @@ import ( ) type CommandRunner struct { - Command string - Environ []string - Stdin io.Reader - Stdout io.Writer - Stderr io.Writer + Command string + Environ []string + ExecutablePaths map[string]string + Stdin io.Reader + Stdout io.Writer + Stderr io.Writer } func RunEmulatedShell( @@ -46,12 +49,20 @@ func RunEmulatedShell( return err } + var commandVars map[syntax.Pos]executableCommand + marker := "" + if len(runner.ExecutablePaths) > 0 { + marker = rand.Text() + commandVars = commandVariables(parsed, runner.ExecutablePaths, marker) + } r, err := interp.New(buildRunnerOptions(shellRunnerOptions{ - stdin: runner.Stdin, - stdout: runner.Stdout, - stderr: runner.Stderr, - env: runner.Environ, - dir: dir, + stdin: runner.Stdin, + stdout: runner.Stdout, + stderr: runner.Stderr, + env: runner.Environ, + dir: dir, + commandVars: commandVars, + marker: marker, })...) if err != nil { return fmt.Errorf("create shell runner: %w", err) @@ -70,12 +81,125 @@ func RunEmulatedShell( return nil } +func commandVariables( + file *syntax.File, + paths map[string]string, + marker string, +) map[syntax.Pos]executableCommand { + printer := syntax.NewPrinter() + names := map[syntax.Pos]executableCommand{} + syntax.Walk(file, func(node syntax.Node) bool { + call, ok := node.(*syntax.CallExpr) + if !ok { + return true + } + name := executableCommandVariable(call, paths, printer) + if name != "" { + word := call.Args[0] + path, _ := configuredExecutablePath(paths, name) + call.Args = append(call.Args, &syntax.Word{ + Parts: []syntax.WordPart{&syntax.Lit{Value: marker}}, + }) + names[word.Pos()] = executableCommand{name: name, word: word, path: path} + } + return true + }) + return names +} + +type executableCommand struct { + name string + word *syntax.Word + path string +} + +func configuredExecutablePath(paths map[string]string, name string) (string, bool) { + if path, ok := paths[name]; ok { + return path, true + } + if runtime.GOOS == "windows" { + for configuredName, path := range paths { + if strings.EqualFold(configuredName, name) { + return path, true + } + } + } + return "", false +} + +func executableCommandVariable( + call *syntax.CallExpr, + paths map[string]string, + printer *syntax.Printer, +) string { + if len(call.Args) == 0 || len(call.Assigns) != 0 { + return "" + } + word := call.Args[0] + if len(word.Parts) != 1 { + return "" + } + exp, ok := word.Parts[0].(*syntax.ParamExp) + if !ok || exp.Param == nil { + return "" + } + name := exp.Param.Value + if _, enabled := configuredExecutablePath(paths, name); enabled && + isPlainExpansion(printer, word, name) { + return name + } + return "" +} + +func isPlainExpansion(printer *syntax.Printer, word *syntax.Word, name string) bool { + var sb strings.Builder + if err := printer.Print(&sb, word); err != nil { + return false + } + return sb.String() == "$"+name || sb.String() == "${"+name+"}" +} + +func joinExecutablePath( + args []string, + env expand.Environ, + dir string, + command executableCommand, +) []string { + fields := strings.FieldsFunc(command.path, isIFSDelimiter) + if ifs := env.Get("IFS"); ifs.IsSet() && ifs.String() != " \t\n" { + var err error + fields, err = expand.Fields(&expand.Config{Env: env}, command.word) + if err != nil { + return args + } + } + if len(fields) < 2 || len(args) < len(fields) || + !slices.Equal(args[:len(fields)], fields) || !isExistingFile(dir, command.path) { + return args + } + return append([]string{command.path}, args[len(fields):]...) +} + +func isIFSDelimiter(r rune) bool { + return r == ' ' || r == '\t' || r == '\n' +} + +func isExistingFile(dir, path string) bool { + if !filepath.IsAbs(path) { + path = filepath.Join(dir, path) + } + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + type shellRunnerOptions struct { - stdin io.Reader - stdout io.Writer - stderr io.Writer - env []string - dir string + stdin io.Reader + stdout io.Writer + stderr io.Writer + env []string + dir string + commandVars map[syntax.Pos]executableCommand + marker string } func buildRunnerOptions(p shellRunnerOptions) []interp.RunnerOption { @@ -96,6 +220,17 @@ func buildRunnerOptions(p shellRunnerOptions) []interp.RunnerOption { // command to an absolute path so IsBuiltin returns false and the // real binary is executed via the exec handler. interp.CallHandler(func(ctx context.Context, args []string) ([]string, error) { + hc := interp.HandlerCtx(ctx) + if p.marker != "" && args[len(args)-1] == p.marker { + args = args[:len(args)-1] + if len(args) == 0 { + return []string{":"}, nil + } + if command, ok := p.commandVars[hc.Pos]; ok && + hc.Env.Get(command.name).String() == command.path { + args = joinExecutablePath(args, hc.Env, hc.Dir, command) + } + } if args[0] == "kill" { args[0] = "/bin/kill" } diff --git a/sites/docs-devsy-sh/content/docs/managing-providers/manage-providers.mdx b/sites/docs-devsy-sh/content/docs/managing-providers/manage-providers.mdx index 1054c8a2e..54b47f9a1 100644 --- a/sites/docs-devsy-sh/content/docs/managing-providers/manage-providers.mdx +++ b/sites/docs-devsy-sh/content/docs/managing-providers/manage-providers.mdx @@ -103,6 +103,12 @@ devsy provider add builtin:microsandbox --name legacy-microsandbox --use=false If a switch fails during initialization, the new source stays selected. Fix the cause and run `devsy provider init `, or set the previous source again. Add `--version ` to `set-source` to pin a release. +### Windows provider launch errors + +Provider binary variables resolve to installed executable paths. An executable under a Windows profile path with spaces is treated as one command, rather than split at the spaces. + +If initialization reports `ERROR_INVALID_PARAMETER` while starting the executable, the provider did not run. This is a local process launch failure, not an SSH host error. Check the Windows version and try running the installed executable directly from a terminal. The error does not identify which process parameter Windows rejected. + ## Set provider options Each provider has its own options. In the desktop app, open **Providers** and click **Edit** on a provider. With the CLI, set options when you add or initialize: