Skip to main content

Example: Untrusted user code

You implement this pattern when someone else’s code runs on your infrastructure: end users paste snippets, or an agent emits code you did not write. You never trust the text. You isolate it in a MicroVM, you bound CPU, memory, and time, and you validate before you execute.

What you accomplish

You reject oversized or disallowed submissions before you touch the API. You run each accepted submission in a dedicated sandbox (or a strictly managed pool). You always set timeouts. You avoid building shell commands by concatenating user input.

Threats you plan for

  • Injection: User code that escapes interpreters or shells.
  • Resource exhaustion: Infinite loops, huge memory use, fork bombs.
  • Data exfiltration: Code that reads environment secrets or calls the network (you combine this with Internet access policy).
  • Persistence: User code that writes malicious artifacts; you remove sandboxes when done.

Prerequisites

You completed Examples overview. You read AI code interpreter if you use runCode / run_code.

Step 1: Define policy constants in your service

You centralize limits so every code path shares the same rules.

Step 2: Create one sandbox per untrusted run

You do not reuse the same sandbox for unrelated users without a documented trust boundary. For the simplest model, you create and remove per request.

Step 3: Never interpolate user code into sh -c

You call the interpreter API (runCode / run_code) for user snippets. When you must use exec with user data (not code), you pass values through env or encoded files, not raw string glue. Unsafe (do not do this):
Safer direction: you upload the snippet to a file with a random name, then you exec a fixed command that reads that path: but you still sanitize path and length, and you prefer run_code when available.

Step 4: Log and map errors for your API

You catch SDK and HTTP errors. You return generic messages to end users; you keep details in server logs only. You map validated request fields into runUntrustedSnippet. You return a safe JSON shape to the client.

Practices you should follow

  • You add static scans (import blocklists, AST checks) when you support Python: this sits before run_code.
  • You disable or restrict outbound network at the platform layer when you run untrusted code.
  • You rate-limit per user and per org so abuse cannot exhaust your quota.
  • You read Internet access and Tailscale when networking is part of your product.

AI code interpreter

Structured interpreter results

Code execution

Exec vs interpreter