Untrusted code
Cloud sandboxes are commonly used to run AI-generated code, user-uploaded scripts, automated tests, data analytics, and third-party dependencies. Treat such code as untrusted by default. A Sandbox reduces execution risk, but it cannot replace input validation, least privilege, network controls, resource limits, and output review.
Assess the risk level first
Before integration, determine which risk category the task falls into:
-
Low risk: runs fixed internal scripts, takes input from trusted systems, and does not access sensitive data.
-
Medium risk: runs AI-generated code or user-uploaded files, but processes only masked data within a controllable access scope.
-
High risk: runs external user code, installs third-party dependencies, accesses the public internet, or processes production data.
-
Never allow by default: tasks that require high-privilege cloud account credentials, write access to production databases, access to internal network management addresses, or writable directories shared across tenants.
Higher risk calls for an isolated Sandbox, short timeouts, short-lived credentials, controlled networking, an isolated working directory, and stricter output review.
Input and command execution
Do not concatenate user input directly into shell commands. User input may contain command separators, path traversal, redirections, variable expansion, or malicious arguments.
Not recommended:
await sandbox.commands.run(`python3 analyze.py ${userInput}`);
Recommended:
await sandbox.files.write("/tmp/input.txt", userInput);
await sandbox.commands.run("python3 analyze.py /tmp/input.txt");
If you must pass arguments, use structured arguments, a whitelist of enumerated values, or an escaping library, and document the allowed argument range. Do not let model-generated commands bypass business-side validation and run directly.
File access control
Create a separate working directory for each task and allow read and write access only to the necessary paths.
const taskId = "task-001";
const workdir = `/tmp/tasks/${taskId}`;
await sandbox.files.makeDir(workdir);
await sandbox.files.write(`${workdir}/input.txt`, userInput);
Recommendations:
-
Have the business system generate file paths instead of directly using the full path provided by the user.
-
Validate the path prefix before deleting files to avoid accidentally deleting system directories, shared directories, or directories of other tasks.
-
Before extracting files, limit the format, size, nesting depth, and total expanded size.
-
Before downloading files, validate the source, size, type, and destination path on disk.
-
Scan and mask output files before returning them to the user.
Network access control
Grant untrusted code only the network capabilities it needs.
Recommendations:
-
By default, do not expose internal network management addresses, database addresses, metadata services, CI/CD services, or internal enterprise APIs to untrusted code.
-
When access to external data sources is required, prefer forwarding through a business-side proxy, and enforce authentication, auditing, rate limiting, and target whitelisting at the proxy layer.
-
Do not use a Sandbox public network port as a long-term service entry point. Configure authentication, expiration, and access scope for temporary preview services.
-
For crawler, browser automation, dependency installation, and model download tasks, set limits on network targets, bandwidth, duration, and output.
If the product does not currently provide fine-grained outbound network policies, constrain the access scope by combining a VPC, security groups, proxy services, data source permissions, and business gateways.
Credential and data minimization
Do not let untrusted code access data or credentials that it does not need.
Recommendations:
-
Mask and trim input data wherever possible, and provide only the minimum fields required by the current task.
-
Use task-scoped, short-lived credentials. Do not inject Alibaba Cloud account credentials, production database passwords, or long-lived third-party tokens.
-
Do not put sensitive content in
envs, metadata, command arguments, file names, logs, or exception stack traces. -
Filter sensitive information out of stdout, stderr, exceptions, generated files, and download links.
Environment variables are not a security boundary. Code running inside a Sandbox may read and output environment variables, so do not give high-privilege, long-lived credentials to untrusted code.
Resource and lifecycle controls
Untrusted code may enter an infinite loop, create many files, start background processes, or keep accessing the network. The business side must set resource and lifecycle boundaries.
As a best practice, always use try/finally or equivalent cleanup logic:
const sandbox = await Sandbox.create("code-interpreter-v1", {
timeoutMs: 300_000,
apiKey: process.env.E2B_API_KEY,
apiUrl: process.env.E2B_API_URL,
domain: process.env.E2B_DOMAIN,
});
try {
await sandbox.commands.run("python3 /tmp/task.py", { timeoutMs: 60_000 });
} finally {
await sandbox.kill();
}
Additional recommendations:
-
Set Sandbox timeouts and command timeouts.
-
Limit the output size, the number of files, and the download volume.
-
Track and terminate background processes.
-
Run the cleanup logic when an exception occurs, when a task times out or is canceled, and when the user closes the page.
-
Set concurrency and cost limits for high-risk tasks.
Pre-launch checks
Before launch, confirm at a minimum that:
-
Untrusted code cannot read production keys, files of other tenants, or unrelated external storage.
-
User input cannot trigger command injection, path traversal, arbitrary file overwrite, or arbitrary file deletion.
-
The Sandbox public network port does not expose any unauthenticated management interface.
-
Logs and output do not leak API keys, AccessKeys, tokens, user privacy, or download addresses.
-
After a task fails, times out, or is canceled, the Sandbox, background processes, and temporary credentials are all cleaned up.
If any of the preceding items cannot be verified, exposing this capability externally as part of the production pipeline is not recommended.