|
| 1 | +package core |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "path/filepath" |
| 6 | + "runtime" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + |
| 10 | + "github.com/smart-mcp-proxy/mcpproxy-go/internal/shellwrap" |
| 11 | + |
| 12 | + "github.com/stretchr/testify/assert" |
| 13 | + "github.com/stretchr/testify/require" |
| 14 | + "go.uber.org/zap" |
| 15 | + "go.uber.org/zap/zaptest/observer" |
| 16 | +) |
| 17 | + |
| 18 | +// newObservedIsolatedClient returns an isolated test client whose logger feeds |
| 19 | +// an in-memory observer, so tests can assert on the spawn-decision INFO logs. |
| 20 | +func newObservedIsolatedClient(t *testing.T) (*Client, *observer.ObservedLogs) { |
| 21 | + t.Helper() |
| 22 | + core, recorded := observer.New(zap.InfoLevel) |
| 23 | + c := newIsolatedTestClient() |
| 24 | + c.logger = zap.New(core) |
| 25 | + return c, recorded |
| 26 | +} |
| 27 | + |
| 28 | +// TestSpawnDecisionIsObservable_DirectExec asserts the #696 diagnosability fix: |
| 29 | +// the direct-exec branch emits an INFO line carrying the resolved docker_path so |
| 30 | +// a field report can be triaged from main.log alone. |
| 31 | +func TestSpawnDecisionIsObservable_DirectExec(t *testing.T) { |
| 32 | + if runtime.GOOS == osWindows { |
| 33 | + t.Skip("unix fake-binary fixture") |
| 34 | + } |
| 35 | + useRealDockerResolver(t) |
| 36 | + forceDockerDaemonEnvGOOS(t, osDarwin) |
| 37 | + |
| 38 | + bundleDocker := writeFakeDockerExecutable(t) |
| 39 | + restore := shellwrap.SetWellKnownDockerPathsForTest(func() []string { return []string{bundleDocker} }) |
| 40 | + t.Cleanup(restore) |
| 41 | + t.Setenv("PATH", t.TempDir()) |
| 42 | + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") |
| 43 | + |
| 44 | + c, recorded := newObservedIsolatedClient(t) |
| 45 | + _, _, shellWrapped := c.setupDockerIsolation(c.config.Command, c.config.Args) |
| 46 | + require.False(t, shellWrapped) |
| 47 | + |
| 48 | + entries := recorded.FilterMessage("Docker spawn: direct-exec of resolved docker binary").All() |
| 49 | + require.Len(t, entries, 1, "direct-exec must log exactly one observable spawn-decision line") |
| 50 | + fields := entries[0].ContextMap() |
| 51 | + assert.Equal(t, bundleDocker, fields["docker_path"], "spawn log must record the resolved absolute docker path") |
| 52 | + assert.Equal(t, false, fields["shell_wrapped"]) |
| 53 | +} |
| 54 | + |
| 55 | +// TestSpawnDecisionIsObservable_ShellWrapFallback asserts the fallback branch is |
| 56 | +// equally observable and flags whether docker even resolved — the one path that |
| 57 | +// can yield #696's `command not found: docker`. |
| 58 | +func TestSpawnDecisionIsObservable_ShellWrapFallback(t *testing.T) { |
| 59 | + orig := resolveDockerBinary |
| 60 | + t.Cleanup(func() { resolveDockerBinary = orig }) |
| 61 | + resolveDockerBinary = func(_ *zap.Logger) (string, error) { |
| 62 | + return "", fmt.Errorf("docker not found") |
| 63 | + } |
| 64 | + |
| 65 | + c, recorded := newObservedIsolatedClient(t) |
| 66 | + _, _, shellWrapped := c.setupDockerIsolation(c.config.Command, c.config.Args) |
| 67 | + require.True(t, shellWrapped) |
| 68 | + |
| 69 | + entries := recorded.FilterMessage("Docker spawn: login-shell wrap fallback").All() |
| 70 | + require.Len(t, entries, 1, "shell-wrap fallback must log exactly one observable spawn-decision line") |
| 71 | + fields := entries[0].ContextMap() |
| 72 | + assert.Equal(t, true, fields["shell_wrapped"]) |
| 73 | + assert.Equal(t, false, fields["docker_resolved"], "unresolved docker must be flagged in the spawn log") |
| 74 | + assert.Equal(t, cmdDocker, fields["docker_command"], "fallback with no resolution wraps bare 'docker'") |
| 75 | +} |
| 76 | + |
| 77 | +// These tests close the integration gap behind GitHub #696: the existing |
| 78 | +// connection_docker_test.go suite STUBS resolveDockerBinary, so it proves the |
| 79 | +// gating logic in isolation but never exercises the REAL |
| 80 | +// shellwrap.ResolveDockerPath -> setupDockerIsolation chain. The #696 field |
| 81 | +// failure ("docker installed via Docker Desktop but not on the spawn PATH" |
| 82 | +// still spawns bare `docker` and dies with `command not found: docker`) can |
| 83 | +// only be reproduced — or refuted — by driving the real resolver end-to-end. |
| 84 | +// |
| 85 | +// useRealDockerResolver pins resolveDockerBinary to the production resolver |
| 86 | +// (un-stubbing any leakage from a sibling test) and clears the process-wide |
| 87 | +// docker-path cache so resolution starts from a clean slate. |
| 88 | +func useRealDockerResolver(t *testing.T) { |
| 89 | + t.Helper() |
| 90 | + orig := resolveDockerBinary |
| 91 | + resolveDockerBinary = shellwrap.ResolveDockerPath |
| 92 | + shellwrap.ResetDockerPathCacheForTest() |
| 93 | + t.Cleanup(func() { |
| 94 | + resolveDockerBinary = orig |
| 95 | + shellwrap.ResetDockerPathCacheForTest() |
| 96 | + }) |
| 97 | +} |
| 98 | + |
| 99 | +// TestIntegration_DockerOnlyAtBundlePath_DirectExecs is the faithful #696 |
| 100 | +// reproduction: on macOS, Docker Desktop's CLI lives only inside the app bundle |
| 101 | +// (/Applications/Docker.app/Contents/Resources/bin/docker) and is absent from |
| 102 | +// the spawn PATH. The real resolver must discover it via the well-known-path |
| 103 | +// probe, and setupDockerIsolation must DIRECT-EXEC that absolute path — never |
| 104 | +// fall back to a `$SHELL -l -c "docker run …"` wrap with bare `docker` (which is |
| 105 | +// what the login shell cannot resolve and what the field report shows failing). |
| 106 | +func TestIntegration_DockerOnlyAtBundlePath_DirectExecs(t *testing.T) { |
| 107 | + if runtime.GOOS == osWindows { |
| 108 | + t.Skip("well-known bundle probe + login-shell fallback are unix-only") |
| 109 | + } |
| 110 | + useRealDockerResolver(t) |
| 111 | + forceDockerDaemonEnvGOOS(t, osDarwin) // matches the affected hosts |
| 112 | + |
| 113 | + // Docker exists ONLY at a "bundle" path, off the spawn PATH. |
| 114 | + bundleDocker := writeFakeDockerExecutable(t) |
| 115 | + restore := shellwrap.SetWellKnownDockerPathsForTest(func() []string { return []string{bundleDocker} }) |
| 116 | + t.Cleanup(restore) |
| 117 | + |
| 118 | + // Spawn PATH excludes the bundle dir (the #696 condition) and the login |
| 119 | + // shell can't find docker either, so the well-known probe is the ONLY way to |
| 120 | + // resolve it. |
| 121 | + t.Setenv("PATH", t.TempDir()) |
| 122 | + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") |
| 123 | + |
| 124 | + c := newIsolatedTestClient() |
| 125 | + cmd, args, shellWrapped := c.setupDockerIsolation(c.config.Command, c.config.Args) |
| 126 | + |
| 127 | + require.False(t, shellWrapped, |
| 128 | + "#696: docker resolved at the bundle path MUST be direct-exec'd, not shell-wrapped with bare docker") |
| 129 | + assert.Equal(t, bundleDocker, cmd, |
| 130 | + "#696: spawn must exec the resolved absolute bundle path, got %q", cmd) |
| 131 | + assert.NotEqual(t, cmdDocker, cmd, "#696: spawn must not degrade to bare 'docker'") |
| 132 | + require.True(t, filepath.IsAbs(cmd), "spawn command must be absolute, got %q", cmd) |
| 133 | + require.NotEmpty(t, args) |
| 134 | + assert.Equal(t, cmdRun, args[0], "args must be raw argv (first token 'run'), got %v", args) |
| 135 | + for _, a := range args { |
| 136 | + assert.NotContains(t, a, " run ", "args must be raw argv tokens, not a shell -c string: %v", args) |
| 137 | + } |
| 138 | +} |
| 139 | + |
| 140 | +// TestIntegration_DockerOnPath_DirectExecs covers the other real resolution |
| 141 | +// leg: when docker IS on the spawn PATH, exec.LookPath resolves it to an |
| 142 | +// absolute path and the spawn direct-execs it. |
| 143 | +func TestIntegration_DockerOnPath_DirectExecs(t *testing.T) { |
| 144 | + if runtime.GOOS == osWindows { |
| 145 | + t.Skip("unix fake-binary fixture") |
| 146 | + } |
| 147 | + useRealDockerResolver(t) |
| 148 | + forceDockerDaemonEnvGOOS(t, osDarwin) |
| 149 | + |
| 150 | + pathDocker := writeFakeDockerExecutable(t) |
| 151 | + // Put the fake docker's dir on PATH so exec.LookPath finds it first. |
| 152 | + t.Setenv("PATH", filepath.Dir(pathDocker)) |
| 153 | + // No well-known override needed; LookPath should win before the probe. |
| 154 | + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") |
| 155 | + |
| 156 | + c := newIsolatedTestClient() |
| 157 | + cmd, args, shellWrapped := c.setupDockerIsolation(c.config.Command, c.config.Args) |
| 158 | + |
| 159 | + require.False(t, shellWrapped, "docker on PATH must resolve to an absolute path and direct-exec") |
| 160 | + assert.Equal(t, pathDocker, cmd, "spawn must exec the LookPath-resolved absolute path, got %q", cmd) |
| 161 | + require.NotEmpty(t, args) |
| 162 | + assert.Equal(t, cmdRun, args[0]) |
| 163 | +} |
| 164 | + |
| 165 | +// TestIntegration_DockerUnresolvable_FallsBackToBareDocker proves the worst |
| 166 | +// case (#696 absent): when docker is nowhere — not on PATH, not at a well-known |
| 167 | +// path, not in the login shell — the spawn falls back to a login-shell wrap of |
| 168 | +// bare `docker`. This is the ONLY path that should ever produce the field |
| 169 | +// failure's `command not found: docker`, and it requires docker to be genuinely |
| 170 | +// absent (not merely off PATH). |
| 171 | +func TestIntegration_DockerUnresolvable_FallsBackToBareDocker(t *testing.T) { |
| 172 | + if runtime.GOOS == osWindows { |
| 173 | + t.Skip("unix login-shell fallback") |
| 174 | + } |
| 175 | + useRealDockerResolver(t) |
| 176 | + forceDockerDaemonEnvGOOS(t, osDarwin) |
| 177 | + |
| 178 | + // No docker anywhere: empty PATH, well-known list points at nothing, login |
| 179 | + // shell sabotaged so its lookup fails too. |
| 180 | + restore := shellwrap.SetWellKnownDockerPathsForTest(func() []string { return nil }) |
| 181 | + t.Cleanup(restore) |
| 182 | + t.Setenv("PATH", t.TempDir()) |
| 183 | + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") |
| 184 | + |
| 185 | + c := newIsolatedTestClient() |
| 186 | + _, shellArgs, shellWrapped := c.setupDockerIsolation(c.config.Command, c.config.Args) |
| 187 | + |
| 188 | + require.True(t, shellWrapped, "unresolvable docker must fall back to the login-shell wrap") |
| 189 | + require.NotEmpty(t, shellArgs) |
| 190 | + cmdStr := shellArgs[len(shellArgs)-1] |
| 191 | + assert.True(t, strings.HasPrefix(cmdStr, "docker run"), |
| 192 | + "only a genuinely-absent docker should degrade to bare 'docker', got %q", cmdStr) |
| 193 | +} |
| 194 | + |
| 195 | +// TestIntegration_StatusAndSpawnResolverDoNotDiverge guards the invariant the |
| 196 | +// #696 v0.39.1 report worried about ("detection discovers docker_path but the |
| 197 | +// spawn doesn't use it"). docker_status.docker_path (server.dockerPathResolver) |
| 198 | +// and the spawn (core.resolveDockerBinary) both call shellwrap.ResolveDockerPath |
| 199 | +// and share ONE process-wide cache, so for a given environment they MUST agree. |
| 200 | +// If a future refactor gives the status panel its own resolver, this test |
| 201 | +// fails — surfacing exactly the divergence the field reports feared. |
| 202 | +func TestIntegration_StatusAndSpawnResolverDoNotDiverge(t *testing.T) { |
| 203 | + if runtime.GOOS == osWindows { |
| 204 | + t.Skip("unix fake-binary fixture") |
| 205 | + } |
| 206 | + useRealDockerResolver(t) |
| 207 | + |
| 208 | + bundleDocker := writeFakeDockerExecutable(t) |
| 209 | + restore := shellwrap.SetWellKnownDockerPathsForTest(func() []string { return []string{bundleDocker} }) |
| 210 | + t.Cleanup(restore) |
| 211 | + t.Setenv("PATH", t.TempDir()) |
| 212 | + t.Setenv("SHELL", "/nonexistent/shell-must-not-be-invoked") |
| 213 | + |
| 214 | + // Spawn side (the value setupDockerIsolation would exec). |
| 215 | + spawnPath, err := resolveDockerBinary(zap.NewNop()) |
| 216 | + require.NoError(t, err) |
| 217 | + |
| 218 | + // Status side reports the SAME resolution branch + path from the shared cache. |
| 219 | + source := shellwrap.ResolveDockerSource(zap.NewNop()) |
| 220 | + statusPath, err := shellwrap.ResolveDockerPath(zap.NewNop()) |
| 221 | + require.NoError(t, err) |
| 222 | + |
| 223 | + assert.Equal(t, bundleDocker, spawnPath, "spawn must resolve the bundle path") |
| 224 | + assert.Equal(t, spawnPath, statusPath, "status and spawn must resolve to the SAME docker path (no divergence)") |
| 225 | + assert.Equal(t, shellwrap.DockerSourceBundled, source, |
| 226 | + "status must report the bundled source matching the spawn resolution") |
| 227 | + assert.True(t, isDirectExecutable(statusPath), |
| 228 | + "the path docker_status reports must itself satisfy the direct-exec contract") |
| 229 | +} |
0 commit comments