//go:build docker_integration // Conformance test for the Docker backend against a real daemon. // // It drives the same public surface as the E2B-protocol conformance suite // (session-scoped script execution, shell commands, attachment staging, // artifact listing, timeouts, teardown), because the point of the docker // backend is to be indistinguishable from a remote one at that level. Anything // asserted here that the E2B suite also asserts is deliberate duplication: a // backend that passes one and fails the other is not interchangeable. // // Run with a reachable daemon and the standard sandbox image: // // docker build -f docker/Dockerfile.sandbox -t wechatopenai/weknora-sandbox:dev . // DOCKER_INTEGRATION_IMAGE=wechatopenai/weknora-sandbox:dev \ // go test -tags=docker_integration ./internal/sandbox \ // -run '^TestDocker.*Integration' -count=1 -v -timeout=15m package sandbox import ( "bytes" "context" "fmt" "os" "path" "strings" "sync" "testing" "time" "github.com/moby/moby/api/types/container" "github.com/moby/moby/client" "github.com/Tencent/WeKnora/internal/types" ) const dockerIntegrationTenantID = 1 func dockerIntegrationConfig(t *testing.T) *Config { t.Helper() image := strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_IMAGE")) if image == "" { t.Skip("DOCKER_INTEGRATION_IMAGE is required for the docker conformance suite") } cfg := DefaultConfig() cfg.Type = SandboxTypeDocker cfg.DockerImage = image cfg.DockerHost = strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")) cfg.DefaultTimeout = 2 * time.Minute applyDockerRuntimeDefaults(cfg) return cfg } func newDockerIntegrationManager(t *testing.T, cfg *Config) *SessionBoundManager { t.Helper() client, err := NewDockerRemoteClient(cfg) if err != nil { t.Fatalf("build docker client: %v", err) } // Integration tests clean up their own sessions. Do not reclaim unrelated // idle containers when using a shared developer daemon. client.sweeper = nil probeCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() if err := client.Health(probeCtx); err != nil { t.Skipf("docker daemon unreachable: %v", err) } manager, err := NewSessionBoundManager(SessionBoundManagerConfig{ Config: cfg, Client: client, Store: NewMemorySessionSandboxBindingStore(), Checker: PermissiveSessionExistenceChecker{}, ConfigID: "docker-conformance", SkipHealthProbe: true, }) if err != nil { t.Fatalf("NewSessionBoundManager: %v", err) } return manager } func TestDockerBackendConformanceIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 12*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-conformance-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 2*time.Minute, ) defer cleanupCancel() if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { t.Errorf("DestroySession: %v", err) } }) counterPath := path.Join(SessionOutputRoot, "counter.txt") t.Run("SessionScopedStatePersistsAcrossExecutions", func(t *testing.T) { first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(` with open(%q, 'w') as handle: handle.write('1') print('wrote counter') `, counterPath)) if !first.IsSuccess() { t.Fatalf("first execution failed: %#v", first) } second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(` with open(%q) as handle: print('counter=' + handle.read()) `, counterPath)) if !second.IsSuccess() || !strings.Contains(second.Stdout, "counter=1") { t.Fatalf("session state did not persist: %#v", second) } }) t.Run("InstalledPackagesSurviveBetweenExecutions", func(t *testing.T) { install := runDockerScript(t, ctx, manager, sessionID, ` import subprocess print(subprocess.run( ['pip', 'install', '--quiet', '--no-cache-dir', '--user', 'cowsay==6.1'], capture_output=True, text=True).returncode) `) if !install.IsSuccess() { t.Fatalf("package install failed: %#v", install) } use := runDockerScript(t, ctx, manager, sessionID, ` import cowsay print('cowsay-ok') `) if !use.IsSuccess() || !strings.Contains(use.Stdout, "cowsay-ok") { t.Fatalf("installed package did not survive: %#v", use) } }) t.Run("ShellExecSharesTheSessionSandbox", func(t *testing.T) { executor := manager.SessionShellExecutor() if executor == nil { t.Fatal("session shell executor is unavailable on a healthy docker backend") } result, err := executor.ExecShellCommand( ctx, sessionID, "cat "+counterPath, SessionWorkspaceRoot, time.Minute, nil, ) if err != nil { t.Fatalf("ExecShellCommand: %v", err) } if !result.IsSuccess() || !strings.Contains(result.Stdout, "1") { t.Fatalf("shell command did not observe the session sandbox: %#v", result) } }) t.Run("AttachmentStagingAndArtifactCollection", func(t *testing.T) { files := manager.SessionFileStore() if files == nil { t.Fatal("session file store is unavailable on a healthy docker backend") } inputPath := path.Join(SessionInputRoot, "attachment.txt") payload := []byte("attachment payload\n") if err := files.WriteSessionInputFile(ctx, sessionID, inputPath, payload); err != nil { t.Fatalf("WriteSessionInputFile: %v", err) } content, err := files.ReadSessionFile(ctx, sessionID, inputPath) if err != nil { t.Fatalf("ReadSessionFile: %v", err) } if !bytes.Equal(content, payload) { t.Fatalf("staged attachment mismatch: got=%q want=%q", content, payload) } result := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(` import os target = os.path.join(os.environ['%s'], 'report.txt') with open(target, 'w') as handle: handle.write('artifact body') print('artifact written') `, skillOutputEnvVar)) if !result.IsSuccess() { t.Fatalf("artifact-producing execution failed: %#v", result) } entries, err := files.ListSessionFiles(ctx, sessionID, SessionOutputRoot) if err != nil { t.Fatalf("ListSessionFiles: %v", err) } found := false for _, entry := range entries { if entry.Name == "report.txt" { found = true } } if !found { t.Fatalf("artifact directory did not contain report.txt: %#v", entries) } if err := files.RemoveSessionInputPath(ctx, sessionID, inputPath); err != nil { t.Fatalf("RemoveSessionInputPath: %v", err) } }) t.Run("TimeoutIsReportedAsKilled", func(t *testing.T) { result := runDockerScriptWithTimeout(t, ctx, manager, sessionID, ` import time time.sleep(60) `, 5*time.Second) if !result.Killed { t.Fatalf("expected a killed result for an over-running script: %#v", result) } }) // The daemon does not stop a process when the client goes away, so the // only proof that a timeout means anything is that nothing is left running. t.Run("TimeoutActuallyStopsTheProcess", func(t *testing.T) { executor := manager.SessionShellExecutor() _, err := executor.ExecShellCommand( ctx, sessionID, "sleep 120", SessionWorkspaceRoot, 3*time.Second, nil, ) if err != nil { t.Fatalf("ExecShellCommand: %v", err) } time.Sleep(2 * time.Second) // Count processes whose command line is exactly "sleep 120", which the // probe's own shell cannot match. const probe = `n=0; for p in /proc/[0-9]*; do ` + `cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); ` + `case "$cmd" in "sleep 120 ") n=$((n+1));; esac; done; echo "$n"` survivors, err := executor.ExecShellCommand( ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil, ) if err != nil { t.Fatalf("survivor probe: %v", err) } if got := strings.TrimSpace(survivors.Stdout); got != "0" { t.Fatalf("timeout left %s 'sleep 120' process(es) running: %#v", got, survivors) } }) // The entrypoint is a plain `sleep`, which never calls wait(). A background // process that outlives the exec which started it is reparented to PID 1, // so without tini in front of it every such process becomes a permanent Z // entry and a long session eventually exhausts PidsLimit. Measured on a // real daemon: three orphans leave three zombies without HostConfig.Init // and none with it. t.Run("OrphanedProcessesAreReaped", func(t *testing.T) { executor := manager.SessionShellExecutor() for i := 0; i < 3; i++ { if _, err := executor.ExecShellCommand( ctx, sessionID, "(sleep 0.2 &) ; exit 0", SessionWorkspaceRoot, 30*time.Second, nil, ); err != nil { t.Fatalf("spawn orphan %d: %v", i, err) } } time.Sleep(2 * time.Second) const probe = `n=0; for p in /proc/[0-9]*; do ` + `s=$(awk '{print $3}' "$p/stat" 2>/dev/null); ` + `[ "$s" = "Z" ] && n=$((n+1)); done; echo "$n"` zombies, err := executor.ExecShellCommand( ctx, sessionID, probe, SessionWorkspaceRoot, 30*time.Second, nil, ) if err != nil { t.Fatalf("zombie probe: %v", err) } if got := strings.TrimSpace(zombies.Stdout); got != "0" { t.Fatalf("PID 1 left %s zombie(s) unreaped: %#v", got, zombies) } }) } // The idle sweeper reclaims a container by the mtime of its activity marker, // and skill scripts run as the unprivileged sandbox user. A session that only // ever runs scripts must still count as active, or it gets deleted underneath // the user who is actively using it. func TestDockerBackendScriptExecutionRefreshesActivityMarkerIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 5*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-activity-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), time.Minute, ) defer cleanupCancel() _ = manager.DestroySession(cleanupCtx, sessionID) }) first := runDockerScript(t, ctx, manager, sessionID, `print('one')`) if !first.IsSuccess() { t.Fatalf("first execution failed: %#v", first) } client, err := NewDockerRemoteClient(cfg) if err != nil { t.Fatalf("build docker client: %v", err) } summaries, err := client.List(ctx, RemoteListFilter{ Metadata: map[string]string{remoteMetadataSessionID: sessionID}, }) if err != nil || len(summaries) != 1 { t.Fatalf("expected exactly one container: %v %#v", err, summaries) } handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID}) if err != nil { t.Fatalf("Connect: %v", err) } // The container entrypoint makes the marker world-writable on purpose. // Leaving it to whatever umask the daemon happens to run with would work // on a host with umask 000 and silently stop tracking script executions on // a host with umask 022. if mode := dockerActivityMarkerStat(t, ctx, summaries[0].ID).Mode.Perm(); mode != 0o666 { t.Fatalf("activity marker is %v, want 0666 so both root and %s can refresh it", mode, DefaultSandboxExecUser) } before := dockerActivityMarkerMTime(t, ctx, summaries[0].ID) // Exec directly as the unprivileged account: this asserts that the account // running user code refreshes the marker itself, rather than relying on // some other step happening to touch it first. The marker has one-second // resolution on most filesystems. time.Sleep(2 * time.Second) result, err := client.Exec(ctx, handle, RemoteExecRequest{ Command: "echo", Args: []string{"as-sandbox-user"}, User: DefaultSandboxExecUser, Timeout: 30 * time.Second, }) if err != nil || result.ExitCode != 0 { t.Fatalf("exec as %s failed: %v %#v", DefaultSandboxExecUser, err, result) } after := dockerActivityMarkerMTime(t, ctx, summaries[0].ID) if !after.After(before) { t.Fatalf("an exec as %s did not refresh the activity marker: before=%s after=%s", DefaultSandboxExecUser, before, after) } } func dockerActivityMarkerMTime(t *testing.T, ctx context.Context, containerID string) time.Time { t.Helper() return dockerActivityMarkerStat(t, ctx, containerID).Mtime } func dockerActivityMarkerStat( t *testing.T, ctx context.Context, containerID string, ) container.PathStat { t.Helper() api, err := sharedDockerEngineClients.get(dockerEndpoint{ Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")), Timeout: DefaultDockerHTTPTimeout, }) if err != nil { t.Fatalf("docker client: %v", err) } stat, err := api.ContainerStatPath(ctx, containerID, client.ContainerStatPathOptions{Path: dockerActivityMarker}) if err != nil { t.Fatalf("stat activity marker: %v", err) } return stat.Stat } // A session must survive the container being stopped underneath it: the // filesystem is intact, so Connect restarts it rather than losing the state. func TestDockerBackendResumesStoppedContainerIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 5*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-resume-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), time.Minute, ) defer cleanupCancel() _ = manager.DestroySession(cleanupCtx, sessionID) }) marker := path.Join(SessionOutputRoot, "resume.txt") first := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(` with open(%q, 'w') as handle: handle.write('before-stop') print('ok') `, marker)) if !first.IsSuccess() { t.Fatalf("seed execution failed: %#v", first) } client, err := NewDockerRemoteClient(cfg) if err != nil { t.Fatalf("build docker client: %v", err) } summaries, err := client.List(ctx, RemoteListFilter{ Metadata: map[string]string{remoteMetadataSessionID: sessionID}, }) if err != nil || len(summaries) != 1 { t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries) } // Stop it the way a host reboot or an operator would. stopCtx, stopCancel := context.WithTimeout(ctx, time.Minute) defer stopCancel() if err := stopDockerContainerForTest(stopCtx, summaries[0].ID); err != nil { t.Fatalf("stop container: %v", err) } second := runDockerScript(t, ctx, manager, sessionID, fmt.Sprintf(` with open(%q) as handle: print('restored=' + handle.read()) `, marker)) if !second.IsSuccess() || !strings.Contains(second.Stdout, "restored=before-stop") { t.Fatalf("session did not resume with its filesystem: %#v", second) } } // A session owns /workspace, so it can replace its own artifact directory with // a symlink pointing anywhere in the container. chown and chmod follow // symlinks, so if the pre-execution bootstrap ran as root it would hand the // session ownership of the link's target — /etc here, which is enough to // rewrite passwd and give the sandbox account uid 0 on the next exec. // // Session-scoped containers are what make this reachable: the link planted by // one execution is still there when the next one runs the bootstrap. Under the // old one-shot `docker run --rm` the two never shared a filesystem. func TestDockerBackendArtifactBootstrapDoesNotFollowSymlinkIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 5*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-chown-escape-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), time.Minute, ) defer cleanupCancel() _ = manager.DestroySession(cleanupCtx, sessionID) }) if first := runDockerScript(t, ctx, manager, sessionID, `print('seed')`); !first.IsSuccess() { t.Fatalf("seed execution failed: %#v", first) } client, err := NewDockerRemoteClient(cfg) if err != nil { t.Fatalf("build docker client: %v", err) } summaries, err := client.List(ctx, RemoteListFilter{ Metadata: map[string]string{remoteMetadataSessionID: sessionID}, }) if err != nil || len(summaries) != 1 { t.Fatalf("expected exactly one container for the session: %v %#v", err, summaries) } handle, err := client.Connect(ctx, RemoteConnectRequest{SandboxID: summaries[0].ID}) if err != nil { t.Fatalf("Connect: %v", err) } ownerOfEtc := func() string { t.Helper() result, err := client.Exec(ctx, handle, RemoteExecRequest{ Command: "stat", Args: []string{"-c", "%U:%G", "/etc"}, User: DefaultSandboxExecUser, Timeout: 30 * time.Second, }) if err != nil || result.ExitCode != 0 { t.Fatalf("stat /etc failed: %v %#v", err, result) } return strings.TrimSpace(result.Stdout) } before := ownerOfEtc() if before != "root:root" { t.Fatalf("/etc should start out root-owned, got %q", before) } // Exactly what a model with shell_exec can do: it owns /workspace. plant, err := client.Exec(ctx, handle, RemoteExecRequest{ Shell: true, Command: fmt.Sprintf( "rm -rf %s && ln -s /etc %s", SessionOutputRoot, SessionOutputRoot, ), User: DefaultSandboxExecUser, Timeout: 30 * time.Second, }) if err != nil || plant.ExitCode != 0 { t.Fatalf("planting the symlink failed: %v %#v", err, plant) } // Any further execution runs the bootstrap against the planted path. _, err = manager.Execute(ctx, &ExecuteConfig{ Script: "conformance.py", ScriptContent: `print('after')`, SessionID: sessionID, Timeout: time.Minute, SkipValidation: true, Env: map[string]string{skillOutputEnvVar: SessionOutputRoot}, }) if err == nil || !strings.Contains(err.Error(), "symlink") { t.Fatalf("bootstrap must preserve and report the symlink before execution: %v", err) } if after := ownerOfEtc(); after != "root:root" { t.Fatalf("the artifact bootstrap chowned through the symlink: /etc is now %q, want root:root", after) } } // stopDockerContainerForTest stops a container behind the adapter's back, the // way a host reboot or an operator with a shell would. func stopDockerContainerForTest(ctx context.Context, id string) error { api, err := sharedDockerEngineClients.get(dockerEndpoint{ Host: strings.TrimSpace(os.Getenv("DOCKER_INTEGRATION_HOST")), Timeout: DefaultDockerHTTPTimeout, }) if err != nil { return err } grace := 5 _, err = api.ContainerStop(ctx, id, client.ContainerStopOptions{Timeout: &grace}) return err } func runDockerScript( t *testing.T, ctx context.Context, manager *SessionBoundManager, sessionID, source string, ) *ExecuteResult { t.Helper() return runDockerScriptWithTimeout(t, ctx, manager, sessionID, source, 3*time.Minute) } func runDockerScriptWithTimeout( t *testing.T, ctx context.Context, manager *SessionBoundManager, sessionID, source string, timeout time.Duration, ) *ExecuteResult { t.Helper() result, err := manager.Execute(ctx, &ExecuteConfig{ Script: "conformance.py", ScriptContent: source, SessionID: sessionID, Timeout: timeout, SkipValidation: true, Env: map[string]string{skillOutputEnvVar: SessionOutputRoot}, }) if err != nil { t.Fatalf("Execute: %v", err) } if result == nil { t.Fatal("Execute returned no result") } t.Logf("execute exit=%d killed=%v stdout=%q stderr=%q err=%q", result.ExitCode, result.Killed, result.Stdout, result.Stderr, result.Error) return result } func TestDockerSkillSnapshotIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) client, err := NewDockerRemoteClient(cfg) if err != nil { t.Fatalf("build docker client: %v", err) } probeCtx, cancelProbe := context.WithTimeout(context.Background(), 15*time.Second) defer cancelProbe() if err := client.Health(probeCtx); err != nil { t.Skipf("docker daemon unreachable: %v", err) } if !client.Capabilities().SupportsSnapshots { t.Fatal("docker backend must advertise snapshot support") } ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 5*time.Minute, ) defer cancel() builder, err := client.Create(ctx, RemoteCreateRequest{ TemplateID: cfg.DockerImage, Metadata: map[string]string{"weknora.test": "skill-snapshot"}, }) if err != nil { t.Fatalf("Create builder: %v", err) } t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute) defer cleanupCancel() _ = client.Delete(cleanupCtx, builder.ID()) }) skillDir := SkillsImageRoot + "/itest" skillFile := skillDir + "/SKILL.md" seed, err := client.Exec(ctx, builder, RemoteExecRequest{ Command: fmt.Sprintf( "mkdir -p %s && echo skill-ok > %s && chown %s:%s %s %s", skillDir, skillFile, DefaultSandboxExecUser, DefaultSandboxExecUser, SkillsImageRoot, skillDir, ), Shell: true, User: "root", Timeout: time.Minute, }) if err != nil || seed == nil || seed.ExitCode != 0 { t.Fatalf("seed skill tree: err=%v result=%#v", err, seed) } ref, err := client.CreateSnapshot(ctx, builder.ID(), "weknora-sk-itest-g1") if err != nil { t.Fatalf("CreateSnapshot: %v", err) } if ref.ID == "" { t.Fatal("CreateSnapshot returned an empty id") } t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute) defer cleanupCancel() _ = client.DeleteSnapshot(cleanupCtx, ref.ID) }) if err := client.Delete(ctx, builder.ID()); err != nil { t.Fatalf("Delete builder: %v", err) } booted, err := client.Create(ctx, RemoteCreateRequest{ TemplateID: ref.ID, Metadata: map[string]string{"weknora.test": "skill-snapshot-boot"}, }) if err != nil { t.Fatalf("Create from snapshot: %v", err) } t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), time.Minute) defer cleanupCancel() _ = client.Delete(cleanupCtx, booted.ID()) }) check, err := client.Exec(ctx, booted, RemoteExecRequest{ Command: "cat " + skillFile, Shell: true, User: DefaultSandboxExecUser, Timeout: 30 * time.Second, }) if err != nil || check == nil || check.ExitCode != 0 || !strings.Contains(check.Stdout, "skill-ok") { t.Fatalf("snapshot did not carry the skill: err=%v result=%#v", err, check) } listed, err := client.ListSnapshots(ctx, "") if err != nil { t.Fatalf("ListSnapshots: %v", err) } found := false for _, item := range listed { if item.ID == ref.ID { found = true break } } if !found { t.Fatalf("ListSnapshots missing %s: %#v", ref.ID, listed) } templates, err := client.ListTemplates(ctx) if err != nil { t.Fatalf("ListTemplates: %v", err) } for _, item := range templates { if dockerCanonicalSnapshotID(item.ID) == ref.ID { t.Fatalf("skill snapshot %s leaked into the template catalog", ref.ID) } } } // terminalCapture drains a PTY session in the background so assertions can wait // for output that arrived before the check, which a direct receive would have // consumed. type terminalCapture struct { mu sync.Mutex buf bytes.Buffer done chan struct{} } func captureTerminal(session RemoteTerminalSession) *terminalCapture { capture := &terminalCapture{done: make(chan struct{})} go func() { defer close(capture.done) for event := range session.Output() { if event.Err != nil { return } capture.mu.Lock() capture.buf.Write(event.Data) capture.mu.Unlock() } }() return capture } func (c *terminalCapture) String() string { c.mu.Lock() defer c.mu.Unlock() return c.buf.String() } func (c *terminalCapture) waitFor(t *testing.T, want string, timeout time.Duration) { t.Helper() deadline := time.Now().Add(timeout) for time.Now().Before(deadline) { if strings.Contains(c.String(), want) { return } time.Sleep(50 * time.Millisecond) } t.Fatalf("terminal output never contained %q; got: %q", want, c.String()) } func (c *terminalCapture) assertNever(t *testing.T, unwanted string, window time.Duration) { t.Helper() deadline := time.Now().Add(window) for time.Now().Before(deadline) { if strings.Contains(c.String(), unwanted) { t.Fatalf("terminal output unexpectedly contained %q: %q", unwanted, c.String()) } time.Sleep(50 * time.Millisecond) } } // TestDockerBackendTerminalIntegration exercises the interactive PTY against a // real daemon and the standard image: live output, window resize, and Ctrl-C. func TestDockerBackendTerminalIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 6*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-terminal-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 2*time.Minute, ) defer cleanupCancel() if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { t.Errorf("DestroySession: %v", err) } }) // Provision the session sandbox the way a chat turn would, then open the // PTY on it. executor := manager.SessionShellExecutor() if executor == nil { t.Fatal("session shell executor is unavailable on a healthy docker backend") } if _, err := executor.ExecShellCommand( ctx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, ); err != nil { t.Fatalf("provision session sandbox: %v", err) } terminal := manager.SessionTerminalManager() if terminal == nil { t.Fatal("docker backend must advertise the terminal capability") } session, err := manager.OpenSessionTerminal(ctx, sessionID, RemoteTerminalOptions{Cols: 100, Rows: 40}) if err != nil { t.Fatalf("OpenSessionTerminal: %v", err) } t.Cleanup(func() { _ = session.Close() }) capture := captureTerminal(session) // Live output: the computed value 42 does not appear in the typed command's // own echo, so matching it proves the shell actually ran the line. if err := session.Write(ctx, []byte("echo LIVE=$((6*7))\n")); err != nil { t.Fatalf("write: %v", err) } capture.waitFor(t, "LIVE=42", 30*time.Second) // Resize: stty reports the geometry the PTY was resized to. The target // differs from the 100x40 the PTY opened at, so a match proves ExecResize // took effect rather than echoing the create-time ConsoleSize. if err := session.Resize(ctx, 120, 30); err != nil { t.Fatalf("resize: %v", err) } if err := session.Write(ctx, []byte("stty size\n")); err != nil { t.Fatalf("write: %v", err) } capture.waitFor(t, "30 120", 30*time.Second) // The adapter's interactive defaults reach the shell (the daemon alone // would leave TERM=xterm). if err := session.Write(ctx, []byte("echo ENV=$TERM/$LC_ALL\n")); err != nil { t.Fatalf("write: %v", err) } capture.waitFor(t, "ENV=xterm-256color/C.UTF-8", 30*time.Second) // Interrupt: Ctrl-C cancels the sleeping command, and its sentinel never // runs. The prompt returning is proven by the follow-up echo completing. if err := session.Write(ctx, []byte("sleep 60; echo SLOW=$((2+2))\n")); err != nil { t.Fatalf("write: %v", err) } time.Sleep(500 * time.Millisecond) if err := session.Write(ctx, []byte{0x03}); err != nil { t.Fatalf("interrupt: %v", err) } if err := session.Write(ctx, []byte("echo AFTER=$((5+5))\n")); err != nil { t.Fatalf("write: %v", err) } capture.waitFor(t, "AFTER=10", 20*time.Second) capture.assertNever(t, "SLOW=4", 3*time.Second) } // Closing a live Docker terminal must terminate the shell. The daemon keeps an // exec (and its foreground jobs) alive when the hijacked connection goes away, // so a bare disconnect would strand the process until the container is swept. func TestDockerBackendTerminalCloseTerminatesShellIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) ctx, cancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 6*time.Minute, ) defer cancel() sessionID := fmt.Sprintf("docker-terminal-close-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 2*time.Minute, ) defer cleanupCancel() if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { t.Errorf("DestroySession: %v", err) } }) executor := manager.SessionShellExecutor() if executor == nil { t.Fatal("session shell executor is unavailable on a healthy docker backend") } if _, err := executor.ExecShellCommand( ctx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, ); err != nil { t.Fatalf("provision session sandbox: %v", err) } session, err := manager.OpenSessionTerminal(ctx, sessionID, RemoteTerminalOptions{}) if err != nil { t.Fatalf("OpenSessionTerminal: %v", err) } go func() { for range session.Output() { } }() // Record the shell PID and start a long foreground job with a unique // marker so the probe can find the job without matching itself. if err := session.Write(ctx, []byte("echo $$ > /tmp/weknora-close.pid\n")); err != nil { t.Fatalf("write pid: %v", err) } // A job the user detached on purpose must outlive the hangup, as it would // when any real terminal closes. if err := session.Write(ctx, []byte("nohup sleep 3619 >/dev/null 2>&1 &\n")); err != nil { t.Fatalf("write nohup job: %v", err) } if err := session.Write(ctx, []byte("sleep 3611\n")); err != nil { t.Fatalf("write job: %v", err) } // Positive control: the shell and its job must both be visible before the // close, or a broken probe would read as a pass. var shellPID string for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); { shellPID = strings.TrimSpace(terminalProbeOutput( t, ctx, executor, sessionID, "cat /tmp/weknora-close.pid 2>/dev/null || true")) if shellPID != "" && terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { break } time.Sleep(300 * time.Millisecond) } if shellPID == "" { t.Fatal("terminal shell never recorded its PID") } if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { t.Fatal("positive control failed: foreground job not visible before close") } if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3619") { t.Fatal("positive control failed: nohup job not visible before close") } if err := session.Close(); err != nil { t.Fatalf("Close: %v", err) } // The hangup runs as a detached exec, so it may land just after Close // returns; poll until both the shell and its job are gone. for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); { alive := strings.Contains(terminalProbeOutput(t, ctx, executor, sessionID, "if [ -d /proc/"+shellPID+" ]; then echo ALIVE; else echo DEAD; fi"), "ALIVE") if !alive && !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3611") { // Past the script's SIGKILL pass too, so a survivor is not just // a job the second pass has yet to reach. time.Sleep(3 * time.Second) if !terminalProbeJobAlive(t, ctx, executor, sessionID, "sleep 3619") { t.Fatal("Close killed a nohup'd job; a terminal hangup must spare it") } return } time.Sleep(500 * time.Millisecond) } t.Fatalf("Close left the shell (pid %s) and/or its foreground job running", shellPID) } // Cancelling the caller's context must terminate the shell just like Close. The // adapter's stream never observes the context on its own — the pump reads the // hijacked connection and the moby hijack stops watching the context once // upgraded — so without the lifetime watcher a cancelled context would leak the // shell and (via the detached TTL refresh) pin the container forever. func TestDockerBackendTerminalContextCancelTerminatesShellIntegration(t *testing.T) { cfg := dockerIntegrationConfig(t) manager := newDockerIntegrationManager(t, cfg) probeCtx, cancelProbe := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 6*time.Minute, ) defer cancelProbe() sessionID := fmt.Sprintf("docker-terminal-cancel-%d", time.Now().UnixNano()) t.Cleanup(func() { cleanupCtx, cleanupCancel := context.WithTimeout( types.WithSandboxTenantID(context.Background(), dockerIntegrationTenantID), 2*time.Minute, ) defer cleanupCancel() if err := manager.DestroySession(cleanupCtx, sessionID); err != nil { t.Errorf("DestroySession: %v", err) } }) executor := manager.SessionShellExecutor() if executor == nil { t.Fatal("session shell executor is unavailable on a healthy docker backend") } if _, err := executor.ExecShellCommand( probeCtx, sessionID, "true", SessionWorkspaceRoot, time.Minute, nil, ); err != nil { t.Fatalf("provision session sandbox: %v", err) } // The session ctx is a child of probeCtx so the probes below keep a live // context after we cancel only the session's. sessionCtx, cancelSession := context.WithCancel(probeCtx) defer cancelSession() session, err := manager.OpenSessionTerminal(sessionCtx, sessionID, RemoteTerminalOptions{}) if err != nil { t.Fatalf("OpenSessionTerminal: %v", err) } go func() { for range session.Output() { } }() if err := session.Write(sessionCtx, []byte("echo $$ > /tmp/weknora-cancel.pid\n")); err != nil { t.Fatalf("write pid: %v", err) } if err := session.Write(sessionCtx, []byte("sleep 3613\n")); err != nil { t.Fatalf("write job: %v", err) } var shellPID string for deadline := time.Now().Add(15 * time.Second); time.Now().Before(deadline); { shellPID = strings.TrimSpace(terminalProbeOutput( t, probeCtx, executor, sessionID, "cat /tmp/weknora-cancel.pid 2>/dev/null || true")) if shellPID != "" && terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { break } time.Sleep(300 * time.Millisecond) } if shellPID == "" { t.Fatal("terminal shell never recorded its PID") } if !terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { t.Fatal("positive control failed: foreground job not visible before cancel") } // Cancel only. No Close(). cancelSession() for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); { alive := strings.Contains(terminalProbeOutput(t, probeCtx, executor, sessionID, "if [ -d /proc/"+shellPID+" ]; then echo ALIVE; else echo DEAD; fi"), "ALIVE") if !alive && !terminalProbeJobAlive(t, probeCtx, executor, sessionID, "sleep 3613") { return } time.Sleep(500 * time.Millisecond) } t.Fatalf("cancelling the context left the shell (pid %s) and/or its job running", shellPID) } func terminalProbeOutput( t *testing.T, ctx context.Context, executor SessionShellExecutor, sessionID, script string, ) string { t.Helper() result, err := executor.ExecShellCommand( ctx, sessionID, script, SessionWorkspaceRoot, 30*time.Second, nil) if err != nil { t.Fatalf("probe: %v", err) } return result.Stdout } // terminalProbeJobAlive reports whether the foreground job (jobCmd, e.g. // "sleep 3611") is still running. The pattern is anchored to the start of the // command line so the probe's own shell (whose argv contains the pattern text) // never matches itself. func terminalProbeJobAlive( t *testing.T, ctx context.Context, executor SessionShellExecutor, sessionID, jobCmd string, ) bool { t.Helper() out := terminalProbeOutput(t, ctx, executor, sessionID, `n=0; for p in /proc/[0-9]*; do cmd=$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null); case "$cmd" in "`+jobCmd+` "*) n=$((n+1));; esac; done; echo $n`) return strings.TrimSpace(out) != "0" }