From 436dd3e73f07582ec3b59c86011ca9c4bffbafb5 Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Tue, 6 Oct 2026 23:44:56 -0700 Subject: [PATCH 1/2] Add explicit agent execution sandbox and scoped cancellation --- .github/workflows/sandbox-validation.yml | 48 ++ .github/workflows/zakura-agent.yml | 8 +- apps/agent/internal/rpc/handler.go | 63 ++- apps/agent/internal/rpc/sandbox.go | 178 ++++++++ .../internal/rpc/sandbox_validation_test.go | 113 +++++ .../internal/sandbox/integration_test.go | 119 +++++ apps/agent/internal/sandbox/sandbox.go | 424 ++++++++++++++++++ .../agent/internal/sandbox/validation_test.go | 232 ++++++++++ apps/server/internal/runtime/acp.go | 38 +- apps/server/internal/runtime/acp_runtime.go | 7 + .../internal/runtime/agent_tool_runners.go | 19 +- apps/server/internal/runtime/agent_tools.go | 21 +- apps/server/internal/runtime/sandbox_exec.go | 102 +++++ .../server/internal/runtime/sandbox_policy.go | 61 +++ .../internal/runtime/sandbox_policy_test.go | 169 +++++++ .../internal/runtime/tool_session_state.go | 5 + docs/sandbox.md | 78 ++++ 17 files changed, 1658 insertions(+), 27 deletions(-) create mode 100644 .github/workflows/sandbox-validation.yml create mode 100644 apps/agent/internal/rpc/sandbox.go create mode 100644 apps/agent/internal/rpc/sandbox_validation_test.go create mode 100644 apps/agent/internal/sandbox/integration_test.go create mode 100644 apps/agent/internal/sandbox/sandbox.go create mode 100644 apps/agent/internal/sandbox/validation_test.go create mode 100644 apps/server/internal/runtime/sandbox_exec.go create mode 100644 apps/server/internal/runtime/sandbox_policy.go create mode 100644 apps/server/internal/runtime/sandbox_policy_test.go create mode 100644 docs/sandbox.md diff --git a/.github/workflows/sandbox-validation.yml b/.github/workflows/sandbox-validation.yml new file mode 100644 index 00000000..bbfb36b5 --- /dev/null +++ b/.github/workflows/sandbox-validation.yml @@ -0,0 +1,48 @@ +name: sandbox-validation + +on: + workflow_dispatch: + pull_request: + paths: + - 'apps/agent/**' + - 'apps/server/**' + - '.github/workflows/sandbox-validation.yml' + push: + branches: ['feat/agent-execution-sandbox'] + +permissions: + contents: read + +jobs: + sandbox: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: '1.26.4' + cache-dependency-path: | + apps/agent/go.sum + apps/server/go.sum + - name: Agent tests and race detector + working-directory: apps/agent + run: | + go test -race ./... + go vet ./... + - name: Prepare sandbox test image + run: | + docker pull alpine:3.23 + echo "ZAKURA_SANDBOX_IMAGE=$(docker image inspect alpine:3.23 --format '{{index .RepoDigests 0}}')" >> "$GITHUB_ENV" + - name: Real container isolation and lifecycle checks + working-directory: apps/agent + env: + ZAKURA_SANDBOX_INTEGRATION: '1' + run: go test -count=1 -v ./internal/sandbox + - name: Server regression tests + working-directory: apps/server + env: + CGO_ENABLED: '1' + run: | + go test ./... + go vet ./... diff --git a/.github/workflows/zakura-agent.yml b/.github/workflows/zakura-agent.yml index a08ae922..bbdc9ea8 100644 --- a/.github/workflows/zakura-agent.yml +++ b/.github/workflows/zakura-agent.yml @@ -61,13 +61,13 @@ jobs: - uses: actions/download-artifact@v4 with: name: zakura-agent-binaries - path: go/agent/dist + path: apps/agent/dist - name: attach raw binaries env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | gh release upload "${GITHUB_REF_NAME}" \ - go/agent/dist/zakura-agent_* \ - go/agent/dist/VERSION \ - go/agent/dist/checksums.txt \ + apps/agent/dist/zakura-agent_* \ + apps/agent/dist/VERSION \ + apps/agent/dist/checksums.txt \ --clobber diff --git a/apps/agent/internal/rpc/handler.go b/apps/agent/internal/rpc/handler.go index b6438700..18a3da92 100644 --- a/apps/agent/internal/rpc/handler.go +++ b/apps/agent/internal/rpc/handler.go @@ -6,28 +6,34 @@ import ( "encoding/json" "fmt" "io" + "os" "strings" "sync" "github.com/Moonrend/Zakura/apps/agent/internal/docker" "github.com/Moonrend/Zakura/apps/agent/internal/host" + "github.com/Moonrend/Zakura/apps/agent/internal/sandbox" "github.com/Moonrend/Zakura/apps/agent/internal/sys" ) type Handler struct { - Kind string - StorageRoot string - jobs *host.Registry - ptys map[string]*host.LiveStream - mu sync.Mutex + Kind string + StorageRoot string + jobs *host.Registry + sandboxJobs *sandbox.Registry + sandboxEnforced bool + ptys map[string]*host.LiveStream + mu sync.Mutex } func New(kind, storageRoot string) *Handler { return &Handler{ - Kind: kind, - StorageRoot: storageRoot, - jobs: host.NewRegistry(), - ptys: map[string]*host.LiveStream{}, + Kind: kind, + StorageRoot: storageRoot, + jobs: host.NewRegistry(), + sandboxJobs: sandbox.NewRegistry(), + sandboxEnforced: sandboxEnforcement(os.Getenv("ZAKURA_SANDBOX_ENABLED")), + ptys: map[string]*host.LiveStream{}, } } @@ -38,7 +44,24 @@ func (h *Handler) workspace(spaceID string) string { func (h *Handler) Dispatch(ctx context.Context, msg Msg, send func(Msg)) { var err error var result any + + // Do not let an explicit isolation request silently use an unsupported + // execution transport. Docker management is not the sandbox backend API. + switch msg.Method { + case "docker.run", "docker.exec", "docker.exec.start", "docker.attach", "docker.recreate": + requested, policyErr := h.sandboxRequested(msg.Params) + if policyErr != nil { + send(Err(msg.ID, policyErr.Error())) + return + } + if requested { + send(Err(msg.ID, "this execution method is unavailable in sandbox mode; use host.exec or host.exec.start")) + return + } + } switch msg.Method { + case "sandbox.policy": + result = map[string]any{"enforced": h.sandboxEnforced, "defaultExecutionMode": map[bool]string{true: "sandbox", false: "host"}[h.sandboxEnforced], "hostModeIsolated": false, "sandbox": sandbox.Policy()} case "sys.info": var p struct { Light bool `json:"light"` @@ -77,15 +100,24 @@ func (h *Handler) Dispatch(ctx context.Context, msg Msg, send func(Msg)) { case "host.fs.rename": result, err = h.fsRename(msg.Params) case "host.exec": - result, err = h.hostExec(msg.Params) + result, err = h.execWithPolicy(ctx, msg.Params, false) case "host.exec.start": - result, err = h.hostExecStart(msg.Params) + result, err = h.execWithPolicy(ctx, msg.Params, true) case "host.exec.get": - result, err = h.hostExecGet(msg.Params) + result, err = h.jobWithPolicy(msg.Params, false) case "host.exec.kill": - result, err = h.hostExecKill(msg.Params) + result, err = h.jobWithPolicy(msg.Params, true) case "host.pty.start": - result, err = h.ptyStart(msg.Params, send) + if enabled, policyErr := h.sandboxRequested(msg.Params); policyErr != nil { + err = policyErr + } else if enabled { + err = fmt.Errorf("interactive execution is unavailable in sandbox mode; use non-interactive sandbox execution") + } else { + result, err = h.ptyStart(msg.Params, send) + if err == nil { + result, err = executionResult(result, "host") + } + } case "host.pty.write": err = h.ptyWrite(msg.Params) result = map[string]bool{"ok": err == nil} @@ -191,6 +223,9 @@ func (h *Handler) Dispatch(ctx context.Context, msg Msg, send func(Msg)) { _ = json.Unmarshal(msg.Params, &p) message = host.ScrubHostPathsInMessage(h.rootOf(p), message) } + if strings.HasPrefix(msg.Method, "host.exec") { + message = host.ScrubHostPathsInMessage(h.StorageRoot, message) + } send(Err(msg.ID, message)) return } diff --git a/apps/agent/internal/rpc/sandbox.go b/apps/agent/internal/rpc/sandbox.go new file mode 100644 index 00000000..3dc40bf3 --- /dev/null +++ b/apps/agent/internal/rpc/sandbox.go @@ -0,0 +1,178 @@ +package rpc + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + "github.com/Moonrend/Zakura/apps/agent/internal/sandbox" +) + +var sandboxSpaceID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`) + +// The authenticated control plane supplies the space identity. Never accept an +// arbitrary root, a storage-root fallback, or a symlink into another workspace. +func (h *Handler) sandboxRoot(spaceID string) (string, error) { + if !sandboxSpaceID.MatchString(spaceID) { + return "", fmt.Errorf("a valid spaceId is required for sandbox execution") + } + root, err := filepath.Abs(h.StorageRoot) + if err != nil || h.StorageRoot == "" { + return "", fmt.Errorf("sandbox storage root is unavailable") + } + resolved, err := filepath.EvalSymlinks(root) + if err != nil || resolved != root { + return "", fmt.Errorf("sandbox storage root must be an existing non-symlink directory") + } + for _, part := range []string{"spaces", spaceID, "workspace"} { + root = filepath.Join(root, part) + if err := os.Mkdir(root, 0755); err != nil && !os.IsExist(err) { + return "", fmt.Errorf("sandbox workspace is unavailable") + } + info, err := os.Lstat(root) + if err != nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return "", fmt.Errorf("sandbox workspace must use real directories") + } + } + return root, nil +} + +type sandboxRequest struct { + sandbox.ExecParams + SpaceID string `json:"spaceId"` +} + +func (h *Handler) sandboxExecContext(ctx context.Context, raw json.RawMessage) (any, error) { + var p sandboxRequest + if err := json.Unmarshal(raw, &p); err != nil { + return nil, fmt.Errorf("invalid sandbox execution parameters") + } + root, err := h.sandboxRoot(p.SpaceID) + if err != nil { + return nil, err + } + return sandbox.Run(ctx, root, p.ExecParams) +} + +func (h *Handler) sandboxExecStart(raw json.RawMessage) (any, error) { + var p sandboxRequest + if err := json.Unmarshal(raw, &p); err != nil { + return nil, fmt.Errorf("invalid sandbox execution parameters") + } + root, err := h.sandboxRoot(p.SpaceID) + if err != nil { + return nil, err + } + return h.sandboxJobs.Start(root, p.ExecParams) +} + +func (h *Handler) sandboxJob(raw json.RawMessage, cancel bool) (any, error) { + var p struct { + ID string `json:"id"` + SpaceID string `json:"spaceId"` + } + if err := json.Unmarshal(raw, &p); err != nil { + return nil, fmt.Errorf("invalid sandbox job parameters") + } + root, err := h.sandboxRoot(p.SpaceID) + if err != nil { + return nil, err + } + var snap *sandbox.JobSnap + if cancel { + snap = h.sandboxJobs.KillScoped(p.ID, root) + } else { + snap = h.sandboxJobs.GetScoped(p.ID, root) + } + if snap == nil { + return nil, fmt.Errorf("sandbox job not found") + } + return snap, nil +} + +// Enforcement is captured when the authenticated runner handler is created. +// A request can select stronger isolation but cannot turn operator policy off. +func (h *Handler) sandboxRequested(raw json.RawMessage) (bool, error) { + var p struct { + ExecutionMode string `json:"executionMode"` + } + if err := json.Unmarshal(raw, &p); err != nil { + return false, fmt.Errorf("invalid execution policy parameters") + } + if p.ExecutionMode != "" && p.ExecutionMode != "host" && p.ExecutionMode != "sandbox" { + return false, fmt.Errorf("executionMode must be host or sandbox") + } + return h.sandboxEnforced || p.ExecutionMode == "sandbox", nil +} + +func executionResult(value any, mode string) (any, error) { + raw, err := json.Marshal(value) + if err != nil { + return nil, err + } + result := map[string]any{} + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + result["executionMode"] = mode + result["isolated"] = mode == "sandbox" + return result, nil +} + +func (h *Handler) execWithPolicy(ctx context.Context, raw json.RawMessage, start bool) (any, error) { + enabled, err := h.sandboxRequested(raw) + if err != nil { + return nil, err + } + var result any + mode := "host" + if enabled { + mode = "sandbox" + if start { + result, err = h.sandboxExecStart(raw) + } else { + result, err = h.sandboxExecContext(ctx, raw) + } + } else { + if start { + result, err = h.hostExecStart(raw) + } else { + result, err = h.hostExec(raw) + } + } + if err != nil { + return nil, err + } + return executionResult(result, mode) +} + +func (h *Handler) jobWithPolicy(raw json.RawMessage, cancel bool) (any, error) { + enabled, err := h.sandboxRequested(raw) + if err != nil { + return nil, err + } + var result any + mode := "host" + if enabled { + mode = "sandbox" + result, err = h.sandboxJob(raw, cancel) + } else if cancel { + result, err = h.hostExecKill(raw) + } else { + result, err = h.hostExecGet(raw) + } + if err != nil { + return nil, err + } + return executionResult(result, mode) +} + +// Unknown nonempty values fail closed rather than silently turning policy off. +func sandboxEnforcement(value string) bool { + value = strings.TrimSpace(value) + return value != "" && !strings.EqualFold(value, "false") && value != "0" +} diff --git a/apps/agent/internal/rpc/sandbox_validation_test.go b/apps/agent/internal/rpc/sandbox_validation_test.go new file mode 100644 index 00000000..d88bfe65 --- /dev/null +++ b/apps/agent/internal/rpc/sandbox_validation_test.go @@ -0,0 +1,113 @@ +package rpc + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" +) + +func sandboxCall(t *testing.T, h *Handler, method string, p any) Msg { + t.Helper() + raw, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + var response Msg + h.Dispatch(context.Background(), Msg{ID: "sandbox-test", Method: method, Params: raw}, func(msg Msg) { response = msg }) + return response +} + +func TestSandboxRPCPolicyAndEnforcement(t *testing.T) { + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + h := New("computer", t.TempDir()) + for _, mode := range []string{"", "host"} { + enabled, err := h.sandboxRequested(json.RawMessage(`{"executionMode":"` + mode + `"}`)) + if err != nil || enabled { + t.Fatalf("legacy mode unexpectedly isolated: %v %v", enabled, err) + } + } + t.Setenv("ZAKURA_SANDBOX_ENABLED", "true") + enforced := New("computer", t.TempDir()) + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + enabled, err := enforced.sandboxRequested(json.RawMessage(`{"executionMode":"host"}`)) + if err != nil || !enabled { + t.Fatalf("request downgraded operator policy: %v %v", enabled, err) + } + result := sandboxCall(t, enforced, "sandbox.policy", map[string]any{}) + var policy struct { + Enforced bool `json:"enforced"` + Default string `json:"defaultExecutionMode"` + HostIsolated bool `json:"hostModeIsolated"` + } + if err := json.Unmarshal(result.Result, &policy); err != nil { + t.Fatal(err) + } + if !policy.Enforced || policy.Default != "sandbox" || policy.HostIsolated { + t.Fatalf("incorrect policy disclosure: %+v", policy) + } +} + +func TestSandboxRPCRejectsUnsupportedTransports(t *testing.T) { + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + h := New("computer", t.TempDir()) + for _, method := range []string{"host.pty.start", "docker.run", "docker.exec", "docker.exec.start", "docker.attach", "docker.recreate"} { + t.Run(method, func(t *testing.T) { + result := sandboxCall(t, h, method, map[string]any{"executionMode": "sandbox", "spaceId": "space-a"}) + if result.Error == "" || !strings.Contains(result.Error, "sandbox") { + t.Fatalf("unsupported transport was not refused: %+v", result) + } + }) + } + for _, method := range []string{"host.exec", "host.exec.start", "host.exec.get", "host.exec.kill"} { + result := sandboxCall(t, h, method, map[string]any{"executionMode": "unknown"}) + if result.Error == "" { + t.Fatalf("%s accepted unknown execution mode", method) + } + } + var response Msg + h.Dispatch(context.Background(), Msg{ID: "invalid", Method: "host.exec", Params: json.RawMessage(`{"`)}, func(msg Msg) { response = msg }) + if response.Error == "" { + t.Fatal("malformed policy accepted") + } +} + +func TestSandboxRPCRequiresWorkspaceAndAvailableBackend(t *testing.T) { + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + t.Setenv("ZAKURA_SANDBOX_IMAGE", "") + h := New("computer", t.TempDir()) + for _, method := range []string{"host.exec", "host.exec.start", "host.exec.get", "host.exec.kill"} { + result := sandboxCall(t, h, method, map[string]any{"executionMode": "sandbox", "command": []string{"printf", "hello"}}) + if result.Error == "" || !strings.Contains(result.Error, "spaceId") { + t.Fatalf("%s accepted absent workspace: %+v", method, result) + } + } + result := sandboxCall(t, h, "host.exec", map[string]any{"executionMode": "sandbox", "spaceId": "space-a", "command": []string{"printf", "hello"}}) + if result.Error == "" || !strings.Contains(result.Error, "ZAKURA_SANDBOX_IMAGE") { + t.Fatalf("missing image did not fail closed: %+v", result) + } + for _, method := range []string{"host.exec.get", "host.exec.kill"} { + result = sandboxCall(t, h, method, map[string]any{"executionMode": "sandbox", "spaceId": "space-b", "id": "unknown-job"}) + if result.Error == "" || !strings.Contains(result.Error, "not found") { + t.Fatalf("unknown job exposed: %+v", result) + } + } +} + +func TestSandboxRPCRejectsSymlinkWorkspaceRoot(t *testing.T) { + t.Setenv("ZAKURA_SANDBOX_ENABLED", "") + storage := t.TempDir() + target := t.TempDir() + if err := os.MkdirAll(filepath.Join(storage, "spaces", "space-a"), 0755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(target, filepath.Join(storage, "spaces", "space-a", "workspace")); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + h := New("computer", storage) + if _, err := h.sandboxRoot("space-a"); err == nil { + t.Fatal("symlink workspace accepted") + } +} diff --git a/apps/agent/internal/sandbox/integration_test.go b/apps/agent/internal/sandbox/integration_test.go new file mode 100644 index 00000000..331e5209 --- /dev/null +++ b/apps/agent/internal/sandbox/integration_test.go @@ -0,0 +1,119 @@ +package sandbox + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" +) + +// This test requires a real local Docker daemon and a pre-pulled trusted image. +// Explicit opt-in makes backend failure fatal, never a successful skipped check. +func TestSandboxRealDockerIntegration(t *testing.T) { + if os.Getenv("ZAKURA_SANDBOX_INTEGRATION") != "1" { + t.Skip("real Docker isolation not requested; unit fixtures do not prove isolation") + } + if os.Getenv("ZAKURA_SANDBOX_IMAGE") == "" { + t.Fatal("integration requires pre-pulled ZAKURA_SANDBOX_IMAGE") + } + if _, err := exec.LookPath("docker"); err != nil { + t.Fatalf("Docker required for opted-in integration: %v", err) + } + listContainers := func() map[string]bool { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := dockerCommand(ctx, "docker", "container", "ls", "--all", "--filter", "name=zakura-sandbox-", "--format", "{{.ID}}") + output, err := cmd.Output() + if err != nil { + t.Fatalf("cannot verify real Docker containers: %v", err) + } + ids := map[string]bool{} + for _, id := range strings.Fields(string(output)) { + ids[id] = true + } + return ids + } + baseline := listContainers() + t.Cleanup(func() { + for id := range listContainers() { + if !baseline[id] { + t.Errorf("sandbox container remains after execution: %s", id) + } + } + }) + root := t.TempDir() + if err := os.Chmod(root, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "input.txt"), []byte("workspace fixture"), 0644); err != nil { + t.Fatal(err) + } + t.Setenv("ZAKURA_TEST_PARENT_SECRET", "must-not-be-inherited") + run := func(t *testing.T, command ...string) ExecResult { + t.Helper() + result, err := Run(context.Background(), root, ExecParams{Command: command, TimeoutMs: 10000}) + if err != nil { + t.Fatal(err) + } + return result + } + t.Run("workspace and user", func(t *testing.T) { + result := run(t, "sh", "-c", "cat /workspace/input.txt; printf '\n'; id -u; pwd") + if result.ExitCode != 0 || result.Stdout != "workspace fixture\n65534\n/workspace\n" { + t.Fatalf("workspace/user mismatch: %+v", result) + } + }) + t.Run("read only workspace", func(t *testing.T) { + result := run(t, "touch", "/workspace/ordinary-output.txt") + if result.ExitCode == 0 { + t.Fatal("workspace unexpectedly writable") + } + if _, err := os.Stat(filepath.Join(root, "ordinary-output.txt")); !os.IsNotExist(err) { + t.Fatalf("unexpected host output: %v", err) + } + }) + t.Run("network and clean environment", func(t *testing.T) { + result := run(t, "sh", "-c", "test -z \"${ZAKURA_TEST_PARENT_SECRET+x}\" && test \"$(ls /sys/class/net)\" = lo") + if result.ExitCode != 0 { + t.Fatalf("network/environment policy failed: %+v", result) + } + }) + t.Run("temporary scratch", func(t *testing.T) { + result := run(t, "sh", "-c", "printf scratch > /tmp/ordinary-output.txt; cat /tmp/ordinary-output.txt") + if result.ExitCode != 0 || result.Stdout != "scratch" { + t.Fatalf("scratch failed: %+v", result) + } + }) + t.Run("output cap", func(t *testing.T) { + result := run(t, "sh", "-c", "head -c 300000 /dev/zero") + if result.ExitCode != 0 || !result.Truncated || len(result.Stdout) != MaxOutputBytes { + t.Fatalf("output bound failed: code=%d bytes=%d truncated=%v", result.ExitCode, len(result.Stdout), result.Truncated) + } + }) + t.Run("timeout", func(t *testing.T) { + result, err := Run(context.Background(), root, ExecParams{Command: []string{"sleep", "30"}, TimeoutMs: 3000}) + if err != nil || !result.TimedOut { + t.Fatalf("timeout/cleanup failure: %+v %v", result, err) + } + }) + t.Run("cancel", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + timer := time.AfterFunc(3*time.Second, cancel) + defer timer.Stop() + result, err := Run(ctx, root, ExecParams{Command: []string{"sleep", "30"}}) + if err != nil || !result.Cancelled { + t.Fatalf("cancellation/cleanup failure: %+v %v", result, err) + } + }) + t.Run("nonzero exit", func(t *testing.T) { + result := run(t, "sh", "-c", "printf diagnostic >&2; exit 7") + if result.ExitCode != 7 || !strings.Contains(result.Stderr, "diagnostic") { + t.Fatalf("exit semantics: %+v", result) + } + }) +} diff --git a/apps/agent/internal/sandbox/sandbox.go b/apps/agent/internal/sandbox/sandbox.go new file mode 100644 index 00000000..850915be --- /dev/null +++ b/apps/agent/internal/sandbox/sandbox.go @@ -0,0 +1,424 @@ +// Package sandbox runs untrusted commands in disposable, restricted containers. +// Filesystem path checks are validation, not an OS isolation boundary. +package sandbox + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + "time" +) + +const MaxOutputBytes = 256 * 1024 +const MaxTimeoutMs = 300000 +const MaxStdinBytes = 64 * 1024 +const MaxJobs = 128 +const MaxConcurrent = 4 + +var executionSlots = make(chan struct{}, MaxConcurrent) + +// Enabled cannot be overridden by request or environment. +func Enabled() bool { return true } + +type PolicyInfo struct { + Enabled bool `json:"enabled"` + Backend string `json:"backend"` + ImageConfigured bool `json:"imageConfigured"` + Network string `json:"network"` + WorkspaceReadOnly bool `json:"workspaceReadOnly"` + MaxTimeoutMs int `json:"maxTimeoutMs"` + MaxOutputBytes int `json:"maxOutputBytes"` + MemoryBytes int64 `json:"memoryBytes"` + PidsLimit int `json:"pidsLimit"` +} + +func Policy() PolicyInfo { + return PolicyInfo{Enabled(), "docker", os.Getenv("ZAKURA_SANDBOX_IMAGE") != "", "none", true, MaxTimeoutMs, MaxOutputBytes, 512 * 1024 * 1024, 64} +} + +type ExecParams struct { + Command []string `json:"command"` + WorkingDir string `json:"workingDir"` + Env map[string]string `json:"env"` + TimeoutMs int `json:"timeoutMs"` + Stdin string `json:"stdin"` +} +type ExecResult struct { + ExitCode int `json:"exitCode"` + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + TimedOut bool `json:"timedOut"` + Cancelled bool `json:"cancelled"` + Truncated bool `json:"truncated"` +} + +type cappedWriter struct { + mu sync.Mutex + b bytes.Buffer + truncated bool +} + +func (w *cappedWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + n := len(p) + remaining := MaxOutputBytes - w.b.Len() + if len(p) > remaining { + p = p[:remaining] + w.truncated = true + } + _, _ = w.b.Write(p) + return n, nil +} +func (w *cappedWriter) snapshot() (string, bool) { + w.mu.Lock() + defer w.mu.Unlock() + return w.b.String(), w.truncated +} + +// buildArgs deliberately accepts no client-provided mounts, user, network or image. +func buildArgs(root string, p ExecParams, name string) ([]string, error) { + image := strings.TrimSpace(os.Getenv("ZAKURA_SANDBOX_IMAGE")) + if image == "" || strings.HasPrefix(image, "-") || strings.ContainsAny(image, "\x00\r\n\t ") { + return nil, errors.New("sandbox requires an operator-configured ZAKURA_SANDBOX_IMAGE") + } + if len(p.Command) == 0 || len(p.Command) > 256 || p.Command[0] == "" { + return nil, errors.New("sandbox command is required") + } + size := 0 + for _, v := range p.Command { + size += len(v) + if strings.ContainsRune(v, 0) { + return nil, errors.New("invalid command") + } + } + if size > 64*1024 || len(p.Stdin) > MaxStdinBytes { + return nil, errors.New("sandbox input limit exceeded") + } + if len(p.Env) > 0 { + return nil, errors.New("sandbox does not accept client environment variables") + } + if p.TimeoutMs < 0 || p.TimeoutMs > MaxTimeoutMs { + return nil, errors.New("sandbox timeout exceeds policy") + } + absolute, err := filepath.Abs(root) + if err != nil { + return nil, err + } + canonical, err := filepath.EvalSymlinks(absolute) + if err != nil { + return nil, fmt.Errorf("sandbox workspace: %w", err) + } + if canonical != absolute { + return nil, errors.New("sandbox workspace must not contain symlink ancestors") + } + info, err := os.Stat(canonical) + if err != nil || !info.IsDir() { + return nil, errors.New("sandbox workspace must be a directory") + } + if canonical == filepath.VolumeName(canonical)+string(filepath.Separator) || strings.ContainsAny(canonical, ",\r\n") { + return nil, errors.New("unsafe sandbox workspace root") + } + // Do not expose host IPC or device endpoints through the workspace mount. + // This check is defense in depth: operators must prevent concurrent host-side + // mutation of the validated workspace while a sandbox is running. + entries := 0 + if err := filepath.WalkDir(canonical, func(_ string, d fs.DirEntry, e error) error { + if e != nil { + return e + } + entries++ + if entries > 100000 { + return errors.New("sandbox workspace entry limit exceeded") + } + if d.Type()&(os.ModeSocket|os.ModeDevice|os.ModeNamedPipe) != 0 { + return errors.New("sandbox workspace contains a special file") + } + return nil + }); err != nil { + return nil, err + } + wd := "/workspace" + if p.WorkingDir != "" { + requested := p.WorkingDir + if requested == "/workspace" { + requested = canonical + } else if strings.HasPrefix(requested, "/workspace/") { + requested = filepath.Join(canonical, filepath.FromSlash(strings.TrimPrefix(requested, "/workspace/"))) + } + if !filepath.IsAbs(requested) { + requested = filepath.Join(canonical, requested) + } + resolved, err := filepath.EvalSymlinks(requested) + if err != nil { + return nil, fmt.Errorf("sandbox working directory: %w", err) + } + rel, err := filepath.Rel(canonical, resolved) + if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { + return nil, errors.New("working directory is outside workspace") + } + stat, err := os.Stat(resolved) + if err != nil || !stat.IsDir() { + return nil, errors.New("working directory must be a directory") + } + if rel != "." { + wd += "/" + filepath.ToSlash(rel) + } + } + return append([]string{"create", "--name", name, "--pull=never", "--rm", "--init", "--network=none", "--no-healthcheck", "--read-only", "--user=65534:65534", "--cap-drop=ALL", "--security-opt=no-new-privileges:true", "--pids-limit=64", "--memory=512m", "--memory-swap=512m", "--cpus=1", "--ulimit=nofile=256:256", "--ulimit=core=0:0", "--ipc=none", "--log-driver=none", "--tmpfs=/tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777", "--mount", "type=bind,src=" + canonical + ",dst=/workspace,readonly,bind-propagation=rprivate,bind-recursive=disabled", "--workdir", wd, "--env=HOME=/tmp", "--env=TMPDIR=/tmp", "--env=PATH=/usr/local/bin:/usr/bin:/bin", "--entrypoint", p.Command[0], "-i", image}, p.Command[1:]...), nil +} + +// The Docker client receives no inherited credentials, proxy or application secrets. +// Only a local default daemon is supported; remote/context overrides are excluded. +func dockerCommand(ctx context.Context, bin string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, bin, args...) + cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/nonexistent", "DOCKER_CONFIG=/nonexistent"} + cmd.WaitDelay = 2 * time.Second + return cmd +} + +func Run(ctx context.Context, root string, p ExecParams) (ExecResult, error) { + return run(ctx, root, p, &cappedWriter{}, &cappedWriter{}) +} +func run(ctx context.Context, root string, p ExecParams, out, errout *cappedWriter) (result ExecResult, runErr error) { + select { + case executionSlots <- struct{}{}: + defer func() { <-executionSlots }() + default: + return result, errors.New("sandbox concurrent execution limit reached") + } + var id [16]byte + if _, err := rand.Read(id[:]); err != nil { + return result, err + } + name := "zakura-sandbox-" + hex.EncodeToString(id[:]) + args, err := buildArgs(root, p, name) + if err != nil { + return result, err + } + bin, err := exec.LookPath("docker") + if err != nil { + return result, errors.New("sandbox Docker backend unavailable; host execution refused") + } + timeout := p.TimeoutMs + if timeout == 0 { + timeout = MaxTimeoutMs + } + ctx, cancel := context.WithTimeout(ctx, time.Duration(timeout)*time.Millisecond) + defer cancel() + defer func() { + result.TimedOut = errors.Is(ctx.Err(), context.DeadlineExceeded) + result.Cancelled = errors.Is(ctx.Err(), context.Canceled) + }() + + // Killing the CLI alone does not terminate its container. Always remove the + // named container with a separate bounded context, including create/start races. + defer func() { + cleanCtx, stop := context.WithTimeout(context.Background(), 10*time.Second) + defer stop() + clean := dockerCommand(cleanCtx, bin, "rm", "--force", name) + var diagnostic cappedWriter + clean.Stdout = &diagnostic + clean.Stderr = &diagnostic + if e := clean.Run(); e != nil { + // --rm already removes successfully finished containers. Confirm absence. + probe := dockerCommand(cleanCtx, bin, "container", "ls", "--all", "--filter", "name=^/"+name+"$", "--format", "{{.ID}}") + var check cappedWriter + probe.Stdout = &check + probe.Stderr = &cappedWriter{} + pe := probe.Run() + remaining, _ := check.snapshot() + if pe != nil || strings.TrimSpace(remaining) != "" { + runErr = errors.Join(runErr, errors.New("sandbox cleanup could not be verified; operator attention required")) + } + } + }() + // Image-declared volumes would allocate writable, unbounded daemon storage + // despite --read-only. Approved images must not declare any volumes. + inspect := dockerCommand(ctx, bin, "image", "inspect", "--format", "{{json .Config.Volumes}}", strings.TrimSpace(os.Getenv("ZAKURA_SANDBOX_IMAGE"))) + var imageVolumes cappedWriter + inspect.Stdout = &imageVolumes + inspect.Stderr = &cappedWriter{} + if err := inspect.Run(); err != nil { + return result, errors.New("sandbox image unavailable or policy inspection failed; host execution refused") + } + volumes, tooLarge := imageVolumes.snapshot() + if tooLarge || (strings.TrimSpace(volumes) != "null" && strings.TrimSpace(volumes) != "{}") { + return result, errors.New("sandbox image must not declare writable volumes") + } + // Creation is separate from start: a cancelled creation can at worst leave + // a stopped container, never a running untracked command. + create := dockerCommand(ctx, bin, args...) + create.Stdout = &cappedWriter{} + create.Stderr = errout + if err := create.Run(); err != nil { + result.ExitCode = -1 + result.Stderr, result.Truncated = errout.snapshot() + result.TimedOut = errors.Is(ctx.Err(), context.DeadlineExceeded) + result.Cancelled = errors.Is(ctx.Err(), context.Canceled) + if ctx.Err() != nil { + return result, errors.New("sandbox creation interrupted; a stopped container may require operator cleanup: " + name) + } + return result, fmt.Errorf("sandbox container creation failed; host execution refused: %w", err) + } + cmd := dockerCommand(ctx, bin, "start", "--attach", "--interactive", name) + cmd.Stdout = out + cmd.Stderr = errout + cmd.Stdin = strings.NewReader(p.Stdin) + e := cmd.Run() + result.Stdout, result.Truncated = out.snapshot() + var truncated bool + result.Stderr, truncated = errout.snapshot() + result.Truncated = result.Truncated || truncated + result.TimedOut = errors.Is(ctx.Err(), context.DeadlineExceeded) + result.Cancelled = errors.Is(ctx.Err(), context.Canceled) + if e != nil { + var exit *exec.ExitError + if errors.As(e, &exit) { + result.ExitCode = exit.ExitCode() + if result.ExitCode == 125 { + runErr = errors.New("sandbox container failed to start; host execution refused") + } + } else { + result.ExitCode = -1 + runErr = fmt.Errorf("sandbox execution failed: %w", e) + } + } + return result, runErr +} + +type JobSnap struct { + ID string `json:"id"` + Stdout string `json:"stdout"` + Stderr string `json:"stderr"` + ExitCode *int `json:"exitCode"` + Running bool `json:"running"` + TimedOut bool `json:"timedOut"` + Cancelled bool `json:"cancelled"` + Truncated bool `json:"truncated"` + Error string `json:"error,omitempty"` +} +type job struct { + mu sync.Mutex + id string + root string + out, errout cappedWriter + cancel context.CancelFunc + result *ExecResult + err error +} +type Registry struct { + mu sync.Mutex + jobs map[string]*job + next uint64 +} + +func NewRegistry() *Registry { return &Registry{jobs: make(map[string]*job)} } +func (r *Registry) Start(root string, p ExecParams) (*JobSnap, error) { + if _, err := buildArgs(root, p, "validation"); err != nil { + return nil, err + } + if _, err := exec.LookPath("docker"); err != nil { + return nil, errors.New("sandbox Docker backend unavailable; host execution refused") + } + r.mu.Lock() + defer r.mu.Unlock() + // Completed results are evicted before refusing further concurrent jobs. + if len(r.jobs) >= MaxJobs { + for id, j := range r.jobs { + j.mu.Lock() + done := j.result != nil + j.mu.Unlock() + if done { + delete(r.jobs, id) + } + } + } + if len(r.jobs) >= MaxJobs { + return nil, errors.New("sandbox concurrent job limit reached") + } + r.next++ + var random [16]byte + if _, err := rand.Read(random[:]); err != nil { + return nil, err + } + ctx, cancel := context.WithCancel(context.Background()) + j := &job{id: hex.EncodeToString(random[:]) + "-" + strconv.FormatUint(r.next, 10), root: root, cancel: cancel} + r.jobs[j.id] = j + go func() { + result, err := run(ctx, root, p, &j.out, &j.errout) + j.mu.Lock() + j.result = &result + j.err = err + j.mu.Unlock() + cancel() + }() + return j.snapshot(), nil +} +func (j *job) snapshot() *JobSnap { + j.mu.Lock() + defer j.mu.Unlock() + out, a := j.out.snapshot() + stderr, b := j.errout.snapshot() + s := &JobSnap{ID: j.id, Stdout: out, Stderr: stderr, Running: j.result == nil, Truncated: a || b} + if j.result != nil { + code := j.result.ExitCode + s.ExitCode = &code + s.TimedOut = j.result.TimedOut + s.Cancelled = j.result.Cancelled + } + if j.err != nil { + s.Error = j.err.Error() + } + return s +} +func (r *Registry) Get(id string) *JobSnap { + r.mu.Lock() + j := r.jobs[id] + r.mu.Unlock() + if j == nil { + return nil + } + return j.snapshot() +} +func (r *Registry) Kill(id string) *JobSnap { + r.mu.Lock() + j := r.jobs[id] + r.mu.Unlock() + if j == nil { + return nil + } + j.cancel() + return j.snapshot() +} + +// Scoped access binds a job to the validated caller workspace. +func (r *Registry) GetScoped(id, root string) *JobSnap { + r.mu.Lock() + j := r.jobs[id] + r.mu.Unlock() + if j == nil || j.root != root { + return nil + } + return j.snapshot() +} +func (r *Registry) KillScoped(id, root string) *JobSnap { + r.mu.Lock() + j := r.jobs[id] + r.mu.Unlock() + if j == nil || j.root != root { + return nil + } + j.cancel() + return j.snapshot() +} diff --git a/apps/agent/internal/sandbox/validation_test.go b/apps/agent/internal/sandbox/validation_test.go new file mode 100644 index 00000000..ab846426 --- /dev/null +++ b/apps/agent/internal/sandbox/validation_test.go @@ -0,0 +1,232 @@ +package sandbox + +import ( + "context" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func testPolicy(t *testing.T) string { + t.Helper() + t.Setenv("ZAKURA_SANDBOX_IMAGE", "zakura-test:local") + return t.TempDir() +} + +func TestSandboxRestrictiveArgumentPolicy(t *testing.T) { + root := testPolicy(t) + args, err := buildArgs(root, ExecParams{Command: []string{"printf", "%s", "hello"}}, "test-policy") + if err != nil { + t.Fatal(err) + } + for _, want := range []string{"--pull=never", "--network=none", "--read-only", "--user=65534:65534", "--cap-drop=ALL", "--security-opt=no-new-privileges:true", "--pids-limit=64", "--memory=512m", "--memory-swap=512m", "--cpus=1", "--ipc=none", "--log-driver=none", "--tmpfs=/tmp:rw,noexec,nosuid,nodev,size=64m,mode=1777"} { + found := false + for _, arg := range args { + if arg == want { + found = true + } + } + if !found { + t.Errorf("missing restriction %s", want) + } + } + joined := strings.Join(args, "\n") + if !strings.Contains(joined, "dst=/workspace,readonly,bind-propagation=rprivate") { + t.Error("workspace mount is not read-only/private") + } + if got := strings.Join(args[len(args)-3:], "|"); got != "zakura-test:local|%s|hello" { + t.Fatalf("command arguments changed: %s", got) + } +} + +func TestSandboxInputPolicyRejectsBeforeExecution(t *testing.T) { + root := testPolicy(t) + cases := map[string]ExecParams{ + "empty": {}, "empty executable": {Command: []string{""}}, + "too many args": {Command: make([]string, 257)}, + "oversize command": {Command: []string{strings.Repeat("x", 64*1024+1)}}, + "oversize stdin": {Command: []string{"printf"}, Stdin: strings.Repeat("x", MaxStdinBytes+1)}, + "negative timeout": {Command: []string{"printf"}, TimeoutMs: -1}, + "excessive timeout": {Command: []string{"printf"}, TimeoutMs: MaxTimeoutMs + 1}, + "custom environment": {Command: []string{"printf"}, Env: map[string]string{"EXAMPLE": "value"}}, + } + for name, p := range cases { + t.Run(name, func(t *testing.T) { + if _, err := buildArgs(root, p, "validation"); err == nil { + t.Fatal("invalid request accepted") + } + }) + } + if _, err := buildArgs(root, ExecParams{Command: []string{"printf"}, TimeoutMs: MaxTimeoutMs, Stdin: strings.Repeat("x", MaxStdinBytes)}, "boundary"); err != nil { + t.Fatal(err) + } +} + +func TestSandboxUnavailableFailsClosed(t *testing.T) { + root := testPolicy(t) + p := ExecParams{Command: []string{"printf", "hello"}} + t.Setenv("ZAKURA_SANDBOX_IMAGE", "") + if _, err := Run(context.Background(), root, p); err == nil { + t.Fatal("missing image accepted") + } + t.Setenv("ZAKURA_SANDBOX_IMAGE", "zakura-test:local") + t.Setenv("PATH", t.TempDir()) + if _, err := Run(context.Background(), root, p); err == nil || !strings.Contains(err.Error(), "host execution refused") { + t.Fatalf("missing Docker must fail closed: %v", err) + } + if _, err := NewRegistry().Start(root, p); err == nil { + t.Fatal("background execution accepted missing backend") + } +} + +func TestSandboxWorkingDirectoryMapping(t *testing.T) { + root := testPolicy(t) + if err := os.Mkdir(filepath.Join(root, "project"), 0755); err != nil { + t.Fatal(err) + } + args, err := buildArgs(root, ExecParams{Command: []string{"pwd"}, WorkingDir: "project"}, "workdir") + if err != nil { + t.Fatal(err) + } + for i, arg := range args { + if arg == "--workdir" && args[i+1] == "/workspace/project" { + return + } + } + t.Fatal("working directory was not mapped inside workspace") +} + +func TestSandboxOutputCapAndConcurrentSnapshots(t *testing.T) { + var w cappedWriter + input := []byte(strings.Repeat("a", MaxOutputBytes)) + if n, err := w.Write(input); n != len(input) || err != nil { + t.Fatalf("write: %d %v", n, err) + } + if _, truncated := w.snapshot(); truncated { + t.Fatal("exact boundary marked truncated") + } + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 20; j++ { + _, _ = w.Write([]byte("extra")) + _, _ = w.snapshot() + } + }() + } + wg.Wait() + output, truncated := w.snapshot() + if len(output) != MaxOutputBytes || !truncated { + t.Fatalf("cap failed: bytes=%d truncated=%v", len(output), truncated) + } +} + +// fakeDocker tests client orchestration only. It provides no container or OS isolation. +func fakeDocker(t *testing.T, runBody string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("synthetic POSIX client fixture") + } + dir := t.TempDir() + script := "#!/bin/sh\ncase \"$1\" in\nimage) printf 'null\\n' ;;\ncreate) exit 0 ;;\nstart) " + runBody + " ;;\nrm) exit 0 ;;\ncontainer) exit 0 ;;\n*) exit 1 ;;\nesac\n" + if err := os.WriteFile(filepath.Join(dir, "docker"), []byte(script), 0700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) +} + +func TestSandboxSyntheticClientTimeoutAndCancellation(t *testing.T) { + root := testPolicy(t) + fakeDocker(t, "exec /bin/sleep 30") + t.Run("timeout", func(t *testing.T) { + result, err := Run(context.Background(), root, ExecParams{Command: []string{"sleep", "30"}, TimeoutMs: 30}) + if err != nil { + t.Fatal(err) + } + if !result.TimedOut || result.Cancelled { + t.Fatalf("wrong timeout state: %+v", result) + } + }) + t.Run("cancel", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + result, _ := Run(ctx, root, ExecParams{Command: []string{"sleep", "30"}}) + if !result.Cancelled || result.TimedOut { + t.Fatalf("wrong cancel state: %+v", result) + } + }) +} + +func TestSandboxSyntheticClientQuotaAndScopedPermission(t *testing.T) { + root := testPolicy(t) + fakeDocker(t, "exit 0") + registry := NewRegistry() + for i := 0; i < MaxJobs; i++ { + id := string(rune(i + 1)) + registry.jobs[id] = &job{id: id, root: root, cancel: func() {}} + } + if _, err := registry.Start(root, ExecParams{Command: []string{"printf", "hello"}}); err == nil || !strings.Contains(err.Error(), "limit") { + t.Fatalf("concurrent quota not enforced: %v", err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + registry.jobs["scoped"] = &job{id: "scoped", root: root, cancel: cancel} + if registry.GetScoped("scoped", "other-workspace") != nil || registry.KillScoped("scoped", "other-workspace") != nil { + t.Fatal("cross-workspace job exposed") + } + if ctx.Err() != nil { + t.Fatal("cross-workspace kill cancelled job") + } + if registry.GetScoped("scoped", root) == nil || registry.KillScoped("scoped", root) == nil { + t.Fatal("owner cannot access job") + } + if ctx.Err() != context.Canceled { + t.Fatal("owner cancellation not delivered") + } +} + +func TestSandboxDockerClientDoesNotInheritSecrets(t *testing.T) { + t.Setenv("ZAKURA_TEST_SECRET", "do-not-forward") + t.Setenv("DOCKER_HOST", "example.invalid") + cmd := dockerCommand(context.Background(), "docker", "version") + for _, entry := range cmd.Env { + if strings.HasPrefix(entry, "ZAKURA_TEST_SECRET=") || strings.HasPrefix(entry, "DOCKER_HOST=") { + t.Fatalf("inherited disallowed environment: %s", entry) + } + } + if cmd.WaitDelay <= 0 || cmd.WaitDelay > 5*time.Second { + t.Fatal("client wait is not bounded") + } +} + +func TestSandboxGlobalExecutionQuota(t *testing.T) { + for i := 0; i < MaxConcurrent; i++ { + executionSlots <- struct{}{} + } + defer func() { + for i := 0; i < MaxConcurrent; i++ { + <-executionSlots + } + }() + if _, err := Run(context.Background(), t.TempDir(), ExecParams{Command: []string{"printf", "hello"}}); err == nil || !strings.Contains(err.Error(), "concurrent execution limit") { + t.Fatalf("global quota not enforced: %v", err) + } +} + +func TestSandboxImageVolumesFailClosed(t *testing.T) { + root := testPolicy(t) + fakeDocker(t, "exit 0") + path := filepath.Join(os.Getenv("PATH"), "docker") + if err := os.WriteFile(path, []byte("#!/bin/sh\ncase \"$1\" in\nimage) printf '{\"/data\":{}}\\n' ;;\n*) exit 1 ;;\nesac\n"), 0700); err != nil { + t.Fatal(err) + } + if _, err := Run(context.Background(), root, ExecParams{Command: []string{"printf", "hello"}}); err == nil || !strings.Contains(strings.ToLower(err.Error()), "volume") { + t.Fatalf("image with writable volume accepted: %v", err) + } +} diff --git a/apps/server/internal/runtime/acp.go b/apps/server/internal/runtime/acp.go index 2b8ff833..5a00f01c 100644 --- a/apps/server/internal/runtime/acp.go +++ b/apps/server/internal/runtime/acp.go @@ -112,6 +112,13 @@ func findAdapter(id string) (acpAdapter, bool) { return acpAdapter{}, false } func (h *handler) runtimeExec(ctx context.Context, tenant, agent, command string, args ...string) (map[string]any, error) { + return h.runtimeExecWithMode(ctx, tenant, agent, "", command, args...) +} + +func (h *handler) runtimeExecWithMode(ctx context.Context, tenant, agent, mode, command string, args ...string) (map[string]any, error) { + if mode != "" && mode != "host" && mode != "sandbox" { + return nil, errors.New("execution_mode must be host or sandbox") + } var nodeID, spaceID, workspaceKind string var rec struct { NodeID string `gorm:"column:node_id"` @@ -123,20 +130,40 @@ func (h *handler) runtimeExec(ctx context.Context, tenant, agent, command string return nil, errors.New("agent runtime node is not online") } nodeID, spaceID, workspaceKind = rec.NodeID, rec.SpaceID, rec.WorkspaceKind + if mode == "sandbox" && workspaceKind != "host" { + return nil, errors.New("sandbox execution requires a host workspace; this workspace mode is unsupported") + } session, err := h.hub.get(nodeID) if err != nil { return nil, err } + if mode == "sandbox" { + var policy struct { + Sandbox struct { + Enabled bool `json:"enabled"` + } `json:"sandbox"` + } + if err := session.call(ctx, "sandbox.policy", map[string]any{}, &policy); err != nil || !policy.Sandbox.Enabled { + return nil, errors.New("runner does not support sandbox execution; upgrade or configure the runner") + } + } argv := append([]string{command}, args...) timeoutMS := int64(30_000) if deadline, ok := ctx.Deadline(); ok { - if remaining := time.Until(deadline).Milliseconds(); remaining > timeoutMS { + if remaining := time.Until(deadline).Milliseconds(); remaining > 0 { timeoutMS = remaining + } else { + return nil, context.DeadlineExceeded } } result := map[string]any{} if workspaceKind == "host" { - err = session.call(ctx, "host.exec", map[string]any{"spaceId": spaceID, "command": argv, "workingDir": "/workspace", "timeoutMs": timeoutMS}, &result) + params := map[string]any{"spaceId": spaceID, "command": argv, "workingDir": "/workspace", "timeoutMs": timeoutMS, "executionMode": mode} + if mode == "sandbox" { + result, err = runSandboxCommand(ctx, session, params) + } else { + err = session.call(ctx, "host.exec", params, &result) + } } else { var containers []struct { DockerID string `json:"dockerId"` @@ -158,6 +185,13 @@ func (h *handler) runtimeExec(ctx context.Context, tenant, agent, command string if err != nil { return nil, err } + if mode == "sandbox" && (result["executionMode"] != "sandbox" || result["isolated"] != true) { + return nil, errors.New("runner did not confirm sandbox execution") + } + if result["executionMode"] == nil { + result["executionMode"] = "host" + result["isolated"] = false + } if code, ok := result["exitCode"].(float64); ok && code != 0 { return result, fmt.Errorf("command exited %d: %v", int(code), result["stderr"]) } diff --git a/apps/server/internal/runtime/acp_runtime.go b/apps/server/internal/runtime/acp_runtime.go index 58d9c365..d69d63ce 100644 --- a/apps/server/internal/runtime/acp_runtime.go +++ b/apps/server/internal/runtime/acp_runtime.go @@ -89,6 +89,13 @@ func (m *acpRuntimeManager) closeAll() { } func (m *acpRuntimeManager) ensure(ctx context.Context, tenantID, agentID, sid string) (*acpLiveRuntime, error) { + required, policyErr := m.h.agentSandboxRequired(ctx, tenantID, agentID) + if policyErr != nil { + return nil, policyErr + } + if required { + return nil, errors.New("ACP adapters are unavailable for sandbox agents") + } key := tenantID + "\x00" + sid m.mu.Lock() if current := m.runtimes[key]; current != nil { diff --git a/apps/server/internal/runtime/agent_tool_runners.go b/apps/server/internal/runtime/agent_tool_runners.go index 988a635c..81b88bc8 100644 --- a/apps/server/internal/runtime/agent_tool_runners.go +++ b/apps/server/internal/runtime/agent_tool_runners.go @@ -253,6 +253,12 @@ func (h *handler) runFSWrite(ctx context.Context, tenant, agent string, args map } func (h *handler) runShellExec(ctx context.Context, tenant, agent string, args map[string]any) (json.RawMessage, error) { + if value, exists := args["execution_mode"]; exists { + mode, ok := value.(string) + if !ok || (mode != "host" && mode != "sandbox") { + return nil, errors.New("execution_mode must be host or sandbox") + } + } command := builtinStringArg(args, "command") if strings.TrimSpace(command) == "" { return nil, errors.New("command is required") @@ -266,7 +272,7 @@ func (h *handler) runShellExec(ctx context.Context, tenant, agent string, args m } callCtx, cancel := context.WithTimeout(ctx, time.Duration(timeoutMS)*time.Millisecond) defer cancel() - result, err := h.runtimeExec(callCtx, tenant, agent, "bash", "-lc", command) + result, err := h.runtimeExecWithMode(callCtx, tenant, agent, builtinStringArg(args, "execution_mode"), "bash", "-lc", command) if result == nil { if err != nil { return nil, err @@ -280,8 +286,13 @@ func (h *handler) runShellExec(ctx context.Context, tenant, agent string, args m stdout, _ = h.truncateToolText(ctx, tenant, agent, stdout, "shell") stderr, _ = h.truncateToolText(ctx, tenant, agent, stderr, "shell") return builtinJSON(map[string]any{ - "stdout": stdout, - "stderr": stderr, - "exitCode": result["exitCode"], + "stdout": stdout, + "stderr": stderr, + "exitCode": result["exitCode"], + "executionMode": result["executionMode"], + "isolated": result["isolated"], + "timedOut": result["timedOut"], + "cancelled": result["cancelled"], + "truncated": result["truncated"], }) } diff --git a/apps/server/internal/runtime/agent_tools.go b/apps/server/internal/runtime/agent_tools.go index 8f50d0d9..95481065 100644 --- a/apps/server/internal/runtime/agent_tools.go +++ b/apps/server/internal/runtime/agent_tools.go @@ -266,6 +266,13 @@ func (h *handler) agentMCPCatalogTools(ctx context.Context, tenant, agentID, spa } func (h *handler) agentToolCatalog(ctx context.Context, tenant, agentID string) (catalog agentCatalog, err error) { + sandbox, policyErr := h.agentSandboxRequired(ctx, tenant, agentID) + if policyErr != nil { + return agentCatalog{}, policyErr + } + if sandbox { + return sandboxAgentCatalog(), nil + } agent, err := h.store.GetAgent(ctx, tenant, agentID) if err != nil { return agentCatalog{}, err @@ -308,9 +315,10 @@ func (h *handler) agentToolCatalog(ctx context.Context, tenant, agentID string) "path": map[string]any{"type": "string"}, "content": map[string]any{"type": "string"}, }, "path", "content"), - directBuiltin("shell_exec", "Run a shell command in the workspace environment.", map[string]any{ - "command": map[string]any{"type": "string", "description": "Shell command to run in the workspace."}, - "timeout_ms": map[string]any{"type": "integer", "description": "Deadline in ms. Default 60000, max 300000."}, + directBuiltin("shell_exec", "Run a shell command. Host mode is UNSANDBOXED. Sandbox mode uses a restricted, read-only workspace with no network and requires a configured runner.", map[string]any{ + "command": map[string]any{"type": "string", "description": "Shell command to run in the workspace."}, + "execution_mode": map[string]any{"type": "string", "enum": []string{"host", "sandbox"}, "description": "Explicitly select sandbox isolation or legacy UNSANDBOXED host execution. Runner enforcement cannot be disabled by this setting."}, + "timeout_ms": map[string]any{"type": "integer", "description": "Deadline in ms. Default 60000, max 300000."}, }, "command"), directBuiltin("codemode", "Run JavaScript that calls the agent's other tools. The script runs as the body of an async function (top-level await and return allowed) inside the workspace. Call tools as async functions on the tools object, e.g. const r = await tools.mcp__github__search_issues({query: \"x\"}). Use text(value) to append output; return a value to finish. Compose calls and filter results so only what you need comes back.", map[string]any{ "code": map[string]any{"type": "string", "description": "JavaScript source."}, @@ -474,6 +482,13 @@ type cachedCatalog struct { } func (h *handler) cachedAgentToolCatalog(ctx context.Context, tenant, agentID string) (agentCatalog, error) { + sandbox, policyErr := h.agentSandboxRequired(ctx, tenant, agentID) + if policyErr != nil { + return agentCatalog{}, policyErr + } + if sandbox { + return sandboxAgentCatalog(), nil + } key := tenant + "/" + agentID h.agentToolMu.Lock() if h.agentToolCache != nil { diff --git a/apps/server/internal/runtime/sandbox_exec.go b/apps/server/internal/runtime/sandbox_exec.go new file mode 100644 index 00000000..65b9797d --- /dev/null +++ b/apps/server/internal/runtime/sandbox_exec.go @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "context" + "errors" + "fmt" + "time" +) + +// Use the runner's scoped job lifecycle so cancelling an agent run also cancels +// its container. Cleanup has a separate deadline and never falls back to host. +func runSandboxCommand(ctx context.Context, runner *runnerSession, params map[string]any) (result map[string]any, err error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + result = map[string]any{} + startCtx, stopStart := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + err = runner.call(startCtx, "host.exec.start", params, &result) + stopStart() + if err != nil { + return nil, fmt.Errorf("sandbox start could not be confirmed; any started job remains bounded by its timeout: %w", err) + } + id, _ := result["id"].(string) + if id == "" { + return nil, errors.New("runner did not return a sandbox job identity") + } + scoped := map[string]any{"id": id, "spaceId": params["spaceId"], "executionMode": "sandbox"} + running := true + defer func() { + if !running { + return + } + cleanup, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if cleanupErr := cancelSandboxJob(cleanup, runner, scoped); cleanupErr != nil { + result = nil + err = errors.Join(err, errors.New("sandbox cancellation could not be confirmed; the job remains bounded by its timeout")) + } + }() + for { + if result["executionMode"] != "sandbox" || result["isolated"] != true { + return nil, errors.New("runner did not confirm sandbox execution") + } + active, ok := result["running"].(bool) + if !ok { + return nil, errors.New("runner returned invalid sandbox lifecycle status") + } + if !active { + if failure, _ := result["error"].(string); failure != "" { + return nil, errors.New("sandbox execution failed; runner configuration or cleanup requires attention") + } + if result["exitCode"] == nil { + return nil, errors.New("sandbox ended without an exit status") + } + running = false + return result, nil + } + timer := time.NewTimer(100 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return nil, fmt.Errorf("sandbox run interrupted: %w", ctx.Err()) + case <-timer.C: + } + result = map[string]any{} + if err = runner.call(ctx, "host.exec.get", scoped, &result); err != nil { + return nil, err + } + } +} + +func cancelSandboxJob(ctx context.Context, runner *runnerSession, scoped map[string]any) error { + method := "host.exec.kill" + for { + var state map[string]any + if err := runner.call(ctx, method, scoped, &state); err != nil { + return err + } + if state["executionMode"] != "sandbox" || state["isolated"] != true { + return errors.New("unconfirmed sandbox cancellation") + } + running, ok := state["running"].(bool) + if !ok { + return errors.New("invalid sandbox cancellation status") + } + if !running { + if failure, _ := state["error"].(string); failure != "" { + return errors.New("sandbox cleanup was not confirmed") + } + return nil + } + timer := time.NewTimer(100 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + method = "host.exec.get" + } +} diff --git a/apps/server/internal/runtime/sandbox_policy.go b/apps/server/internal/runtime/sandbox_policy.go new file mode 100644 index 00000000..bb8c4165 --- /dev/null +++ b/apps/server/internal/runtime/sandbox_policy.go @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "context" + "encoding/json" + "errors" + "fmt" +) + +// This policy lives in the tenant-owned agent configuration, not tool arguments. +// All tools are denied by default; only the bounded execution transport is +// supported. It deliberately makes no claim to isolate arbitrary ACP adapters. +func (h *handler) agentSandboxRequired(ctx context.Context, tenant, agent string) (bool, error) { + record, err := h.store.GetAgent(ctx, tenant, agent) + if err != nil { + return false, err + } + var config map[string]json.RawMessage + if len(record.Config) > 0 && json.Unmarshal(record.Config, &config) != nil { + return false, errors.New("invalid agent execution policy") + } + raw, present := config["executionMode"] + if !present { + return false, nil + } + var mode string + if json.Unmarshal(raw, &mode) != nil || (mode != "host" && mode != "sandbox") { + return false, errors.New("agent executionMode must be host or sandbox") + } + return mode == "sandbox", nil +} + +func (h *handler) sandboxToolPolicy(ctx context.Context, tenant, agent, name string, args json.RawMessage) (json.RawMessage, error) { + required, err := h.agentSandboxRequired(ctx, tenant, agent) + if err != nil { + return nil, err + } + if !required { + return args, nil + } + if name == "ask_user" { + return args, nil + } + if name != "shell_exec" { + return nil, fmt.Errorf("tool %s is unavailable for sandbox agents", name) + } + var parsed map[string]any + if err := json.Unmarshal(args, &parsed); err != nil || parsed == nil { + return nil, errors.New("invalid sandbox tool arguments") + } + parsed["execution_mode"] = "sandbox" + return json.Marshal(parsed) +} + +func sandboxAgentCatalog() agentCatalog { + return agentCatalog{Tools: []agentTool{directBuiltin("shell_exec", "Execute in the configured restricted sandbox. Workspace is read-only; only bounded /tmp is writable. No network. Only shell_exec and ask_user are allowed; ACP adapters are unavailable.", map[string]any{ + "command": map[string]any{"type": "string"}, + "timeout_ms": map[string]any{"type": "integer", "description": "Deadline in ms, maximum 300000."}, + }, "command"), directBuiltin("ask_user", "Ask the user a question and wait for their reply.", map[string]any{"question": map[string]any{"type": "string"}, "title": map[string]any{"type": "string"}}, "question")}} +} diff --git a/apps/server/internal/runtime/sandbox_policy_test.go b/apps/server/internal/runtime/sandbox_policy_test.go new file mode 100644 index 00000000..3a4071c7 --- /dev/null +++ b/apps/server/internal/runtime/sandbox_policy_test.go @@ -0,0 +1,169 @@ +package runtime + +import ( + "context" + "encoding/json" + "testing" +) + +func TestSandboxAgentPolicyForcesShellAndDeniesOtherTools(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + store := NewStore(d) + space, err := store.CreateSpace(context.Background(), "tenant", Space{Name: "sandbox"}) + if err != nil { + t.Fatal(err) + } + agent, err := store.CreateAgent(context.Background(), "tenant", Agent{Name: "sandbox", SpaceID: space.ID, Config: json.RawMessage(`{"executionMode":"sandbox"}`)}) + if err != nil { + t.Fatal(err) + } + h := &handler{deps: d, store: store} + raw, err := h.sandboxToolPolicy(context.Background(), "tenant", agent.ID, "shell_exec", json.RawMessage(`{"command":"echo hello","execution_mode":"host"}`)) + if err != nil { + t.Fatal(err) + } + var args map[string]any + _ = json.Unmarshal(raw, &args) + if args["execution_mode"] != "sandbox" { + t.Fatalf("model bypassed sandbox: %s", raw) + } + for _, name := range []string{"fs_read", "fs_write", "apply_patch", "codemode", "delegate_agent", "browser_open", "computer_click", "mcp__evil__shell_exec", "instance:shell_exec", " shell_exec", "SHELL_EXEC", "unknown_future_tool"} { + if _, err := h.dispatchAgentTool(context.Background(), "tenant", agent.ID, "", "", name, json.RawMessage(`{}`)); err == nil { + t.Fatalf("allowed %s", name) + } + } + if _, err := h.sandboxToolPolicy(context.Background(), "other-tenant", agent.ID, "shell_exec", json.RawMessage(`{}`)); err == nil { + t.Fatal("cross-tenant agent allowed") + } + catalog, err := h.cachedAgentToolCatalog(context.Background(), "tenant", agent.ID) + if err != nil { + t.Fatal(err) + } + if len(catalog.Tools) != 2 { + t.Fatalf("unexpected sandbox catalog: %+v", catalog) + } + for _, tool := range catalog.Tools { + if tool.Name != "shell_exec" && tool.Name != "ask_user" { + t.Fatalf("unsafe tool: %s", tool.Name) + } + } + manager := newACPRuntimeManager(h) + if _, err := manager.ensure(context.Background(), "tenant", agent.ID, "sid"); err == nil { + t.Fatal("sandbox ACP allowed") + } + for _, bad := range []any{"invalid", false, nil} { + _, err = store.UpdateAgent(context.Background(), "tenant", agent.ID, map[string]any{"config": map[string]any{"executionMode": bad}}) + if err != nil { + t.Fatal(err) + } + if _, err = h.agentSandboxRequired(context.Background(), "tenant", agent.ID); err == nil { + t.Fatalf("invalid mode accepted: %#v", bad) + } + } +} + +func TestSandboxShellUsesPreflightAndNeverFallsBack(t *testing.T) { + for _, scenario := range []string{"supported", "old_runner", "mismatch", "cleanup_error"} { + t.Run(scenario, func(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + store := NewStore(d) + node := "node" + space, err := store.CreateSpace(context.Background(), "tenant", Space{Name: "S", RuntimeNodeID: &node, WorkspaceKind: "host"}) + if err != nil { + t.Fatal(err) + } + agent, err := store.CreateAgent(context.Background(), "tenant", Agent{Name: "A", SpaceID: space.ID}) + if err != nil { + t.Fatal(err) + } + calls := 0 + h := builtinToolHarness(t, d, "rnr_sandbox", func(method string, p map[string]any) (any, error) { + switch method { + case "sys.info": + return map[string]any{"version": "test", "kind": "computer", "storageRoot": "/srv/zakura", "capabilities": map[string]any{}, "hostInfo": map[string]any{}}, nil + case "sandbox.policy": + return map[string]any{"sandbox": map[string]any{"enabled": scenario != "old_runner"}}, nil + case "host.exec.start": + calls++ + if p["executionMode"] != "sandbox" || p["spaceId"] != space.ID { + t.Errorf("unsafe dispatch: %#v", p) + } + if scenario == "cleanup_error" { + return map[string]any{"id": "job", "running": false, "executionMode": "sandbox", "isolated": true, "exitCode": 0, "error": "cleanup failure"}, nil + } + if scenario == "mismatch" { + return map[string]any{"id": "job", "running": false, "executionMode": "host", "isolated": false, "exitCode": 0}, nil + } + return map[string]any{"id": "job", "running": false, "executionMode": "sandbox", "isolated": true, "exitCode": 0, "stdout": "hello", "stderr": "", "truncated": true}, nil + case "host.exec.kill": + return map[string]any{"running": false, "executionMode": "sandbox", "isolated": true}, nil + default: + t.Errorf("unexpected RPC: %s", method) + return nil, nil + } + }) + raw, err := h.runShellExec(context.Background(), "tenant", agent.ID, map[string]any{"command": "echo hello", "execution_mode": "sandbox"}) + if scenario == "supported" { + if err != nil { + t.Fatal(err) + } + var result map[string]any + _ = json.Unmarshal(raw, &result) + if result["executionMode"] != "sandbox" || result["truncated"] != true { + t.Fatalf("lost policy/output state: %s", raw) + } + if calls != 1 { + t.Fatalf("calls %d", calls) + } + } else { + if err == nil { + t.Fatalf("unconfirmed sandbox result accepted: %s", raw) + } + if scenario == "old_runner" && calls != 0 { + t.Fatal("old runner executed command") + } + } + }) + } +} + +func TestSandboxCancellationUsesIndependentCleanupContext(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant") + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + killed := make(chan map[string]any, 1) + h := builtinToolHarness(t, d, "rnr_cancel", func(method string, p map[string]any) (any, error) { + switch method { + case "sys.info": + return map[string]any{"version": "test", "kind": "computer", "storageRoot": "/srv/zakura", "capabilities": map[string]any{}, "hostInfo": map[string]any{}}, nil + case "host.exec.start": + cancel() + return map[string]any{"id": "job", "executionMode": "sandbox", "isolated": true, "running": true, "exitCode": nil}, nil + case "host.exec.kill": + killed <- p + return map[string]any{"id": "job", "executionMode": "sandbox", "isolated": true, "running": false, "exitCode": 137}, nil + default: + t.Errorf("unexpected RPC: %s", method) + return nil, nil + } + }) + runner, err := h.hub.get("node") + if err != nil { + t.Fatal(err) + } + _, err = runSandboxCommand(ctx, runner, map[string]any{"spaceId": "space", "executionMode": "sandbox", "command": []string{"true"}}) + if err == nil { + t.Fatal("cancelled context succeeded") + } + select { + case p := <-killed: + if p["spaceId"] != "space" || p["executionMode"] != "sandbox" || p["id"] != "job" { + t.Fatalf("unscoped cleanup: %#v", p) + } + default: + t.Fatal("cancel did not stop job") + } +} diff --git a/apps/server/internal/runtime/tool_session_state.go b/apps/server/internal/runtime/tool_session_state.go index ea5f0551..dde6d961 100644 --- a/apps/server/internal/runtime/tool_session_state.go +++ b/apps/server/internal/runtime/tool_session_state.go @@ -25,6 +25,11 @@ func isBuiltinToolName(name string) bool { } func (h *handler) dispatchAgentTool(ctx context.Context, tenant, agent, session, toolCallID, name string, args json.RawMessage) (json.RawMessage, error) { + var policyErr error + args, policyErr = h.sandboxToolPolicy(ctx, tenant, agent, name, args) + if policyErr != nil { + return nil, policyErr + } if toolDisabled(ctx, name) { return nil, fmt.Errorf("tool %s is disabled for this run", name) } diff --git a/docs/sandbox.md b/docs/sandbox.md new file mode 100644 index 00000000..e508853e --- /dev/null +++ b/docs/sandbox.md @@ -0,0 +1,78 @@ +# Agent execution sandbox + +The Go agent supports an explicit Docker-backed execution mode. Legacy host execution remains available and **is not isolated**. Path validation on a host working directory is not a sandbox. + +## Selecting the mode + +For an agent-wide tool boundary, set the agent's persisted `config.executionMode` to `"sandbox"` through the existing authenticated agent configuration PATCH API, and configure the runner image below. The server rereads the tenant-scoped agent configuration on every tool invocation. It forces `shell_exec` into sandbox mode even if model arguments request host mode; only `ask_user` is otherwise permitted. Arbitrary MCP tools, filesystem tools, browser tools, code mode, delegation, and service tools are denied. The tool catalog is limited to `shell_exec` and `ask_user`; ACP startup/reuse is refused. Invalid configuration modes fail closed. Omitting the agent configuration keeps legacy host behavior. + +Enable sandbox mode before starting agent runs. Changing the policy does not retroactively stop existing host jobs or ACP processes; stop those separately before relying on the new boundary. + +This is separate from choosing sandbox mode on an individual shell command. Manual user filesystem/admin APIs are outside the agent tool boundary, and configured model providers still receive prompts and conversation content. Sandbox mode is not a promise that no data leaves the application. + + +- `shell_exec` accepts `execution_mode: "sandbox"` or `"host"`. The server checks the runner's `sandbox.policy` capability before requesting sandbox execution, so an older runner cannot silently ignore the mode. +- Agent RPC `host.exec`, `host.exec.start`, `host.exec.get`, and `host.exec.kill` accept `executionMode: "sandbox"`. Supply the same valid `spaceId` and execution mode when polling or cancelling a job. +- Setting `ZAKURA_SANDBOX_ENABLED=true` on the agent enforces sandbox mode when its handler is created. A request for host mode cannot disable operator enforcement. Without enforcement, omitted execution mode preserves host compatibility. +- Results disclose `executionMode` and `isolated`; sandbox execution adds `timedOut`, `cancelled`, and `truncated`. Background jobs also report operational errors. +- `sandbox.policy` describes the configured policy, default mode, and enforcement. Image configuration is not evidence that the Docker daemon or image is usable. +- Sandbox mode currently supports host workspaces only. Unsupported workspace backends, PTY sessions, and Docker execution/management transports are refused rather than silently downgraded. + +## Operator prerequisites + +Use a trusted, local Linux Docker daemon with a current engine supporting `bind-recursive=disabled`. The daemon must share the agent's filesystem. The agent does not forward `DOCKER_HOST`, context overrides, credentials, proxies, or application environment to the Docker client. + +Provision an approved local image in advance and set `ZAKURA_SANDBOX_IMAGE` on the agent. Pin a reviewed image digest for reproducibility. Execution uses `--pull=never`; it does not pull images. The image must include the executable and supporting files the command needs, contain no application secrets, and declare no Docker `VOLUME` paths. The runtime inspects and refuses images declaring volumes. Image-baked environment and image content are trusted operator inputs, so a clean parent environment does not sanitize a secret-bearing image. + +Workspace files must be readable by UID/GID 65534. Workspace roots must use real directories; sockets, devices and FIFOs are rejected. The operator must prevent concurrent host-side mutations while execution runs. Path and file-type checks have time-of-check/time-of-use limitations; they are not an independent isolation boundary. Other agent file or management APIs remain separately authorized control-plane operations: this feature is a command-execution boundary, not a replacement for control-plane authentication and authorization. + +## Fixed restrictions + +| Resource | Policy | +| --- | --- | +| Network | `none`; no external network interface | +| User | UID/GID 65534, all capabilities dropped, no new privileges | +| Filesystem | Read-only image and read-only `/workspace` bind; nested mounts excluded | +| Writable scratch | Ephemeral `/tmp`, 64 MiB, noexec/nosuid/nodev | +| Memory / swap | 512 MiB memory, no additional swap | +| CPU / processes | 1 CPU, 64 PIDs | +| Open files / core | 256 open files; core dumps disabled | +| Execution timeout | Default and maximum 300,000 ms | +| Captured output | 256 KiB per stdout/stderr stream, then discarded with truncation flag | +| Input | 64 KiB stdin, 64 KiB combined command strings, 256 command arguments | +| Concurrency | 4 active executions; 128 retained/background job records with completed-result eviction | +| Environment | No caller-supplied environment; fixed HOME/TMPDIR/PATH | + +Read-only workspace means build/install workflows must use `/tmp` and cannot persist output back into the project through this API. Runtime resource flags depend on actual Docker/kernel enforcement; argument-policy unit tests alone do not establish enforcement. + +## Failure and lifecycle behavior + +The server uses workspace-scoped background start/get/kill RPCs for sandbox commands. Cancelling an agent run sends a scoped kill and waits up to five seconds for a terminal acknowledgment. Cleanup or terminal execution errors are surfaced, and an unconfirmed cancellation is reported as uncertain rather than successful. + +Starting a job uses a separate ten-second deadline so that an agent-run cancellation does not immediately discard the job identity needed for cleanup. If the start response is lost or cannot be confirmed, the server does not retry: the outcome is unknown, and any started job remains bounded by its hard execution timeout. Operator follow-up may still be needed when connectivity or daemon failures prevent cleanup confirmation. + +Missing configuration, unavailable Docker, image inspection failure, invalid inputs, unsupported isolation options, or container creation failures return errors without executing the command on the host. Container creation and execution are separate. Cancellation during creation may leave a stopped container and reports that uncertainty; it must not start an untracked command. + +Timeouts and cancellation terminate the client, then force-remove the named container using a separate bounded cleanup context. If removal fails, the runtime checks container absence. An inability to verify cleanup is returned as an operational error requiring operator attention. This is best-effort cleanup under daemon failures, not a guarantee against daemon outages. Do not treat a cancelled job as fully cleaned up when its error reports otherwise. + +## Validation + +From `apps/agent`: + +```sh +go test -race ./... +go vet ./... +``` + +`validation_test.go` covers restrictive Docker arguments, request bounds, missing-backend refusal, output bounds under concurrent access, workspace mapping, job quotas, workspace-scoped access, clean Docker client environment, and synthetic timeout/cancellation. The synthetic Docker fixture only tests client orchestration; it does not launch containers or prove OS isolation. RPC tests cover policy enforcement, unsupported transports, missing workspace identity, and fail-closed configuration. + +A separate integration test uses a **real Docker daemon** and benign commands. On a dedicated Docker-capable test host, pre-pull an approved Alpine-compatible image, set its pinned reference, and run: + +```sh +ZAKURA_SANDBOX_INTEGRATION=1 ZAKURA_SANDBOX_IMAGE='' \ + go test ./internal/sandbox -run '^TestSandboxRealDockerIntegration$' -count=1 -v +``` + +The image needs `sh`, `cat`, `id`, `pwd`, `touch`, `ls`, `head`, and `sleep`. The test checks workspace readability, non-root user, denied workspace writes, ephemeral scratch, clean parent environment, loopback-only networking, capped output, timeout/cancellation and absence of newly remaining sandbox containers. Run without concurrent sandbox workloads so cleanup assertions are meaningful. Opt-in with missing Docker/image fails rather than skips. Without opt-in it explicitly skips. + +The development executor had no Docker CLI or daemon access, so real Docker isolation was **not locally verified**. The dedicated CI integration stage must pass on the exact change before claiming real-backend validation. These tests are defensive behavior checks; they do not constitute a sandbox-escape assessment or production certification. From b9934b43ef5438ddfe5874cf6546d22bdc8cce83 Mon Sep 17 00:00:00 2001 From: momo-mnsjtxy <122842784+momo-mnsjtxy@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:16:27 +0800 Subject: [PATCH 2/2] Fix security finding acf_403793664d1543ce9aaf4cb2a5d68d4d --- .../internal/runtime/runtime_nodes_extra.go | 33 ++++++++++++- .../runtime_update_authorization_test.go | 48 +++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 apps/server/internal/runtime/runtime_update_authorization_test.go diff --git a/apps/server/internal/runtime/runtime_nodes_extra.go b/apps/server/internal/runtime/runtime_nodes_extra.go index ba7b335f..8ed7fd19 100644 --- a/apps/server/internal/runtime/runtime_nodes_extra.go +++ b/apps/server/internal/runtime/runtime_nodes_extra.go @@ -335,6 +335,23 @@ func runnerShellInstaller(server, token, kind, prelude string) string { } func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'" } + +var errRuntimeNodeUpdateForbidden = errors.New("platform admin required") + +func (h *handler) authorizeRuntimeNodeUpdate(ctx context.Context, actor httpx.Principal, nodeID string) error { + if !actor.IsPlatformAdmin { + return errRuntimeNodeUpdateForbidden + } + var count int64 + if err := h.deps.Gorm.WithContext(ctx).Table("runtime_nodes").Where("tenant_id=? AND id=?", actor.TenantID, nodeID).Count(&count).Error; err != nil { + return err + } + if count != 1 { + return ErrNotFound + } + return nil +} + func (h *handler) getRuntimeNodeMap(r *http.Request) (map[string]any, error) { node, err := scanRuntimeNode(h.deps.Gorm.WithContext(r.Context()).Raw(`SELECT id,name,slug,kind,status,endpoint,capabilities_json,host_info_json,storage_root,agent_version,last_seen_at,labels_json,is_shared,created_at,updated_at FROM runtime_nodes WHERE (tenant_id=? OR is_shared=true) AND id=?`, principal(r).TenantID, chi.URLParam(r, "id")).Row()) if err == nil { @@ -426,6 +443,14 @@ func (h *handler) runtimeNodeVersion(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, http.StatusOK, result) } func (h *handler) runtimeUpdateInfo(w http.ResponseWriter, r *http.Request) { + if err := h.authorizeRuntimeNodeUpdate(r.Context(), principal(r), chi.URLParam(r, "id")); err != nil { + if errors.Is(err, errRuntimeNodeUpdateForbidden) { + httpx.Error(w, http.StatusForbidden, err.Error()) + } else { + statusErr(w, err) + } + return + } id := r.URL.Query().Get("id") if id == "" { httpx.Error(w, http.StatusBadRequest, "id required") @@ -441,8 +466,12 @@ func (h *handler) runtimeUpdateInfo(w http.ResponseWriter, r *http.Request) { httpx.JSON(w, http.StatusOK, map[string]any{"update": job}) } func (h *handler) runtimeUpdateRunner(w http.ResponseWriter, r *http.Request) { - if _, err := h.getRuntimeNodeMap(r); err != nil { - statusErr(w, err) + if err := h.authorizeRuntimeNodeUpdate(r.Context(), principal(r), chi.URLParam(r, "id")); err != nil { + if errors.Is(err, errRuntimeNodeUpdateForbidden) { + httpx.Error(w, http.StatusForbidden, err.Error()) + } else { + statusErr(w, err) + } return } session, err := h.hub.get(chi.URLParam(r, "id")) diff --git a/apps/server/internal/runtime/runtime_update_authorization_test.go b/apps/server/internal/runtime/runtime_update_authorization_test.go new file mode 100644 index 00000000..24254950 --- /dev/null +++ b/apps/server/internal/runtime/runtime_update_authorization_test.go @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +package runtime + +import ( + "context" + "errors" + "testing" + + "github.com/Moonrend/Zakura/apps/server/internal/platform/db/models" + "github.com/Moonrend/Zakura/apps/server/internal/platform/httpx" +) + +func TestRuntimeNodeUpdateAuthorizationRequiresPlatformAdminOwnership(t *testing.T) { + d := testDeps(t) + seedTenant(t, d, "tenant-a") + seedTenant(t, d, "tenant-b") + now := runtimeTimeString(d.Clock()) + node := func(id, tenant string, shared bool) models.RuntimeNode { + return models.RuntimeNode{ID: &id, TenantID: tenant, Name: id, Slug: id, Kind: "computer", Status: "online", CapabilitiesJSON: "{}", HostInfoJSON: "{}", StorageRoot: "/var/lib/zakura", LabelsJSON: "{}", IsShared: shared, CreatedAt: now, UpdatedAt: now} + } + for _, candidate := range []models.RuntimeNode{ + node("owned", "tenant-a", false), + node("foreign-shared", "tenant-b", true), + } { + if err := d.Gorm.Create(&candidate).Error; err != nil { + t.Fatal(err) + } + } + h := &handler{deps: d} + for _, tc := range []struct { + name string + actor httpx.Principal + node string + want error + }{ + {name: "member cannot update owned node", actor: httpx.Principal{TenantID: "tenant-a", Role: "member"}, node: "owned", want: errRuntimeNodeUpdateForbidden}, + {name: "admin cannot update foreign shared node", actor: httpx.Principal{TenantID: "tenant-a", Role: "owner", IsPlatformAdmin: true}, node: "foreign-shared", want: ErrNotFound}, + {name: "admin can update owned node", actor: httpx.Principal{TenantID: "tenant-a", Role: "owner", IsPlatformAdmin: true}, node: "owned"}, + {name: "owning admin can update shared node", actor: httpx.Principal{TenantID: "tenant-b", Role: "owner", IsPlatformAdmin: true}, node: "foreign-shared"}, + } { + t.Run(tc.name, func(t *testing.T) { + err := h.authorizeRuntimeNodeUpdate(context.Background(), tc.actor, tc.node) + if !errors.Is(err, tc.want) { + t.Fatalf("authorizeRuntimeNodeUpdate() error = %v, want %v", err, tc.want) + } + }) + } +}