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
22 changes: 22 additions & 0 deletions docs/SANDBOX.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<id>` writes JSONL connection logs to a proxy-only bind mount (`/app/data/egress-audit/<id>/egress.jsonl`, mounted at `/audit:rw` inside the proxy) and stdout. The worker container only mounts `/app/data/tasks/<id>:/workspace:rw` and cannot read, truncate, or forge the egress audit log.
- **Kernel-backed kill-switch (no agent-writable state)**: `artex-worker-<id>` 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`).
Expand Down
112 changes: 80 additions & 32 deletions sandbox/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}

Expand All @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -884,15 +932,15 @@ 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
} else {
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
}
}
Expand Down
Loading
Loading