diff --git a/docs/SANDBOX.md b/docs/SANDBOX.md index 6afe9f63c..a5e7a4d44 100644 --- a/docs/SANDBOX.md +++ b/docs/SANDBOX.md @@ -70,6 +70,28 @@ ARTEX_SANDBOX=off ## Security Hardening Notes +### Worker cleanup after execution errors + +Command timeout, cancellation or a broken execution stream removes the worker +container that ran the command. The runner also removes it when Docker cannot +confirm that the exec has finished. This terminates detached children and **all +other concurrent commands and background services in that task**. The next exec +recreates the worker; the task's `/workspace` directory survives. Successful +commands keep their worker and may leave intentional background services running. + +Cleanup uses the captured container ID, so a delayed completion cannot remove a +replacement worker or another task's worker. Failed removal returns an error and +keeps the worker tracked for retry. Deleting a task removes its worker before its +proxy and network, including when no application processes remain in the worker. + +Run the unit and simulated Engine tests with `go test -race ./sandbox`. On a +dedicated Docker host with the sandbox images built, enable the detached-child +cleanup test with: + +```bash +ARTEX_SANDBOX_DOCKER_TEST=1 go test ./sandbox -run TestDockerTimeoutRemovesDetachedChild -v +``` + - **Tamper-proof egress audit log**: `artex-egress-` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit//egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/:/workspace:rw` and cannot read, truncate, or forge the egress audit log. - **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-` runs `/usr/local/bin/artex-exec-wrap --init` as PID 1 (reaping all orphaned children). On `POST /v1/tasks/{id}/kill`, `artex-runner` executes `/usr/local/bin/artex-exec-wrap --kill-uid 10001` as uid `10001` (preserving `--cap-drop ALL`) scanning `/proc` directly (defeating `setsid`, `nohup`, nested double-forked daemons, `trap '' TERM`, and `/tmp` tampering), verifies zero non-PID-1 uid-10001 processes remain, and falls back to force-removing the worker container if any check fails. - **Browser & `WebFetch` containment**: In `ARTEX_SANDBOX=required` mode, local stdio MCP servers (including the default private browser MCP) are skipped on the panel; `WebFetch` enforces the task's `sandbox.EgressPolicy` on every URL, redirect hop, and pinned dial (with direct retry disabled); and the opt-in panel-hosted shared browser MCP is only attached when `target_gate` is enabled or an explicit egress proxy is configured, with every browser navigation URL gated against the task's `sandbox.EgressPolicy` (execution containment + scope-gated panel fetch/browser; full subresource browser network isolation requires running the shared browser behind `egress-guard` in `EGRESS_MODE=enforce`). diff --git a/sandbox/docker.go b/sandbox/docker.go index 663261571..b197276d4 100644 --- a/sandbox/docker.go +++ b/sandbox/docker.go @@ -40,8 +40,8 @@ type taskContainers struct { proxyID string netName string scopeHash string - // cleanupMu serializes Kill and Delete for this task. A pause racing a - // delete must not interleave two cleanup sequences over the same IDs. + // cleanupMu serializes creation, recovery on exec, and cleanup for this task. + // Commands may execute concurrently, but lifecycle changes share this lock. cleanupMu sync.Mutex } @@ -441,14 +441,28 @@ func scopeFingerprint(domains, cidrs []string) string { func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDomains, scopeCIDRs []string) (*taskContainers, error) { b.mu.Lock() tc := b.tasks[taskID] + if tc == nil { + tc = &taskContainers{taskID: taskID, netName: b.cfg.TaskNetPrefix + taskID} + b.tasks[taskID] = tc + } + b.mu.Unlock() + tc.cleanupMu.Lock() + defer tc.cleanupMu.Unlock() + // Delete may have completed while this request waited for the lifecycle lock. + b.mu.Lock() + current := b.tasks[taskID] == tc b.mu.Unlock() + if !current { + return nil, fmt.Errorf("%w: task %s was deleted", ErrNotFound, taskID) + } netName := b.cfg.TaskNetPrefix + taskID + tc.netName = netName proxyName := "artex-egress-" + taskID workerName := "artex-worker-" + taskID sh := scopeFingerprint(scopeDomains, scopeCIDRs) - if tc != nil && tc.scopeHash == sh { + if tc.scopeHash == sh { proxyOK := tc.proxyID != "" && b.startContainer(ctx, tc.proxyID) == nil if !proxyOK && tc.proxyID != "" { b.removeContainer(ctx, tc.proxyID) @@ -488,7 +502,7 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma } // Recreate proxy if missing or scope changed. - if tc == nil || tc.proxyID == "" || tc.scopeHash != sh { + if tc.proxyID == "" || tc.scopeHash != sh { b.removeContainer(ctx, proxyName) proxySpec := map[string]any{ "Image": b.cfg.ProxyImage, @@ -529,9 +543,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma b.removeContainer(ctx, pid) return nil, err } - if tc == nil { - tc = &taskContainers{taskID: taskID, netName: netName} - } tc.proxyID = pid tc.scopeHash = sh } @@ -591,9 +602,6 @@ func (b *DockerBackend) ensureTask(ctx context.Context, taskID string, scopeDoma tc.workerID = wid } - b.mu.Lock() - b.tasks[taskID] = tc - b.mu.Unlock() return tc, nil } @@ -605,6 +613,12 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest if err != nil { return ExecResponse{}, err } + tc.cleanupMu.Lock() + workerID := tc.workerID + tc.cleanupMu.Unlock() + if workerID == "" { + return ExecResponse{}, fmt.Errorf("%w: task %s worker was removed", ErrNotFound, taskID) + } // Wrap argv with artex-exec-wrap so every exec gets its own process group, // enforces timeout_ms (SIGTERM group -> 5s -> SIGKILL -> exit 124) without @@ -623,7 +637,7 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest } sort.Strings(envList) - createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(tc.workerID)+"/exec", map[string]any{ + createResp, err := b.dockerDo(ctx, http.MethodPost, "/containers/"+url.PathEscape(workerID)+"/exec", map[string]any{ "AttachStdout": true, "AttachStderr": true, "Tty": false, @@ -656,28 +670,44 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest "Tty": false, }) if err != nil { - if ctx.Err() != nil { - _ = b.Kill(context.Background(), taskID) - } - return ExecResponse{}, err + return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID)) } defer startResp.Body.Close() + if startResp.StatusCode >= 300 { + return ExecResponse{}, errors.Join(fmt.Errorf("start exec: HTTP %d", startResp.StatusCode), b.removeExecWorker(ctx, tc, workerID)) + } - stdout, stderr, truncated, _ := demuxDockerStream(startResp.Body, MaxOutputBytes) + stdout, stderr, truncated, streamErr := demuxDockerStream(startResp.Body, MaxOutputBytes) + if err := errors.Join(streamErr, execCtx.Err()); err != nil { + return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID)) + } - inspectResp, err := b.dockerDo(context.Background(), http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil) - exitCode := -1 - if err == nil { - defer inspectResp.Body.Close() - var ins struct { - ExitCode int `json:"ExitCode"` - } - if json.NewDecoder(inspectResp.Body).Decode(&ins) == nil { - exitCode = ins.ExitCode - } + ic, cancelInspect := cleanupContext(ctx) + defer cancelInspect() + inspectResp, err := b.dockerDo(ic, http.MethodGet, "/exec/"+url.PathEscape(created.ID)+"/json", nil) + if err != nil { + return ExecResponse{}, errors.Join(err, b.removeExecWorker(ctx, tc, workerID)) + } + defer inspectResp.Body.Close() + var ins struct { + ExitCode *int `json:"ExitCode"` + Running *bool `json:"Running"` + } + decodeErr := json.NewDecoder(inspectResp.Body).Decode(&ins) + completed := ins.ExitCode != nil && ins.Running != nil && !*ins.Running + if decodeErr != nil || inspectResp.StatusCode != http.StatusOK || !completed { + return ExecResponse{}, errors.Join(fmt.Errorf("cannot prove exec completed (HTTP %d): %v", inspectResp.StatusCode, decodeErr), b.removeExecWorker(ctx, tc, workerID)) } + exitCode := *ins.ExitCode timedOut := exitCode == 124 + if timedOut || ctx.Err() != nil { + // Process-group timeout cannot kill setsid/double-fork descendants. + // Destroy the captured container, including its PID namespace and cgroup. + if err := b.removeExecWorker(ctx, tc, workerID); err != nil { + return ExecResponse{}, err + } + } return ExecResponse{ ExitCode: exitCode, Stdout: stdout, @@ -688,6 +718,21 @@ func (b *DockerBackend) Exec(ctx context.Context, taskID string, req ExecRequest }, nil } +// removeExecWorker removes the exact container that ran this exec. A timeout +// also terminates sibling execs in that task, while preserving /workspace. +// Never remove a replacement worker, or forget a failed cleanup. +func (b *DockerBackend) removeExecWorker(ctx context.Context, tc *taskContainers, workerID string) error { + tc.cleanupMu.Lock() + defer tc.cleanupMu.Unlock() + cctx, cancel := cleanupContext(ctx) + defer cancel() + if err := b.removeContainer(cctx, workerID); err != nil { + return fmt.Errorf("exec cleanup for task %s: %w", tc.taskID, err) + } + b.clearWorkerID(tc, workerID) + return nil +} + // Kill terminates EVERY uid-10001 process inside the task's worker container // (excluding PID 1) by running a root exec scanning /proc directly — never // trusting any agent-writable state. If root exec fails or reports surviving @@ -751,7 +796,6 @@ func (b *DockerBackend) clearWorkerID(tc *taskContainers, workerID string) { cur.workerID = "" } b.mu.Unlock() - tc.workerID = "" } func (b *DockerBackend) killWorkerByProcScan(ctx context.Context, workerID string) error { @@ -827,9 +871,13 @@ func (b *DockerBackend) Delete(ctx context.Context, taskID string) error { cctx, cancel := cleanupContext(ctx) defer cancel() - if err := b.killCaptured(cctx, tc); err != nil { - return fmt.Errorf("delete task %s: %w", taskID, err) + // Removing the worker also stops its processes and detaches the network + // endpoint. A process scan alone leaves PID 1 and the endpoint alive. + workerID := tc.workerID + if err := b.removeContainer(cctx, workerID); err != nil { + return fmt.Errorf("delete task %s worker: %w", taskID, err) } + b.clearWorkerID(tc, workerID) var errs []error if err := b.removeContainer(cctx, tc.proxyID); err != nil { @@ -861,7 +909,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca hdr := make([]byte, 8) for { if _, err := io.ReadFull(r, hdr); err != nil { - if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { + if errors.Is(err, io.EOF) { break } return outBuf.String(), errBuf.String(), truncated, err @@ -884,7 +932,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca take = rem truncated = true } - if _, err := io.CopyN(dst, r, take); err != nil && !errors.Is(err, io.EOF) { + if _, err := io.CopyN(dst, r, take); err != nil { return outBuf.String(), errBuf.String(), truncated, err } frameLen -= take @@ -892,7 +940,7 @@ func demuxDockerStream(r io.Reader, maxBytes int) (stdout, stderr string, trunca truncated = true } if frameLen > 0 { - if _, err := io.CopyN(io.Discard, r, frameLen); err != nil && !errors.Is(err, io.EOF) { + if _, err := io.CopyN(io.Discard, r, frameLen); err != nil { return outBuf.String(), errBuf.String(), truncated, err } } diff --git a/sandbox/docker_cleanup_test.go b/sandbox/docker_cleanup_test.go index 3cfc2db12..9eae6410b 100644 --- a/sandbox/docker_cleanup_test.go +++ b/sandbox/docker_cleanup_test.go @@ -15,11 +15,20 @@ import ( // the request sequence so tests can assert cleanup ordering, and lets each test // fail specific delete calls. type fakeDocker struct { - mu sync.Mutex - calls []string - execStatus int // POST /containers/{id}/exec, 0 means 200 - deleteCode map[string]int // container name -> status, 0 means 204 - networkCode int // 0 means 204 + mu sync.Mutex + calls []string + execStatus int // POST /containers/{id}/exec, 0 means 200 + deleteCode map[string]int // container name -> status, 0 means 204 + networkCode int // 0 means 204 + requireWorkerRemoval bool // model Docker rejecting a network with a live worker endpoint + execExitCode int + execRunning bool + execStream []byte + execStartCode int + inspectCode int + inspectBody string + streamReady chan struct{} + streamStarted bool } func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -29,6 +38,8 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Unlock() switch { + case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"): + w.WriteHeader(http.StatusNoContent) case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"): if f.execStatus != 0 { w.WriteHeader(f.execStatus) @@ -36,9 +47,37 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) { } _ = json.NewEncoder(w).Encode(map[string]string{"Id": "exec-1"}) case r.Method == http.MethodPost && strings.HasPrefix(p, "/exec/") && strings.HasSuffix(p, "/start"): + if f.execStartCode != 0 { + w.WriteHeader(f.execStartCode) + return + } w.WriteHeader(http.StatusOK) + f.mu.Lock() + firstStream := f.streamReady != nil && !f.streamStarted + if firstStream { + f.streamStarted = true + } + f.mu.Unlock() + if firstStream { + w.(http.Flusher).Flush() + close(f.streamReady) + <-r.Context().Done() + return + } + _, _ = w.Write(f.execStream) case r.Method == http.MethodGet && strings.HasPrefix(p, "/exec/"): - _ = json.NewEncoder(w).Encode(map[string]int{"ExitCode": 0}) + if f.inspectBody != "" { + if f.inspectCode != 0 { + w.WriteHeader(f.inspectCode) + } + _, _ = w.Write([]byte(f.inspectBody)) + return + } + if f.inspectCode != 0 { + w.WriteHeader(f.inspectCode) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": f.execExitCode, "Running": f.execRunning}) case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"): name := strings.TrimPrefix(p, "/containers/") if code := f.deleteCode[name]; code >= 300 { @@ -47,6 +86,10 @@ func (f *fakeDocker) ServeHTTP(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusNoContent) case r.Method == http.MethodDelete && strings.HasPrefix(p, "/networks/"): + if f.requireWorkerRemoval && !f.seen("DELETE /containers/worker-1") { + http.Error(w, "network has active endpoints", http.StatusForbidden) + return + } if f.networkCode >= 300 { w.WriteHeader(f.networkCode) return @@ -68,7 +111,7 @@ func (f *fakeDocker) seen(prefix string) bool { return false } -func newFakeDockerBackend(t *testing.T, f *fakeDocker) *DockerBackend { +func newFakeDockerBackend(t *testing.T, f http.Handler) *DockerBackend { t.Helper() sock := filepath.Join(t.TempDir(), "docker.sock") ln, err := net.Listen("unix", sock) @@ -181,26 +224,26 @@ func TestDeleteKeepsStateWhenProxyRemovalFails(t *testing.T) { if !f.seen("DELETE /containers/proxy-1") { t.Fatal("Delete never attempted the proxy removal") } - // The kill sequence must run before the proxy delete. + // Removing the worker stops its processes before the proxy is removed. f.mu.Lock() - killIdx, proxyIdx := -1, -1 + workerIdx, proxyIdx := -1, -1 for i, c := range f.calls { - if strings.HasPrefix(c, "POST /containers/worker-1/exec") { - killIdx = i + if c == "DELETE /containers/worker-1" { + workerIdx = i } if c == "DELETE /containers/proxy-1" { proxyIdx = i } } f.mu.Unlock() - if killIdx == -1 || proxyIdx == -1 || killIdx > proxyIdx { - t.Fatalf("Delete did not kill the worker before removing the proxy: %v", f.calls) + if workerIdx == -1 || proxyIdx == -1 || workerIdx > proxyIdx { + t.Fatalf("Delete did not remove the worker before removing the proxy: %v", f.calls) } } // TestDeleteUnpublishesOnlyAfterFullSuccess covers the happy path. func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) { - f := &fakeDocker{} + f := &fakeDocker{requireWorkerRemoval: true} b := newFakeDockerBackend(t, f) seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") @@ -210,11 +253,26 @@ func TestDeleteUnpublishesOnlyAfterFullSuccess(t *testing.T) { if _, ok := b.tasks["t1"]; ok { t.Fatal("Delete left the task in the map after full success") } - if !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") { + if !f.seen("DELETE /containers/worker-1") || !f.seen("DELETE /containers/proxy-1") || !f.seen("DELETE /networks/artex-task-t1") { t.Fatalf("Delete skipped resources: %v", f.calls) } } +func TestDeleteRetainsWorkerAfterRemovalFailure(t *testing.T) { + f := &fakeDocker{deleteCode: map[string]int{"worker-1": http.StatusInternalServerError}} + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") + if err := b.Delete(context.Background(), "t1"); err == nil { + t.Fatal("Delete succeeded although the worker could not be removed") + } + if b.tasks["t1"] != tc || tc.workerID != "worker-1" { + t.Fatal("Delete lost the worker needed for a cleanup retry") + } + if f.seen("DELETE /networks/") { + t.Fatal("network deletion attempted while worker is still attached") + } +} + // TestDeleteUsesFreshContextAfterCancellation: deletion from a cancelled HTTP // request must still stop the containers. func TestDeleteUsesFreshContextAfterCancellation(t *testing.T) { diff --git a/sandbox/docker_timeout_e2e_test.go b/sandbox/docker_timeout_e2e_test.go new file mode 100644 index 000000000..eb770abd2 --- /dev/null +++ b/sandbox/docker_timeout_e2e_test.go @@ -0,0 +1,72 @@ +package sandbox + +import ( + "context" + "fmt" + "net/http" + "os" + "path/filepath" + "testing" + "time" +) + +// A real Engine is needed to prove the kernel kills a detached child, not just +// that the runner requests removal. The child writes a canary and performs no +// network activity. Build the worker/proxy images before opting in. +func TestDockerTimeoutRemovesDetachedChild(t *testing.T) { + if os.Getenv("ARTEX_SANDBOX_DOCKER_TEST") != "1" { + t.Skip("requires live Docker and built sandbox images") + } + ws, au := t.TempDir(), t.TempDir() + id := fmt.Sprintf("timeout-%d", time.Now().UnixNano()) + egressNet := "artex-test-egress-" + id + for _, dir := range []string{ws, au, filepath.Join(ws, id), filepath.Join(au, id)} { + if err := os.MkdirAll(dir, 0o777); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o777); err != nil { + t.Fatal(err) + } + } + b := NewDockerBackend(DockerConfig{WorkspaceRoot: ws, HostWorkspaceRoot: ws, AuditRoot: au, HostAuditRoot: au, + TaskNetPrefix: "artex-test-task-", EgressNet: egressNet}) + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + t.Cleanup(func() { + _ = b.Delete(context.Background(), id) + _ = b.removeNetwork(context.Background(), egressNet) + }) + if err := b.Ping(ctx); err != nil { + t.Fatal(err) + } + tc, err := b.ensureTask(ctx, id, nil, nil) + if err != nil { + t.Fatal(err) + } + worker := tc.workerID + script := `import subprocess,sys,time +child="import time; f=open('/workspace/timeout-canary','ab',buffering=0); [(f.write(b'x'),time.sleep(.05)) for _ in range(200)]" +subprocess.Popen([sys.executable,'-c',child],start_new_session=True,stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) +time.sleep(10)` + res, err := b.Exec(ctx, id, ExecRequest{Argv: []string{"python3", "-c", script}, Workdir: "/workspace", TimeoutMS: 1000}) + if err != nil || !res.TimedOut { + t.Fatalf("response=%+v error=%v", res, err) + } + r, err := b.dockerDo(ctx, http.MethodGet, "/containers/"+worker+"/json", nil) + if err != nil { + t.Fatal(err) + } + defer r.Body.Close() + if r.StatusCode != http.StatusNotFound { + t.Fatalf("timed-out worker still exists: HTTP %d", r.StatusCode) + } + before, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary")) + if err != nil || len(before) == 0 { + t.Fatalf("child never ran: %v", err) + } + time.Sleep(200 * time.Millisecond) + after, err := os.ReadFile(filepath.Join(ws, id, "timeout-canary")) + if err != nil || len(after) != len(before) { + t.Fatalf("child continued after timeout: %v", err) + } +} diff --git a/sandbox/exec_cleanup_test.go b/sandbox/exec_cleanup_test.go new file mode 100644 index 000000000..7ec568ca1 --- /dev/null +++ b/sandbox/exec_cleanup_test.go @@ -0,0 +1,108 @@ +package sandbox + +import ( + "context" + "net/http" + "testing" + "time" +) + +func TestExecFailsClosedAndRemovesWorker(t *testing.T) { + for _, test := range []struct { + name string + fake *fakeDocker + wantErr bool + }{ + {"timeout", &fakeDocker{execExitCode: 124}, false}, + {"still_running", &fakeDocker{execRunning: true}, true}, + {"truncated_stream", &fakeDocker{execStream: []byte{1, 0, 0}}, true}, + {"truncated_payload", &fakeDocker{execStream: []byte{1, 0, 0, 0, 0, 0, 0, 4, 'x'}}, true}, + {"inspect_failure", &fakeDocker{inspectCode: http.StatusInternalServerError}, true}, + {"missing_exit_code", &fakeDocker{inspectBody: `{"Running":false}`}, true}, + {"missing_running_status", &fakeDocker{inspectBody: `{"ExitCode":0}`}, true}, + {"malformed_inspect", &fakeDocker{inspectBody: `{`}, true}, + {"start_failure", &fakeDocker{execStartCode: http.StatusInternalServerError}, true}, + } { + t.Run(test.name, func(t *testing.T) { + b := newFakeDockerBackend(t, test.fake) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") + tc.scopeHash = scopeFingerprint(nil, nil) + res, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}) + if (err != nil) != test.wantErr { + t.Fatalf("response=%+v error=%v", res, err) + } + if !test.wantErr && !res.TimedOut { + t.Fatalf("timeout lost: %+v", res) + } + if tc.workerID != "" || !test.fake.seen("DELETE /containers/worker-1") { + t.Fatal("worker survived failed/timed-out execution") + } + }) + } +} + +func TestExecCancellationCleansUpWithFreshContext(t *testing.T) { + f := &fakeDocker{streamReady: make(chan struct{})} + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") + tc.scopeHash = scopeFingerprint(nil, nil) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + done := make(chan error, 1) + go func() { _, err := b.Exec(ctx, "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); done <- err }() + select { + case <-f.streamReady: + case <-time.After(3 * time.Second): + t.Fatal("exec did not start") + } + cancel() + select { + case err := <-done: + if err == nil { + t.Fatal("cancelled exec reported success") + } + case <-time.After(3 * time.Second): + t.Fatal("cleanup hung") + } + if tc.workerID != "" || !f.seen("DELETE /containers/worker-1") { + t.Fatal("cancelled exec left worker alive") + } +} + +func TestExecTimeoutRemovalFailureKeepsWorker(t *testing.T) { + f := &fakeDocker{execExitCode: 124, deleteCode: map[string]int{"worker-1": 500}} + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") + tc.scopeHash = scopeFingerprint(nil, nil) + if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err == nil { + t.Fatal("cleanup failure hidden") + } + if tc.workerID != "worker-1" { + t.Fatal("worker lost before cleanup was proven") + } +} + +func TestSuccessfulExecPreservesWorker(t *testing.T) { + f := &fakeDocker{} + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "artex-task-t1") + tc.scopeHash = scopeFingerprint(nil, nil) + if _, err := b.Exec(context.Background(), "t1", ExecRequest{Argv: []string{"true"}, TimeoutMS: 1000}); err != nil { + t.Fatal(err) + } + if tc.workerID != "worker-1" || f.seen("DELETE /containers/worker-1") { + t.Fatal("successful exec lost its worker") + } +} + +func TestDelayedExecCleanupPreservesReplacementWorker(t *testing.T) { + f := &fakeDocker{} + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "replacement-worker", "proxy-1", "artex-task-t1") + if err := b.removeExecWorker(context.Background(), tc, "old-worker"); err != nil { + t.Fatal(err) + } + if tc.workerID != "replacement-worker" || f.seen("DELETE /containers/replacement-worker") || !f.seen("DELETE /containers/old-worker") { + t.Fatal("late cleanup targeted or forgot replacement worker") + } +} diff --git a/sandbox/exec_concurrency_test.go b/sandbox/exec_concurrency_test.go new file mode 100644 index 000000000..66af87186 --- /dev/null +++ b/sandbox/exec_concurrency_test.go @@ -0,0 +1,204 @@ +package sandbox + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "sync" + "testing" + "time" +) + +// A timed-out command removes its task's worker, ending sibling exec streams. +// An exec in another task must remain live until it finishes independently. +func TestExecTimeoutStopsSiblingsButPreservesOtherTask(t *testing.T) { + siblingStarted := make(chan struct{}) + otherStarted := make(chan struct{}) + workerRemoved := make(chan struct{}) + finishOther := make(chan struct{}) + var removedOnce sync.Once + var mu sync.Mutex + var removed []string + f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + p := r.URL.Path + switch { + case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/start"): + w.WriteHeader(http.StatusNoContent) + case r.Method == http.MethodPost && strings.HasPrefix(p, "/containers/") && strings.HasSuffix(p, "/exec"): + var spec struct{ Cmd []string } + if err := json.NewDecoder(r.Body).Decode(&spec); err != nil || len(spec.Cmd) == 0 { + http.Error(w, "missing command", http.StatusBadRequest) + return + } + _ = json.NewEncoder(w).Encode(map[string]string{"Id": spec.Cmd[len(spec.Cmd)-1]}) + case p == "/exec/sibling/start" || p == "/exec/other/start": + w.WriteHeader(http.StatusOK) + w.(http.Flusher).Flush() + if p == "/exec/sibling/start" { + close(siblingStarted) + select { + case <-workerRemoved: + case <-r.Context().Done(): + } + } else { + close(otherStarted) + select { + case <-finishOther: + case <-r.Context().Done(): + } + } + case p == "/exec/timeout/start": + w.WriteHeader(http.StatusOK) + case p == "/exec/sibling/json": + http.Error(w, "worker removed", http.StatusNotFound) + case p == "/exec/timeout/json": + _ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 124, "Running": false}) + case p == "/exec/other/json": + _ = json.NewEncoder(w).Encode(map[string]any{"ExitCode": 0, "Running": false}) + case r.Method == http.MethodDelete && strings.HasPrefix(p, "/containers/"): + mu.Lock() + removed = append(removed, p) + mu.Unlock() + if p == "/containers/worker-a" { + removedOnce.Do(func() { close(workerRemoved) }) + } + w.WriteHeader(http.StatusNoContent) + default: + http.NotFound(w, r) + } + }) + b := newFakeDockerBackend(t, f) + a := seedTask(b, "a", "worker-a", "proxy-a", "net-a") + other := seedTask(b, "b", "worker-b", "proxy-b", "net-b") + a.scopeHash = scopeFingerprint(nil, nil) + other.scopeHash = a.scopeHash + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + siblingDone := make(chan error, 1) + otherDone := make(chan error, 1) + run := func(task, command string, done chan<- error) { + res, err := b.Exec(ctx, task, ExecRequest{Argv: []string{command}, TimeoutMS: 1000}) + if err == nil && res.ExitCode != 0 { + err = errors.New("unexpected nonzero exit") + } + done <- err + } + go run("a", "sibling", siblingDone) + waitSignal(t, ctx, siblingStarted) + go run("b", "other", otherDone) + waitSignal(t, ctx, otherStarted) + res, err := b.Exec(ctx, "a", ExecRequest{Argv: []string{"timeout"}, TimeoutMS: 1000}) + if err != nil || !res.TimedOut { + t.Fatalf("timeout response=%+v err=%v", res, err) + } + select { + case err := <-siblingDone: + if err == nil { + t.Fatal("sibling reported success after its worker was removed") + } + case <-ctx.Done(): + t.Fatal("sibling did not finish after worker removal") + } + select { + case err := <-otherDone: + t.Fatalf("another task's exec stopped early: %v", err) + default: + } + mu.Lock() + deletions := append([]string(nil), removed...) + mu.Unlock() + for _, path := range deletions { + if path != "/containers/worker-a" { + t.Fatalf("removed an unrelated resource: %s", path) + } + } + if a.workerID != "" || other.workerID != "worker-b" { + t.Fatalf("worker state: task a=%q, task b=%q", a.workerID, other.workerID) + } + close(finishOther) + select { + case err := <-otherDone: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("other task did not finish") + } +} + +func waitSignal(t *testing.T, ctx context.Context, signal <-chan struct{}) { + t.Helper() + select { + case <-signal: + case <-ctx.Done(): + t.Fatal("timed out waiting for simulated Docker request") + } +} + +// Delete must retain the lifecycle lock until resources and the map entry are +// removed. An exec waiting behind it must not recreate the deleted task. +func TestEnsureTaskDoesNotRecreateDuringDelete(t *testing.T) { + deleting := make(chan struct{}) + releaseDelete := make(chan struct{}) + creationAttempt := make(chan struct{}, 1) + f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodDelete { + if r.URL.Path == "/containers/worker-1" { + close(deleting) + select { + case <-releaseDelete: + case <-r.Context().Done(): + } + } + w.WriteHeader(http.StatusNoContent) + return + } + select { + case creationAttempt <- struct{}{}: + default: + } + http.NotFound(w, r) + }) + b := newFakeDockerBackend(t, f) + tc := seedTask(b, "t1", "worker-1", "proxy-1", "net-1") + tc.scopeHash = scopeFingerprint(nil, nil) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(releaseDelete) }) } + defer release() + deleteDone := make(chan error, 1) + go func() { deleteDone <- b.Delete(ctx, "t1") }() + waitSignal(t, ctx, deleting) + ensureDone := make(chan error, 1) + go func() { _, err := b.ensureTask(ctx, "t1", nil, nil); ensureDone <- err }() + select { + case <-creationAttempt: + t.Fatal("ensureTask contacted Docker while Delete held the worker") + case err := <-ensureDone: + t.Fatalf("ensureTask returned before Delete completed: %v", err) + case <-time.After(50 * time.Millisecond): + } + release() + select { + case err := <-deleteDone: + if err != nil { + t.Fatal(err) + } + case <-ctx.Done(): + t.Fatal("Delete did not finish") + } + select { + case err := <-ensureDone: + if !errors.Is(err, ErrNotFound) { + t.Fatalf("ensureTask after deletion: %v", err) + } + case <-ctx.Done(): + t.Fatal("ensureTask did not finish") + } + if b.WorkerCount() != 0 { + t.Fatal("deleted task was re-registered") + } +}