The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(daytona): activate the advisory bwrap wrapper at the execute seam (#10554)
Nicky Leach8c910b9a40a8
diff --git a/packages/plugins/sandbox-providers/daytona/README.md b/packages/plugins/sandbox-providers/daytona/README.mdindex 1057794b34..f2762feef1 100644--- a/packages/plugins/sandbox-providers/daytona/README.md+++ b/packages/plugins/sandbox-providers/daytona/README.md@@ -31,12 +31,14 @@ Notes:## Advisory bwrap wrapper-The driver prepares an advisory bubblewrap (`bwrap`) wrapper for a sandbox command. The wrapper is advisory and best-effort. The driver does not wrap the command during execution yet. At lease time the driver probes the sandbox for the wrapper capability and records the result on the lease metadata. The command builder exists as a pure function. A later change wires the builder into command execution.+The driver wraps a sandbox command with an advisory bubblewrap (`bwrap`) wrapper. The wrapper is advisory, best-effort, and automatic. At lease time the driver probes the sandbox for the wrapper capability and records the result on the lease metadata. At execute time the driver wraps the command when the capability is present. The command builder is a pure function.- **The wrapper adds no security.** The ephemeral sandbox stays the only security posture. The wrapper only gives an agent real-time feedback when the agent tries to change a file that the ephemeral sandbox will not keep.- **The read-only root is a feedback signal.** The wrapper binds the root as read-only (`--ro-bind / /`) and re-binds only the writable directories. A write to a path outside the writable set fails at once, so the agent learns the change is not durable.- **A capability probe records the wrapper capability.** No configuration field turns it on. At lease time the driver probes the sandbox for the end-to-end `bwrap` capability (`sudo -n bwrap` with a user namespace) and reads the sandbox user's uid and gid. It stores `bwrapAvailable`, `sandboxUid`, and `sandboxGid` on the lease metadata.- **The probe is best-effort.** A missing `bwrap` binary, a missing passwordless `sudo -n` rule, or a missing user namespace records `bwrapAvailable: false` and never fails the lease.+- **The writable set is the workspace plus the read-write sync destinations.** The wrapper binds the workspace directory read-write as the baseline; the workspace is always durable. It adds the read-write sync destinations that a sync-in recorded for the same lease. The set deduplicates the directories. The baseline keeps a safe result even when the collected set is empty.+- **The wrapper runs at execute time when the capability is present.** The driver wraps the command only when the lease reports `bwrapAvailable: true` and a uid/gid pair is known. It binds the workspace and the read-write sync destinations, keeps the root read-only for feedback, and re-binds the stdin file after the fresh `/tmp`. It runs the plain command when the capability or the uid/gid is missing. A wrap without a uid/gid would run as root and give the agent's files root ownership, so the driver keeps the plain command in that case.## Local developmentdiff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.test.tsindex 911590bddb..7f21b11b85 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts@@ -1196,6 +1196,241 @@ describe("Daytona sandbox provider plugin", () => {});});+ it("wraps the command when the lease reports bwrap available and uid/gid known", async () => {+ process.env.DAYTONA_API_KEY = "host-key";+ const sandbox = createMockSandbox();+ mockGet.mockResolvedValue(sandbox);++ await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: {+ remoteCwd: "/home/daytona/paperclip-workspace",+ bwrapAvailable: true,+ sandboxUid: 1000,+ sandboxGid: 1000,+ },+ },+ command: "printf",+ args: ["hello"],+ timeoutMs: 1000,+ });++ const [command] = sandbox.process.executeCommand.mock.calls[0] as [string];+ // The wrapper runs `sudo -n bwrap`, re-enters the sandbox user through the+ // user namespace, and binds the workspace directory read-write.+ expect(command.startsWith("sudo -n bwrap")).toBe(true);+ expect(command).toContain("--unshare-user --uid 1000 --gid 1000");+ expect(command).toContain(+ "--bind-try '/home/daytona/paperclip-workspace' '/home/daytona/paperclip-workspace'",+ );+ // The login-shell script still rides inside the wrapper through `sh -c`.+ expect(command).toContain("/etc/profile");+ });++ it("binds collected rw sync directories", async () => {+ process.env.DAYTONA_API_KEY = "host-key";+ const remoteCwd = "/home/daytona/paperclip-workspace";+ const collectedDir = `${remoteCwd}/data`;+ const hostDir = await fs.mkdtemp(path.join(os.tmpdir(), "daytona-bwrap-test-"));+ const source = path.join(hostDir, "in-place.txt");+ await fs.writeFile(source, "bytes");+ const sandbox = createMockSandbox();+ mockGet.mockResolvedValue(sandbox);++ const scopeParams = {+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ };++ // Record a read-write sync destination under the shared scope. The execute+ // hook reads the same scope, so the wrapper must bind this directory too.+ await plugin.definition.onEnvironmentSyncIn?.({+ ...scopeParams,+ lease: { providerLeaseId: "sandbox-123", metadata: { remoteCwd } },+ operations: [+ {+ operationId: "sync-op-rw",+ files: [+ {+ sourcePath: source,+ targetPath: `${collectedDir}/in-place.txt`,+ kind: "file" as const,+ access: "rw" as const,+ },+ ],+ },+ ],+ });+ sandbox.process.executeCommand.mockClear();++ await plugin.definition.onEnvironmentExecute?.({+ ...scopeParams,+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: { remoteCwd, bwrapAvailable: true, sandboxUid: 1000, sandboxGid: 1000 },+ },+ command: "printf",+ args: ["hello"],+ timeoutMs: 1000,+ });++ const [command] = sandbox.process.executeCommand.mock.calls[0] as [string];+ expect(command).toContain(`--bind-try '${collectedDir}' '${collectedDir}'`);+ await fs.rm(hostDir, { recursive: true, force: true });+ });++ it("keeps binding a collected rw directory after a later sync deletes it, so a stale path does not abort a later command", async () => {+ // A sync records a read-write destination, then a later operation removes+ // that path in the sandbox. The store still holds the path, so the wrapper+ // still adds it to the command. `--bind-try` skips a missing source, so the+ // command still runs. This test proves the wrapper uses `--bind-try` (not+ // `--bind`) for the collected path, which stops a stale path from failing+ // every later command for the scope.+ process.env.DAYTONA_API_KEY = "host-key";+ const remoteCwd = "/home/daytona/paperclip-workspace";+ const collectedDir = `${remoteCwd}/scratch`;+ const hostDir = await fs.mkdtemp(path.join(os.tmpdir(), "daytona-bwrap-stale-"));+ const source = path.join(hostDir, "note.txt");+ await fs.writeFile(source, "bytes");+ const sandbox = createMockSandbox();+ mockGet.mockResolvedValue(sandbox);++ const scopeParams = {+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ };++ await plugin.definition.onEnvironmentSyncIn?.({+ ...scopeParams,+ lease: { providerLeaseId: "sandbox-123", metadata: { remoteCwd } },+ operations: [+ {+ operationId: "sync-op-rw",+ files: [+ {+ sourcePath: source,+ targetPath: `${collectedDir}/note.txt`,+ kind: "file" as const,+ access: "rw" as const,+ },+ ],+ },+ ],+ });+ sandbox.process.executeCommand.mockClear();++ await plugin.definition.onEnvironmentExecute?.({+ ...scopeParams,+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: { remoteCwd, bwrapAvailable: true, sandboxUid: 1000, sandboxGid: 1000 },+ },+ command: "printf",+ args: ["hello"],+ timeoutMs: 1000,+ });++ const [command] = sandbox.process.executeCommand.mock.calls[0] as [string];+ // The stale collected path binds with `--bind-try`, so a missing source is+ // skipped and the command still runs.+ expect(command).toContain(`--bind-try '${collectedDir}' '${collectedDir}'`);+ // No writable directory uses a plain `--bind`, so no stale source can abort.+ expect(command).not.toMatch(/(^| )--bind '/);+ await fs.rm(hostDir, { recursive: true, force: true });+ });++ it("re-binds the stdin path when stdin is present and bwrap is available", async () => {+ process.env.DAYTONA_API_KEY = "host-key";+ const sandbox = createMockSandbox();+ mockGet.mockResolvedValue(sandbox);++ await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: {+ remoteCwd: "/home/daytona/paperclip-workspace",+ bwrapAvailable: true,+ sandboxUid: 1000,+ sandboxGid: 1000,+ },+ },+ command: "cat",+ args: [],+ stdin: "input payload",+ timeoutMs: 1000,+ });++ const stdinPath = sandbox.fs.uploadFile.mock.calls[0][1] as string;+ expect(stdinPath).toMatch(/^\/tmp\/paperclip-stdin-/);+ const [command] = sandbox.process.executeCommand.mock.calls[0] as [string];+ // The `--tmpfs /tmp` flag hides the uploaded stdin file, so the wrapper must+ // re-bind it read-only after the tmpfs.+ expect(command).toContain(`--ro-bind '${stdinPath}' '${stdinPath}'`);+ });++ it("runs the plain command when bwrap is unavailable or uid/gid is unknown", async () => {+ process.env.DAYTONA_API_KEY = "host-key";+ const sandbox = createMockSandbox();+ mockGet.mockResolvedValue(sandbox);++ // Case 1: the probe reported bwrap unavailable.+ await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: {+ remoteCwd: "/home/daytona/paperclip-workspace",+ bwrapAvailable: false,+ sandboxUid: 1000,+ sandboxGid: 1000,+ },+ },+ command: "printf",+ args: ["hello"],+ timeoutMs: 1000,+ });+ expect((sandbox.process.executeCommand.mock.calls[0] as [string])[0]).not.toContain("bwrap");++ // Case 2: bwrap is available but the uid/gid is unknown. A wrap without a+ // uid/gid would run as root, so the seam keeps the plain command.+ sandbox.process.executeCommand.mockClear();+ await plugin.definition.onEnvironmentExecute?.({+ driverKey: "daytona",+ companyId: "company-1",+ environmentId: "env-1",+ config: { timeoutMs: 300000, reuseLease: false },+ lease: {+ providerLeaseId: "sandbox-123",+ metadata: {+ remoteCwd: "/home/daytona/paperclip-workspace",+ bwrapAvailable: true,+ sandboxUid: null,+ sandboxGid: null,+ },+ },+ command: "printf",+ args: ["hello"],+ timeoutMs: 1000,+ });+ expect((sandbox.process.executeCommand.mock.calls[0] as [string])[0]).not.toContain("bwrap");+ });+it("rejects invalid shell env keys before execution", async () => {process.env.DAYTONA_API_KEY = "host-key";const sandbox = createMockSandbox();@@ -3377,7 +3612,7 @@ describe("buildBwrapCommand advisory wrapper builder", () => {expect(command).toBe("sudo -n bwrap --unshare-user --uid 1000 --gid 1000 "+ "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp "- + "--bind '/home/daytona/paperclip-workspace' '/home/daytona/paperclip-workspace' "+ + "--bind-try '/home/daytona/paperclip-workspace' '/home/daytona/paperclip-workspace' "+ "--new-session -- sh -c 'echo hi'",);});@@ -3393,7 +3628,7 @@ describe("buildBwrapCommand advisory wrapper builder", () => {expect(command).toBe("sudo -n bwrap --unshare-user --uid 1000 --gid 1000 "+ "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp "- + "--bind '/work' '/work' "+ + "--bind-try '/work' '/work' "+ "--ro-bind '/tmp/stdin.bin' '/tmp/stdin.bin' "+ "--new-session -- sh -c 'run-cmd'",);@@ -3411,7 +3646,7 @@ describe("buildBwrapCommand advisory wrapper builder", () => {// shellQuote rewrites each embedded single quote as the `'"'"'` token.expect(command).toContain(`'"'"'`);- expect(command).toContain(`--bind '/data/o'"'"'brien' '/data/o'"'"'brien'`);+ expect(command).toContain(`--bind-try '/data/o'"'"'brien' '/data/o'"'"'brien'`);expect(command).toContain(`-- sh -c 'echo '"'"'hello'"'"''`);});@@ -3421,13 +3656,35 @@ describe("buildBwrapCommand advisory wrapper builder", () => {expect(command).toBe("sudo -n bwrap "+ "--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp "- + "--bind '/w' '/w' "+ + "--bind-try '/w' '/w' "+ "--new-session -- sh -c 'plain'",);expect(command).not.toContain("--unshare-user");expect(command).not.toContain("--uid");expect(command).not.toContain("--gid");});++ it("binds each writable directory with --bind-try so a stale or deleted path does not abort bwrap", () => {+ // The writable set holds advisory sandbox paths. A later sync can delete or+ // replace one. `--bind` aborts when the source is absent; `--bind-try` skips+ // a missing source and runs the command. Assert the builder emits+ // `--bind-try` for every writable directory and never a plain `--bind` for+ // them, so one stale path never poisons a later command.+ const command = buildBwrapCommand(+ "echo hi",+ ["/home/daytona/paperclip-workspace", "/home/daytona/data"],+ null,+ { uid: 1000, gid: 1000 },+ );++ expect(command).toContain(+ "--bind-try '/home/daytona/paperclip-workspace' '/home/daytona/paperclip-workspace'",+ );+ expect(command).toContain("--bind-try '/home/daytona/data' '/home/daytona/data'");+ // The only plain `--bind` family in the command is the read-only bind+ // (`--ro-bind`). No writable directory uses a plain `--bind`.+ expect(command).not.toMatch(/(^| )--bind '/);+ });});describe("advisory bwrap capability probe at lease time", () => {diff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.tsindex bf56998410..d12dfff0fa 100644--- a/packages/plugins/sandbox-providers/daytona/src/plugin.ts+++ b/packages/plugins/sandbox-providers/daytona/src/plugin.ts@@ -620,13 +620,20 @@ function shellQuote(value: string): string {// 1. `--unshare-user --uid <uid> --gid <gid>` when a uid/gid pair is supplied.// 2. `--ro-bind / /` (read-only root — the static system allowance base).// 3. `--dev /dev --proc /proc --tmpfs /tmp` (fresh pseudo-filesystems).-// 4. one `--bind <dir> <dir>` per writable directory, in the caller's order.+// 4. one `--bind-try <dir> <dir>` per writable directory, in the caller's order.// 5. `--ro-bind <stdinPath> <stdinPath>` when a stdin path is supplied.// 6. `--new-session`.// 7. `-- sh -c '<escaped inner script>'`.// `--uid`/`--gid` require `--unshare-user`, so the function emits the three// flags only together. `sudo -n bwrap` runs as root; the user namespace// re-enters the sandbox as the normal sandbox user.+//+// The writable binds use `--bind-try`, not `--bind`. The writable set is an+// advisory in-memory collection of sandbox paths. The host cannot check whether+// a sandbox path still exists. A path can be deleted or replaced after the store+// records it. `--bind` aborts bwrap when the source is absent, so one stale path+// would fail every later command for the scope. `--bind-try` skips a missing+// source and runs the command, which keeps the wrapper advisory and best-effort.export function buildBwrapCommand(innerScript: string,writableDirs: string[],@@ -637,7 +644,7 @@ export function buildBwrapCommand(? ["--unshare-user", "--uid", String(identity.uid), "--gid", String(identity.gid)]: [];const rootBinds = ["--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc", "--tmpfs", "/tmp"];- const writableBinds = writableDirs.flatMap((dir) => ["--bind", shellQuote(dir), shellQuote(dir)]);+ const writableBinds = writableDirs.flatMap((dir) => ["--bind-try", shellQuote(dir), shellQuote(dir)]);// Re-bind the stdin file after `--tmpfs /tmp`, so the tmpfs does not hide it.const stdinReBind = stdinPath ? ["--ro-bind", shellQuote(stdinPath), shellQuote(stdinPath)] : [];const tail = ["--new-session", "--", "sh", "-c", shellQuote(innerScript)];@@ -1257,6 +1264,11 @@ const sandboxHandleCache = (() => {// and a cold store (for example after a worker restart) degrades to the// workspace baseline, never to a crash. The store is keyed the same way as// `sandboxHandleCache`, by `sandboxHandleCacheKey(scope)`.+//+// The store keeps a path after a sync records it, so a path that a later+// operation deletes or replaces can stay in the set. The wrapper binds each+// path with `bwrap --bind-try`, which skips a missing source, so a stale path+// never fails a later command. See `buildBwrapCommand`.const sandboxHandleWritableDirs = (() => {const dirsByKey = new Map<string, Set<string>>();@@ -1351,6 +1363,40 @@ function evictSandboxHandle(scope: SandboxScope): void {sandboxHandleCache.clear(scope);}+// Advisory bwrap execution plan. When present, `executeOneShot` wraps the+// login-shell string with `buildBwrapCommand`. When null, it runs the plain+// string, which keeps today's behavior. `writableDirs` holds the workspace+// directory (baseline, always read-write) plus the collected read-write sync+// destinations. `identity` carries the sandbox uid/gid for the user namespace.+type BwrapExecPlan = {+ writableDirs: string[];+ identity: { uid: number; gid: number };+};++// Decide whether the advisory bwrap wrapper runs for one exec. The wrapper runs+// only when the lease reports bwrap available, a uid/gid pair is known, and the+// workspace directory is known. A wrap without a uid/gid would run as root and+// give the agent's files root ownership, so this returns null (run the plain+// command) in that case. The writable set is the workspace directory (baseline,+// always read-write) plus the per-scope read-write sync destinations. The+// baseline guarantees a safe result even when the collected store is cold.+function resolveBwrapExecPlan(+ metadata: Record<string, unknown> | null | undefined,+ scope: SandboxScope,+): BwrapExecPlan | null {+ if (metadata?.bwrapAvailable !== true) return null;+ const uid = metadata.sandboxUid;+ const gid = metadata.sandboxGid;+ if (typeof uid !== "number" || typeof gid !== "number") return null;+ const remoteCwd = typeof metadata.remoteCwd === "string" ? metadata.remoteCwd.trim() : "";+ if (remoteCwd.length === 0) return null;+ const writableDirs = new Set<string>([remoteCwd]);+ for (const dir of sandboxHandleWritableDirs.get(scope)) {+ writableDirs.add(dir);+ }+ return { writableDirs: [...writableDirs], identity: { uid, gid } };+}+// One-shot command execution via Daytona's `process.executeCommand`. The// session-based API (`createSession` + `executeSessionCommand` with// `runAsync: false`) hangs indefinitely when the supplied command ends with@@ -1366,6 +1412,7 @@ async function executeOneShot(sandbox: Sandbox,params: PluginEnvironmentExecuteParams,config: DaytonaDriverConfig,+ bwrap: BwrapExecPlan | null,): Promise<PluginEnvironmentExecuteResult> {const gitNet = isGitNetworkCommand(params.command, params.args ?? []);const timeoutMs = resolveTimeoutMs(params.timeoutMs, config);@@ -1385,7 +1432,7 @@ async function executeOneShot(await sandbox.fs.uploadFile(Buffer.from(params.stdin ?? "", "utf8"), stdinPath, timeoutSeconds);}- const command = buildLoginShellScript({+ const loginScript = buildLoginShellScript({command: params.command,args: params.args ?? [],cwd: params.cwd,@@ -1393,6 +1440,16 @@ async function executeOneShot(stdinPath: stdinPath ?? undefined,});+ // Advisory bwrap wrapper (best-effort, automatic, no security boundary). When+ // the lease reports bwrap available and a uid/gid is known, wrap the+ // login-shell string so a write to a non-persistent path fails and the agent+ // gets real-time feedback. The writable set binds the workspace and the+ // read-write sync destinations; the stdin re-bind survives the `--tmpfs /tmp`.+ // When the plan is null, run the plain string, which keeps today's behavior.+ const command = bwrap+ ? buildBwrapCommand(loginScript, bwrap.writableDirs, stdinPath, bwrap.identity)+ : loginScript;+// Pass cwd undefined: `buildLoginShellScript` already injects the `cd` after// it sources the login profiles, when params.cwd is set. The Daytona// executor's own cwd argument runs before that profile sourcing, which is@@ -2071,7 +2128,16 @@ const plugin = definePlugin({}, { bypassTeardownGate: true });const getDurationMs = timingNow() - getStart;await ensureSandboxStarted(sandbox, toTimeoutSeconds(resolveTimeoutMs(params.timeoutMs, config)));- const result = await executeOneShot(sandbox, params, config);+ // Read the advisory bwrap flags from the lease metadata and read the+ // collected writable directories from the same scope the sync-in hook uses.+ const bwrapPlan = resolveBwrapExecPlan(params.lease.metadata, {+ driverKey: params.driverKey,+ companyId: params.companyId,+ environmentId: params.environmentId,+ providerLeaseId,+ config,+ });+ const result = await executeOneShot(sandbox, params, config, bwrapPlan);if (!result.timedOut) {sandboxHandleCache.markFresh({driverKey: params.driverKey,