Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions internal/shellwrap/cmdline_other.go
Original file line number Diff line number Diff line change
@@ -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) {}
18 changes: 18 additions & 0 deletions internal/shellwrap/cmdline_other_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
27 changes: 27 additions & 0 deletions internal/shellwrap/cmdline_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//go:build windows

package shellwrap

import (
"os/exec"
"path/filepath"
"strings"
"syscall"
)

// UseVerbatimCmdLine makes a `cmd.exe /c <command string>` 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] + `"`
}
37 changes: 37 additions & 0 deletions internal/shellwrap/cmdline_windows_test.go
Original file line number Diff line number Diff line change
@@ -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]")
}
}
50 changes: 50 additions & 0 deletions internal/upstream/core/cmdline_windows_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
25 changes: 25 additions & 0 deletions internal/upstream/core/connection_docker_integration_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package core

import (
"context"
"fmt"
"path/filepath"
"runtime"
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions internal/upstream/core/connection_launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions internal/upstream/core/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
2 changes: 2 additions & 0 deletions internal/upstream/core/process_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down
Loading