diff --git a/internal/shellwrap/cmdline_other.go b/internal/shellwrap/cmdline_other.go new file mode 100644 index 000000000..2f60660c4 --- /dev/null +++ b/internal/shellwrap/cmdline_other.go @@ -0,0 +1,8 @@ +//go:build !windows + +package shellwrap + +import "os/exec" + +// UseVerbatimCmdLine is a no-op outside Windows; see cmdline_windows.go. +func UseVerbatimCmdLine(*exec.Cmd) {} diff --git a/internal/shellwrap/cmdline_other_test.go b/internal/shellwrap/cmdline_other_test.go new file mode 100644 index 000000000..243df660e --- /dev/null +++ b/internal/shellwrap/cmdline_other_test.go @@ -0,0 +1,18 @@ +//go:build !windows + +package shellwrap + +import ( + "os/exec" + "testing" +) + +// Outside Windows UseVerbatimCmdLine must leave the command untouched; the +// verbatim-cmdline behavior itself is asserted in cmdline_windows_test.go. +func TestUseVerbatimCmdLine_NoOpOutsideWindows(t *testing.T) { + cmd := exec.Command("sh", "-c", "true") + UseVerbatimCmdLine(cmd) + if cmd.SysProcAttr != nil { + t.Fatal("UseVerbatimCmdLine must not touch SysProcAttr outside Windows") + } +} diff --git a/internal/shellwrap/cmdline_windows.go b/internal/shellwrap/cmdline_windows.go new file mode 100644 index 000000000..7a3da7d70 --- /dev/null +++ b/internal/shellwrap/cmdline_windows.go @@ -0,0 +1,27 @@ +//go:build windows + +package shellwrap + +import ( + "os/exec" + "path/filepath" + "strings" + "syscall" +) + +// UseVerbatimCmdLine makes a `cmd.exe /c ` invocation (the +// shape WrapWithUserShell returns for cmd.exe) reach cmd.exe as written. Go +// would otherwise quote the command string as one argument and escape its +// embedded quotes as \", which cmd.exe does not understand, so any quoted +// path or argument (e.g. one under "Program Files") failed to run (#1960). +// Any other command is left unchanged. +func UseVerbatimCmdLine(cmd *exec.Cmd) { + if len(cmd.Args) != 3 || cmd.Args[1] != "/c" || !strings.EqualFold(filepath.Base(cmd.Path), "cmd.exe") { + return + } + if cmd.SysProcAttr == nil { + cmd.SysProcAttr = &syscall.SysProcAttr{} + } + // /s: cmd.exe strips only the outer quotes and runs the rest as written. + cmd.SysProcAttr.CmdLine = syscall.EscapeArg(cmd.Args[0]) + ` /s /c "` + cmd.Args[2] + `"` +} diff --git a/internal/shellwrap/cmdline_windows_test.go b/internal/shellwrap/cmdline_windows_test.go new file mode 100644 index 000000000..3b7c791ed --- /dev/null +++ b/internal/shellwrap/cmdline_windows_test.go @@ -0,0 +1,37 @@ +//go:build windows + +package shellwrap + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// #1960: a cmd.exe-wrapped command whose path and argument contain spaces +// must run, with the argument intact. +func TestUseVerbatimCmdLine_PathWithSpace(t *testing.T) { + t.Setenv("SHELL", "") // force cmd.exe even under Git Bash + + dir := filepath.Join(t.TempDir(), "HTTP Toolkit") + if err := os.Mkdir(dir, 0o755); err != nil { + t.Fatal(err) + } + script := filepath.Join(dir, "echo-arg.cmd") + if err := os.WriteFile(script, []byte("@echo off\r\necho [%~1]\r\n"), 0o600); err != nil { + t.Fatal(err) + } + + shell, args := WrapWithUserShell(nil, script, []string{"a b"}) + cmd := exec.Command(shell, args...) + UseVerbatimCmdLine(cmd) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("run failed: %v\n%s", err, out) + } + if got := strings.TrimSpace(string(out)); got != "[a b]" { + t.Fatalf("output = %q, want %q", got, "[a b]") + } +} diff --git a/internal/upstream/core/cmdline_windows_test.go b/internal/upstream/core/cmdline_windows_test.go new file mode 100644 index 000000000..0986a0119 --- /dev/null +++ b/internal/upstream/core/cmdline_windows_test.go @@ -0,0 +1,50 @@ +//go:build windows + +package core + +import ( + "context" + "os/exec" + "syscall" + "testing" + + "github.com/stretchr/testify/require" + "go.uber.org/zap" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secureenv" +) + +// #1960: both upstream spawn paths must hand cmd.exe the wrapped command +// string verbatim, or a quoted path with a space fails to start. +func TestSpawnSitesUseVerbatimCmdLine(t *testing.T) { + t.Setenv("SHELL", "") // force cmd.exe even under Git Bash + command := `C:\Program Files\Tool\server.cmd` + args := []string{"a b"} + + assertVerbatim := func(t *testing.T, cmd *exec.Cmd) { + t.Helper() + require.Len(t, cmd.Args, 3) + require.NotNil(t, cmd.SysProcAttr) + require.Equal(t, syscall.EscapeArg(cmd.Args[0])+` /s /c "`+cmd.Args[2]+`"`, cmd.SysProcAttr.CmdLine) + } + + t.Run("stdio", func(t *testing.T) { + c := &Client{config: &config.ServerConfig{Name: "s", Command: command, Args: args}, logger: zap.NewNop()} + shell, shellArgs := c.wrapWithUserShell(command, args) + cmd, err := createProcessGroupCommandFunc(nil, "", zap.NewNop())(context.Background(), shell, nil, shellArgs) + require.NoError(t, err) + assertVerbatim(t, cmd) + }) + + t.Run("launcher", func(t *testing.T) { + c := &Client{ + config: &config.ServerConfig{Name: "s", Command: command, Args: args}, + logger: zap.NewNop(), + envManager: secureenv.NewManager(nil), + } + cmd, _, _, err := c.buildLauncherCmd(context.Background(), false) + require.NoError(t, err) + assertVerbatim(t, cmd) + }) +} diff --git a/internal/upstream/core/connection_docker_integration_test.go b/internal/upstream/core/connection_docker_integration_test.go index df7986fc2..e85441347 100644 --- a/internal/upstream/core/connection_docker_integration_test.go +++ b/internal/upstream/core/connection_docker_integration_test.go @@ -1,6 +1,7 @@ package core import ( + "context" "fmt" "path/filepath" "runtime" @@ -192,6 +193,30 @@ func TestIntegration_DockerUnresolvable_FallsBackToBareDocker(t *testing.T) { "only a genuinely-absent docker should degrade to bare 'docker', got %q", cmdStr) } +// TestIntegration_NewDockerCmd_UnresolvableFallsBackToShellWrap covers the +// newDockerCmd spawn fallback: with docker genuinely absent it must degrade to +// the user-shell wrap of bare `docker` — the wrap that on Windows needs the +// verbatim cmd.exe command line (#1960) to survive quoted paths. +func TestIntegration_NewDockerCmd_UnresolvableFallsBackToShellWrap(t *testing.T) { + shellwrap.ResetDockerPathCacheForTest() + t.Cleanup(shellwrap.ResetDockerPathCacheForTest) + restore := shellwrap.SetWellKnownDockerPathsForTest(func() []string { return nil }) + t.Cleanup(restore) + t.Setenv("PATH", t.TempDir()) + if runtime.GOOS == osWindows { + t.Setenv("SHELL", "") // force cmd.exe even under Git Bash + } else { + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") + } + + c := newIsolatedTestClient() + cmd := c.newDockerCmd(context.Background(), "run", "img") + require.NotNil(t, cmd) + cmdStr := cmd.Args[len(cmd.Args)-1] + assert.True(t, strings.HasPrefix(cmdStr, "docker run"), + "unresolvable docker must degrade to the shell wrap, got %q", cmd.Args) +} + // TestIntegration_StatusAndSpawnResolverDoNotDiverge guards the invariant the // #696 v0.39.1 report worried about ("detection discovers docker_path but the // spawn doesn't use it"). docker_status.docker_path (server.dockerPathResolver) diff --git a/internal/upstream/core/connection_launcher.go b/internal/upstream/core/connection_launcher.go index 88e13fb32..2cb4cfb28 100644 --- a/internal/upstream/core/connection_launcher.go +++ b/internal/upstream/core/connection_launcher.go @@ -15,6 +15,7 @@ import ( "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" "github.com/smart-mcp-proxy/mcpproxy-go/internal/logs" "github.com/smart-mcp-proxy/mcpproxy-go/internal/oauth" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/shellwrap" "github.com/smart-mcp-proxy/mcpproxy-go/internal/upstream/launcher" ) @@ -338,6 +339,7 @@ func (c *Client) buildLauncherCmd(_ context.Context, willUseDocker bool) (*exec. } cmd := exec.Command(finalCommand, finalArgs...) + shellwrap.UseVerbatimCmdLine(cmd) cmd.Env = envVars if c.config.WorkingDir != "" { cmd.Dir = c.config.WorkingDir diff --git a/internal/upstream/core/docker.go b/internal/upstream/core/docker.go index f119de427..e2ac6a73f 100644 --- a/internal/upstream/core/docker.go +++ b/internal/upstream/core/docker.go @@ -34,6 +34,7 @@ func (c *Client) newDockerCmd(ctx context.Context, args ...string) *exec.Cmd { // interactive PATH the user sees in Terminal. shell, shellArgs := c.wrapWithUserShell("docker", args) cmd := exec.CommandContext(ctx, shell, shellArgs...) + shellwrap.UseVerbatimCmdLine(cmd) if c.envManager != nil { cmd.Env = c.envManager.BuildSecureEnvironment() } diff --git a/internal/upstream/core/process_windows.go b/internal/upstream/core/process_windows.go index 4642448e3..27a2ce683 100644 --- a/internal/upstream/core/process_windows.go +++ b/internal/upstream/core/process_windows.go @@ -12,6 +12,7 @@ import ( "go.uber.org/zap" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/shellwrap" "github.com/smart-mcp-proxy/mcpproxy-go/internal/winjob" ) @@ -46,6 +47,7 @@ var ( func createProcessGroupCommandFunc(client *Client, workingDir string, logger *zap.Logger) func(ctx context.Context, command string, env []string, args []string) (*exec.Cmd, error) { return func(ctx context.Context, command string, env []string, args []string) (*exec.Cmd, error) { cmd := exec.CommandContext(ctx, command, args...) + shellwrap.UseVerbatimCmdLine(cmd) cmd.Env = env // Start suspended: the child runs no code until it is in its Job // Object (assignProcessTree resumes it), so it cannot fork a