Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(execd): run large background code in isolated sessions
Maohaod3275f387a98
diff --git a/components/execd/pkg/runtime/isolated_background.go b/components/execd/pkg/runtime/isolated_background.goindex d820827c5..535888d7a 100644--- a/components/execd/pkg/runtime/isolated_background.go+++ b/components/execd/pkg/runtime/isolated_background.go@@ -35,7 +35,7 @@ import ()// isolatedBackgroundRunDir is the workspace-relative directory for background-// run log and exit-code files (dot-dir, created by the session shell).+// run log, exit-code and script files (dot-dir, created by the session shell).const isolatedBackgroundRunDir = ".execd/background-runs"// isolatedBackgroundPollInterval is how often the watcher checks for the@@ -81,8 +81,8 @@ type IsolatedBackgroundRun struct {running bool}-// relLogPath/relExitPath/relFallbackLogPath/relFallbackExitPath return the-// run's control files relative to logRoot (the run directory for the primary+// relLogPath/relExitPath/relScriptPath and their fallbacks return the run's+// control files relative to logRoot (the run directory for the primary// files, the workspace root for the fallbacks).func (r *IsolatedBackgroundRun) relLogPath() string {return filepath.Join(isolatedBackgroundRunDir, r.ID+".log")@@ -100,6 +100,14 @@ func (r *IsolatedBackgroundRun) relFallbackExitPath() string {return r.ID + ".code"}+func (r *IsolatedBackgroundRun) relScriptPath() string {+ return filepath.Join(isolatedBackgroundRunDir, r.ID+".sh")+}++func (r *IsolatedBackgroundRun) relFallbackScriptPath() string {+ return r.ID + ".sh"+}+// IsolatedBackgroundRunSnapshot is a consistent read of a background run.type IsolatedBackgroundRunSnapshot struct {RunID string@@ -184,11 +192,14 @@ func (r *IsolatedRunner) RunInIsolatedSessionBackground(return "", time.Time{}, err}- // The background job runs under `bash -c` (or `sh -c` when bash is- // unavailable) so user code is parsed as its own program: shell syntax+ // The background job runs the code as a script file under bash (or sh when+ // bash is unavailable) so it is parsed as its own program: shell syntax// errors in the code cannot break the control wrapper, which would// otherwise leave the run stuck `running` (the wrapper's completion lines- // are only parsed after the code). The code's output is redirected to the+ // are only parsed after the code). The file is written from a quoted+ // here-document, which keeps the code verbatim, instead of passing the+ // code to `-c`, where Linux limits a single argument to 128 KiB. It is+ // removed when the code exits. The code's output is redirected to the// log file; its exit code is captured and written to the code file. The// script's mkdir creates the run dir as the session's own uid (so it is// writable even when the session runs as a different uid than execd); if@@ -206,8 +217,13 @@ func (r *IsolatedRunner) RunInIsolatedSessionBackground(script += "export " + shellescape(k) + "=" + shellescape(v) + "; "}}- script += shell + " -c " + shellescape(code) + " </dev/null >\"$D/" + runID + ".log\" 2>&1"- script += "\ncode=$?; mkdir -p \"$D\" 2>/dev/null && [ -w \"$D\" ] || D=" ++ delimiter := "EXECD_RUN_" + strings.ReplaceAll(runID, "-", "_")+ script += "F=\"$D/" + runID + ".sh\"; cat >\"$F\" <<'" + delimiter + "'\n" + code+ if !strings.HasSuffix(code, "\n") {+ script += "\n"+ }+ script += delimiter + "\n" + shell + " \"$F\" </dev/null >\"$D/" + runID + ".log\" 2>&1"+ script += "\ncode=$?; rm -f \"$F\"; mkdir -p \"$D\" 2>/dev/null && [ -w \"$D\" ] || D=" +shellescape(paths.nsWorkspace)script += "\necho \"$code\" >\"$D/" + runID + ".code\"; } >/dev/null 2>&1 &\n"@@ -462,18 +478,20 @@ func (r *IsolatedRunner) SeekIsolatedBackgroundOutput(return data, newCursor, nil}-// removeIsolatedRunFiles best-effort deletes the log/exit-code files of a run-// (primary and fallback locations). Overlay workspaces lose them with the-// upper directory anyway; rw workspaces would otherwise keep them in the-// user's persistent workspace. Removes go through the pinned root so-// sandbox-created symlinks can never redirect host-side deletion outside the-// workspace.+// removeIsolatedRunFiles best-effort deletes the log, exit-code and script+// files of a run (primary and fallback locations). Overlay workspaces lose+// them with the upper directory anyway; rw workspaces would otherwise keep+// them in the user's persistent workspace. Removes go through the pinned root+// so sandbox-created symlinks can never redirect host-side deletion outside+// the workspace.func removeIsolatedRunFiles(root *os.Root, run *IsolatedBackgroundRun) {for _, rel := range []string{run.relLogPath(),run.relExitPath(),+ run.relScriptPath(),run.relFallbackLogPath(),run.relFallbackExitPath(),+ run.relFallbackScriptPath(),} {_ = root.Remove(rel)}diff --git a/components/execd/pkg/runtime/isolated_background_test.go b/components/execd/pkg/runtime/isolated_background_test.goindex 84ff910d5..d1d2f2244 100644--- a/components/execd/pkg/runtime/isolated_background_test.go+++ b/components/execd/pkg/runtime/isolated_background_test.go@@ -438,6 +438,37 @@ func TestDeleteSessionRemovesRWRunArtifacts(t *testing.T) {}}+// TestDeleteSessionRemovesRunningRunScript verifies that a run cut short by+// DeleteIsolatedSession does not leave its script file in an rw workspace.+func TestDeleteSessionRemovesRunningRunScript(t *testing.T) {+ runner := newTestRunner(t)+ ws := filepath.Join(t.TempDir(), "ws")+ id, err := runner.CreateIsolatedSession(&IsolatedSessionOptions{+ WorkspacePath: ws,+ WorkspaceMode: "rw",+ })+ if err != nil {+ t.Fatalf("CreateIsolatedSession: %v", err)+ }++ runID, _, err := runner.RunInIsolatedSessionBackground(id, "sleep 30", nil)+ if err != nil {+ t.Fatalf("RunInIsolatedSessionBackground: %v", err)+ }+ scriptPath := filepath.Join(ws, isolatedBackgroundRunDir, runID+".sh")+ require.Eventually(t, func() bool {+ _, err := os.Stat(scriptPath)+ return err == nil+ }, 5*time.Second, 20*time.Millisecond, "script file should exist while the run is in flight")++ if err := runner.DeleteIsolatedSession(id); err != nil {+ t.Fatalf("DeleteIsolatedSession: %v", err)+ }+ if _, err := os.Stat(scriptPath); !os.IsNotExist(err) {+ t.Errorf("script file should be removed after delete, stat err = %v", err)+ }+}+// TestRunInIsolatedSessionBackground_RejectsUnwritableWorkspace verifies that// a session whose workspace root is not writable by its own uid gets a clean// rejection instead of an accepted run that can never write its exit code@@ -765,6 +796,43 @@ func TestBackgroundRunCompletesDespiteShellSyntaxError(t *testing.T) {}}+// TestRunInIsolatedSessionBackground_LargeCode verifies that code larger than+// the 128 KiB limit on a single exec argument runs like any other code, and+// leaves no script file behind.+func TestRunInIsolatedSessionBackground_LargeCode(t *testing.T) {+ runner := newTestRunner(t)+ ws := filepath.Join(t.TempDir(), "ws")+ id, err := runner.CreateIsolatedSession(&IsolatedSessionOptions{+ WorkspacePath: ws,+ WorkspaceMode: "rw",+ })+ if err != nil {+ t.Fatalf("CreateIsolatedSession: %v", err)+ }+ defer runner.DeleteIsolatedSession(id)++ code := "#" + strings.Repeat("x", 150*1024) + "\necho large-code-done"+ runID, _, err := runner.RunInIsolatedSessionBackground(id, code, nil)+ if err != nil {+ t.Fatalf("RunInIsolatedSessionBackground: %v", err)+ }++ snapshot := waitForBackgroundRun(t, runner, id, runID)+ output, _, err := runner.SeekIsolatedBackgroundOutput(id, runID, 0)+ if err != nil {+ t.Fatalf("SeekIsolatedBackgroundOutput: %v", err)+ }+ if snapshot.ExitCode == nil || *snapshot.ExitCode != 0 {+ t.Fatalf("ExitCode = %v, want 0; output = %q", snapshot.ExitCode, output)+ }+ if !strings.Contains(string(output), "large-code-done") {+ t.Errorf("output = %q, want to contain large-code-done", output)+ }+ if _, err := os.Stat(filepath.Join(ws, isolatedBackgroundRunDir, runID+".sh")); !os.IsNotExist(err) {+ t.Errorf("script file should be removed after the run, stat err = %v", err)+ }+}+// TestBackgroundRunCompletesAfterRunDirDeleted verifies that a background// command deleting its own .execd/background-runs directory cannot strand the// run: the exit-code marker falls back to the workspace root and the watcher