Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
docs(sandbox): fix secret lifetime and shell quoting examples (#3565)
Francesco Bonaccibaa421525a49
diff --git a/docs/content/docs/how-to-guides/sandbox/secrets.mdx b/docs/content/docs/how-to-guides/sandbox/secrets.mdxindex a61dbc7ad6..c25231b96d 100644--- a/docs/content/docs/how-to-guides/sandbox/secrets.mdx+++ b/docs/content/docs/how-to-guides/sandbox/secrets.mdx@@ -5,45 +5,48 @@ description: Read secrets from the host and inject them into a sandbox at runtimimport { Callout } from 'fumadocs-ui/components/callout';-Pass secrets from the host environment into a sandbox **at runtime**, and keep image metadata for non-sensitive configuration.+Pass task-specific credentials from the host into a sandbox at runtime. Keep secrets out of image specifications, build commands, and copied application files.++These examples use a connected Linux sandbox named `sb` with a POSIX shell and Python 3. Put your application at `/app/main.py` before running them. Use credentials with only the permissions and lifetime the task needs.## Inject secrets at runtime-Read secrets from the host environment, then inject them into the sandbox with `sb.shell.run`.+Set `DATABASE_URL` and `GITHUB_TOKEN` in the host environment through your secret manager. Then call `await run_with_secrets(sb)` from your async code:```pythonimport os-import asyncio-from cua import Sandbox, Image+import shlex+from cua_sandbox import Sandbox+-async def main():+async def run_with_secrets(sb: Sandbox):db_url = os.environ['DATABASE_URL']gh_token = os.environ['GITHUB_TOKEN']-- async with Sandbox.ephemeral(Image.linux(), local=True) as sb:- await sb.shell.run(f"export DATABASE_URL='{db_url}'")- await sb.shell.run(f"export GITHUB_TOKEN='{gh_token}'")- await sb.shell.run('python /app/main.py')--asyncio.run(main())+ command = (+ f'DATABASE_URL={shlex.quote(db_url)} '+ f'GITHUB_TOKEN={shlex.quote(gh_token)} '+ 'python3 /app/main.py'+ )+ result = await sb.shell.run(command)+ if not result.success:+ raise RuntimeError('Application failed; inspect sanitized diagnostics')```-For multi-command sessions, use a wrapper script:+Keep the assignments and application in the same `shell.run()` call. An `export` in one call does not persist into another call. `shlex.quote()` preserves spaces, quotes, and newlines as literal values in a POSIX shell; environment values cannot contain a NUL byte.-```python-script = f"""-export DATABASE_URL='{db_url}'-export GITHUB_TOKEN='{gh_token}'-python /app/main.py-"""-result = await sb.shell.run(script)-```+The assignments apply to the application and its child processes. They do not configure later shell calls. Wait for the application to finish, and avoid leaving background children running with inherited credentials.-## Non-sensitive config with Image.env()+<Callout type="warn">+ These commands contain the secret values. Shell quoting prevents shell interpretation; it does not redact command logs, traces, process inspection, or application output. Use a trusted sandbox, restrict access to its diagnostics, and do not print the command or enable shell tracing (`set -x`).+</Callout>++## Keep image configuration non-sensitiveUse `Image.env()` for non-sensitive config, **not for secrets**.```python+from cua_sandbox import Image+img = (Image.linux().apt_install('python3')@@ -59,30 +62,38 @@ img = (.env() values are stored in the Image spec and visible to anyone who can inspect it. Do not use .env() for API keys, passwords, or tokens.</Callout>-## Copy secret files into the sandbox+## Provide a temporary credential file-Copy SSH keys, certificates, and other secret files into the sandbox at runtime, then set file permissions.+For an application that reads an SSH key file, create a credential for the task and set `TASK_SSH_KEY_FILE` to its host file path. Restrict that host file to its owner (`chmod 600`). Configure `/app/main.py` to read the sandbox file path from `TASK_SSH_KEY_FILE`, then call `await run_with_key_file(sb)`:```python-async with Sandbox.ephemeral(Image.linux(), local=True) as sb:- with open(os.path.expanduser('~/.ssh/id_rsa')) as f:- key_content = f.read()- await sb.shell.run('mkdir -p /root/.ssh && chmod 700 /root/.ssh')- await sb.shell.run(f"cat > /root/.ssh/id_rsa << 'EOF'\n{key_content}\nEOF")- await sb.shell.run('chmod 600 /root/.ssh/id_rsa')+import os+from pathlib import Path+import shlex+from cua_sandbox import Sandbox+++async def run_with_key_file(sb: Sandbox):+ key_content = Path(os.environ['TASK_SSH_KEY_FILE']).read_bytes().decode('utf-8')+ script = f"""+set -eu+umask 077+secret_dir=$(mktemp -d /tmp/cua-task-secret.XXXXXXXXXX)+trap 'rm -f "$secret_dir/task-key"; rmdir "$secret_dir"' EXIT+trap 'exit 1' HUP INT TERM+printf '%s' {shlex.quote(key_content)} > "$secret_dir/task-key"+chmod 600 "$secret_dir/task-key"+TASK_SSH_KEY_FILE="$secret_dir/task-key" python3 /app/main.py+"""+ result = await sb.shell.run(script)+ if not result.success:+ raise RuntimeError('Credential task failed; inspect sanitized diagnostics')```-For files safe to bake in, use Image.copy():+This example accepts a UTF-8 text key without NUL bytes. `printf '%s'` writes its content without adding or removing a trailing newline. `mktemp -d` creates a private directory, and `umask 077` restricts the file to its owner from creation. Mode `600` permits only the owner to read and write the key; it does not protect against root or other processes running as that owner.-```python-img = Image.linux().copy('./app-config.json', '/app/config.json')-```+The exit trap removes the temporary file and directory after the application exits, including an ordinary nonzero exit. Forced termination, a shell timeout, or loss of the sandbox connection can prevent cleanup. The host key remains in place. Do not snapshot the sandbox while it holds credentials, and revoke the task credential when finished. Removing the file does not securely erase copies, logs, or snapshots.-## Best practices+## Finish the task-| Do | Don't |-|----|-------|-| Read secrets from host environment variables | Hardcode secrets in Python source |-| Inject secrets at runtime via sb.shell.run | Store secrets in Image.env() |-| Use .env files + python-dotenv locally | Commit .env files to version control |-| Use your CI/CD provider's secret manager | Log or print secret values |+Check the application's exit status without printing credentials or unreviewed output. Confirm that credential-consuming processes have stopped and that temporary files were removed. If cleanup was interrupted, remove the remaining task files or destroy the disposable sandbox before reusing it. Revoke or expire credentials through the issuing service, and keep host secret files out of version control.diff --git a/docs/scripts/tests/test_sandbox_secret_example.py b/docs/scripts/tests/test_sandbox_secret_example.pynew file mode 100644index 0000000000..27c721e361--- /dev/null+++ b/docs/scripts/tests/test_sandbox_secret_example.py@@ -0,0 +1,113 @@+"""Exercise the documented commands with synthetic secrets and a local shell.++Run with Python and cua-sandbox==0.4.3 installed. No sandbox is provisioned;+the released Shell interface sends commands to a disposable local test transport.+"""++import asyncio+import importlib.metadata+import json+import os+from pathlib import Path+import re+import shlex+import subprocess+import sys+import tempfile+import types+import unittest+from unittest.mock import patch++from cua_sandbox.interfaces.shell import Shell+++PAGE = Path(__file__).resolve().parents[2] / "content/docs/how-to-guides/sandbox/secrets.mdx"+BLOCKS = re.findall(r"```python\n(.*?)\n```", PAGE.read_text(), re.DOTALL)+SYNTHETIC = "synthetic space 'quote' \"double\" $HOME $(exit 91) `exit 92`\nEOF\nlast\n"+++class LocalTestTransport:+ """Run each command in a new shell; replace only the sample application."""++ def __init__(self, consumer):+ self.consumer = consumer+ self.results = []++ async def send(self, action, *, command, timeout):+ assert action == "run_command"+ consumer = f"{shlex.quote(sys.executable)} -c {shlex.quote(self.consumer)}"+ command = command.replace("python3 /app/main.py", consumer)+ result = subprocess.run(+ ["/bin/sh", "-c", command],+ capture_output=True,+ text=True,+ timeout=timeout,+ env={"PATH": "/usr/bin:/bin"},+ )+ self.results.append(result)+ return result+++class SecretExampleTests(unittest.TestCase):+ def load_example(self, function_name):+ block = next(block for block in BLOCKS if f"async def {function_name}(" in block)+ namespace = {}+ exec(compile(block, str(PAGE), "exec"), namespace)+ return namespace[function_name]++ def test_released_api_and_python_syntax(self):+ self.assertEqual(importlib.metadata.version("cua-sandbox"), "0.4.3")+ for block in BLOCKS:+ compile(block, str(PAGE), "exec")++ def test_environment_round_trip_and_lifetime(self):+ transport = LocalTestTransport(+ "import json, os; print(json.dumps([os.environ['DATABASE_URL'], "+ "os.environ['GITHUB_TOKEN']]))"+ )+ shell = Shell(transport)+ with patch.dict(os.environ, DATABASE_URL=SYNTHETIC, GITHUB_TOKEN=SYNTHETIC):+ asyncio.run(self.load_example("run_with_secrets")(types.SimpleNamespace(shell=shell)))+ self.assertEqual(json.loads(transport.results[0].stdout), [SYNTHETIC, SYNTHETIC])+ later = asyncio.run(shell.run('test -z "${DATABASE_URL+x}${GITHUB_TOKEN+x}"'))+ self.assertTrue(later.success)++ def test_separate_export_does_not_persist(self):+ shell = Shell(LocalTestTransport(""))+ exported = asyncio.run(shell.run(f"export CUA_TEST_SECRET={shlex.quote(SYNTHETIC)}"))+ self.assertTrue(exported.success)+ later = asyncio.run(shell.run('test -z "${CUA_TEST_SECRET+x}"'))+ self.assertTrue(later.success)++ def test_key_bytes_permissions_and_cleanup_on_success_and_failure(self):+ for exit_code in (0, 7):+ with self.subTest(exit_code=exit_code), tempfile.TemporaryDirectory() as host_dir:+ host_key = Path(host_dir) / "task-key"+ host_key.write_bytes(SYNTHETIC.encode())+ host_key.chmod(0o600)+ consumer = (+ "import json, os, pathlib, stat, sys; "+ "p = pathlib.Path(os.environ['TASK_SSH_KEY_FILE']); "+ "print(json.dumps([str(p), p.read_bytes().decode(), "+ "stat.S_IMODE(p.stat().st_mode), stat.S_IMODE(p.parent.stat().st_mode)])); "+ f"sys.exit({exit_code})"+ )+ transport = LocalTestTransport(consumer)+ sandbox = types.SimpleNamespace(shell=Shell(transport))+ with patch.dict(os.environ, TASK_SSH_KEY_FILE=str(host_key)):+ task = self.load_example("run_with_key_file")(sandbox)+ if exit_code:+ with self.assertRaises(RuntimeError):+ asyncio.run(task)+ else:+ asyncio.run(task)+ path, content, mode, directory_mode = json.loads(transport.results[0].stdout)+ self.assertEqual(content, SYNTHETIC)+ self.assertEqual((mode, directory_mode), (0o600, 0o700))+ self.assertFalse(Path(path).exists())+ self.assertFalse(Path(path).parent.exists())+ self.assertEqual(host_key.read_bytes(), SYNTHETIC.encode())+++if __name__ == "__main__":+ unittest.main()