Untrusted Code

更新时间:
复制 MD 格式

FC Agent Sandbox is commonly used to run AI-generated code, user-uploaded scripts, automated tests, data analysis jobs, and third-party dependencies. This kind of code should be treated as untrusted by default. FC Agent Sandbox can reduce execution risk, but it does not replace input validation, least privilege, network control, resource limits, or output review.

Assess the risk level first

Before integration, determine which risk category the task belongs to:

  • Low risk: runs fixed internal scripts, input comes from trusted systems, and no sensitive data is accessed.

  • Medium risk: runs AI-generated code or user-uploaded files, but processes only redacted data and has a controlled access scope.

  • High risk: runs external user code, installs third-party dependencies, accesses the public internet, or processes production data.

  • Do not allow by default: tasks that require high-privilege cloud account credentials, write access to production databases, access to internal management addresses, or cross-tenant shared writable directories.

The higher the risk, the more you should rely on dedicated sandboxes, short timeouts, short-lived credentials, controlled networks, isolated working directories, and stricter output review.

Inputs and command execution

Do not concatenate user input directly into shell commands. User input may contain command separators, path traversal, redirection, 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 parameters must be passed, use structured arguments, whitelist enums, or escaping libraries, and record the allowed parameter ranges. Do not allow model-generated commands to bypass business-side validation and execute directly.

File access control

Create a dedicated working directory for each task and allow read/write access only where required.

const taskId = "task-001";
const workdir = `/tmp/tasks/${taskId}`;
await sandbox.files.makeDir(workdir);
await sandbox.files.write(`${workdir}/input.txt`, userInput);

Recommendations:

  • File paths should be generated by the business system. Do not use full user-provided paths directly.

  • Validate path prefixes before deleting files to avoid removing system directories, shared directories, or directories that belong to other tasks.

  • Restrict archive formats, sizes, nesting depth, and total extracted size before extraction.

  • Validate the source, size, type, and destination path before downloading files.

  • Scan and redact output files before returning them to users.

Network access control

Network access for untrusted code should follow the principle of minimum necessity.

Recommendations:

  • Do not expose internal management addresses, database endpoints, metadata services, CI/CD services, or enterprise internal APIs to untrusted code by default.

  • When access to external data sources is required, prefer forwarding through a business-side proxy and enforce authentication, auditing, rate limits, and destination whitelists at the proxy layer.

  • Do not treat public sandbox ports as long-lived service entry points. Temporary preview services should have authentication, expiration, and access-scope restrictions.

  • Set limits on network destinations, bandwidth, time, and output for crawling, browser automation, dependency installation, and model download tasks.

If the current product capability does not provide fine-grained outbound network policies, constrain access jointly through VPCs, security groups, proxy services, data-source permissions, and business gateways.

Credential and data minimization

Do not let untrusted code access data or credentials it does not need.

Recommendations:

  • Redact and trim input data as much as possible, and provide only the minimum fields required by the current task.

  • Use task-level short-lived credentials. Do not inject primary-account credentials, production database passwords, or long-lived third-party tokens.

  • Do not place sensitive payloads in envs, metadata, command arguments, file names, logs, or exception stacks.

  • Filter sensitive information from 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 hand long-lived high-privilege credentials to untrusted code.

Resource and lifecycle control

Untrusted code may loop forever, create many files, spawn background processes, or keep accessing the network. The business side must enforce resource and lifecycle boundaries.

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();
}

Also recommended:

  • Set sandbox timeouts and command timeouts.

  • Limit output size, file count, and download volume.

  • Track and terminate background processes.

  • Run cleanup logic on exceptions, timeouts, task cancellation, and user page close events.

  • Set concurrency and cost ceilings for high-risk tasks.

Pre-production checklist

Before launch, confirm at least the following:

  • Untrusted code cannot read production secrets, files from other tenants, or unrelated external storage.

  • User input cannot trigger command injection, path traversal, arbitrary file overwrite, or arbitrary file deletion.

  • No unauthenticated management interface is exposed through public sandbox ports.

  • Logs and output do not leak API keys, AccessKeys, tokens, user privacy data, or download addresses.

  • Sandbox instances, background processes, and temporary credentials are cleaned up after task failure, timeout, or cancellation.

If any of the above cannot be verified, this capability should not be exposed externally as a production path.