search

Safely run AI-generated code in Cloud Run sandboxes

person By Greg Block
source Source: Cloud Blog
calendar_today
schedule 5 min read

Here’s a question we hear often at Google Cloud: How do you safely run AI-generated code or untrusted binaries without putting your host application, data, and cloud credentials at risk? In other words, how do you give AI-written programs a safe space to run — one that keeps them completely separate from your trusted programs with higher privileges? Until now, developers had to build complex sandboxing infrastructure using container clusters or pay for specialized third-party microVM runtimes. Today, at WeAreDevelopers World Congress, we are announcing Google Cloud Run sandboxes in public preview. Cloud Run sandboxes are a native, secure, and ultra-fast runtime environment built specifically for executing untrusted code and agent workloads, starting in milliseconds. In the following example, we send requests to safely execute untrusted Python code on a Cloud Run service that starts, executes, and stops 1,000 sandboxes with an average of 500ms latency: In this post, we’ll share more about the feature and core use cases. What is a Cloud Run sandbox? Cloud Run sandboxes are lightweight, isolated execution boundaries that you can spawn near-instantly within your existing Cloud Run service instances. Whether you need to let an LLM run a dynamically generated Python script to calculate business margins or spin up a headless browser to perform web research, Cloud Run sandboxes give you a secure, isolated sandbox to run these tasks without leaving your serverless environment. Core use cases LLM code interpreters: Build advanced data analysis features into your AI products. Let your models write and execute Python, R, or SQL code to analyze datasets, generate charts, and perform complex math securely. Headless browsers: Give your agents a secure environment to run browsers. Safely scrape web pages, take screenshots, and automate web workflows without risking your host machine. User-submitted code execution: Beyond AI, platforms hosted on Cloud Run can use sandboxes to safely run custom scripts, plugins, or webhooks uploaded by their own end-users. How it works: The developer experience Enabling sandboxes on your Cloud Run service is as simple as adding a single flag to your deployment. Step 1: Enable the sandbox launcher When deploying your Cloud Run service, enable the sandbox launcher via gcloud or your YAML configuration: code_block <ListValue: [StructValue([(‘code’, ‘gcloud beta run deploy my-agent-service \\r\n –image=gcr.io/my-project/agent-image \\r\n –sandbox-launcher’), (’language’, ‘’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fbfc240a730>)])]> Step 2: Spawn a sandbox natively in your code Once enabled, a lightweight sandbox CLI binary is automatically mounted into your execution environment. Your agent application can spawn sandboxes programmatically using standard subprocess calls. Here is how easily you can run an untrusted Python script generated by an LLM: code_block <ListValue: [StructValue([(‘code’, ‘import subprocess\r\n\r\ndef run_untrusted_code(llm_code: str):\r\n # 1. Write the untrusted LLM code to a local file\r\n with open("/tmp/generated_script.py", “w”) as f:\r\n f.write(llm_code)\r\n \r\n # 2. Run it inside the secure sandbox\r\n # The sandbox shares your container's filesystem tools but runs in a secure silo\r\n result = subprocess.run(\r\n [“sandbox”, “do”, “–”, “python3”, “/tmp/generated_script.py”],\r\n capture_output=True,\r\n text=True,\r\n timeout=10\r\n )\r\n \r\n return result.stdout if result.returncode == 0 else result.stderr’), (’language’, ‘’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fbfc246abe0>)])]> Security by design: Zero-trust by default Cloud Run sandboxes are engineered to protect your host application and cloud resources from malicious or erroneous code execution. The runtime enforces three critical security boundaries: 1. Credential and environment isolation: These sandboxes do not have access to the Cloud Run service’s environment variables nor do they have the ability to call the Google Cloud metadata server. 2. Locked-down network egress (deny-by-default): By default, sandboxes have zero outbound network access. If your agent is tricked into running a script that attempts to exfiltrate data to a malicious server, the network request is blocked at the system layer. Egress can be enabled only when explicitly requested: code_block <ListValue: [StructValue([(‘code’, ‘sandbox do –allow-egress – curl https://api.github.com’), (’language’, ‘’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fbfc246a940>)])]> 3. Safe filesystem overlay: The sandbox runs with a read-only view of your container’s filesystem (allowing it to use your installed packages, Python runtimes, and binaries) but writes all changes to an isolated, temporary memory overlay. Once the sandbox execution ends, all generated files are discarded. Though you can still import and export files as needed for re-use across sandboxes: code_block <ListValue: [StructValue([(‘code’, ‘# Write data from the sandbox to an archive file that can be persisted\r\nsandbox do –write –export-tar=/tmp/work.tar \\r\n – /bin/bash -c “mkdir -p /tmp/work && echo 'task-complete' > /tmp/work/status.txt”\r\n\r\n# Import the archive file in a new sandbox\r\nsandbox do –write –import-tar=/tmp/work.tar \\r\n – /bin/bash -c “cat /tmp/work/status.txt”’), (’language’, ‘’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fbfc246ad90>)])]> ADK and ComputeSDK built-in support Cloud Run sandboxes will be supported in the next version of Agent Development Kit with a new CloudRunSandboxCodeExecutor. This integration gives your ADK agents running on Cloud Run the ability to execute code in one single line: code_block <ListValue: [StructValue([(‘code’, ‘from google.adk.agents import Agent\r\nfrom google.adk.integrations.cloud_run import CloudRunSandboxCodeExecutor\r\n\r\nanalyst_agent = Agent(\r\n name=“cloud_run_data_analyst”,\r\n model=“gemini-3.1-pro-preview”,\r\n system_instruction=(\r\n “You are an expert data analyst. Write and execute Python code to answer “\r\n “user questions and process data safely."\r\n ),\r\n code_executor=CloudRunSandboxCodeExecutor(),\r\n)’), (’language’, ‘’), (‘caption’, <wagtail.rich_text.RichText object at 0x7fbfc246af10>)])]> Cloud Run sandboxes were also added to ComputeSDK, a vendor agnostic SDK for running sandboxes. This SDK allows you to either invoke sandboxes remotely from outside the Cloud Run service or use them directly as a local tool on the service. You can learn how to use this SDK for Cloud Run sandboxes here. Get started today Unlike dedicated sandbox hosting platforms that charge high premiums for on-demand virtual machines, Cloud Run sandboxes run directly on your existing allocated CPU and memory. Because the sandboxes share the resources of your running instances, there is no additional cost or premium to use this feature. You can check out our documentation here.

Related articles

architect

Cloudflare WAF protects WordPress applications from two high-severity vulnerabilities

Cloudflare has deployed two WAF rules in response to high-severity vulnerabilities disclosed to us by the WordPress security team. The new rules protect all Cloudflare customers using affected WordPress versions, but customers should still update immediately to a patched release

architect

Eclipse Dataspace Components on AWS: Cost optimization strategies

When you deploy Eclipse Dataspace Components (EDC) connectors on AWS, one of the first challenges you face is predicting and controlling the cost of the required infrastructure. Without clear benchmarks, it is difficult to make informed decisions about workload sizing, environment configuration, and long-term investment. Part 1 of this 3-part blog series covered the fundamentals

architect

Eclipse Dataspace Components on AWS: Architecture patterns in production

Running Eclipse Dataspace Components (EDC) connectors in production on AWS requires deliberate architecture decisions around isolation, managed services, and security layering. In Part 1 of this series, we covered the fundamentals of data space architectures and EDC per the International Data Space Association’s (IDSA) standards. If you are new to EDC, we recommend starting there.