How to execute Python and Node.js in a Cloud Run Sandbox

1. Introduction

Overview

Cloud Run sandboxes provide a fast, secure, and isolated environment to execute untrusted code or run tools, such as code written by AI agents, within your existing service.

This codelab shows you how to execute both nodejs and python in a Cloud Run sandbox. You'll also see how to install a dependency within the sandbox using the --allow-egress flag.

You can learn more about sandboxes in the Cloud Run documentation for sandboxes, how to run code in a sandbox, and in the blog post.

What you'll learn

  • How to run code (nodejs and python) in a Cloud Run sandbox
  • How to install dependencies in a Cloud Run sandbox
  • How to use FastAPI with Cloud Run

2. Setup and Requirements

Prerequisites

  • You are logged into the Cloud Console.
  • You have previously deployed a Cloud Run service. For example, you can follow this quickstart to deploy a Cloud Run service to get started.

Set Environment Variables

First, make sure you have configured a project ID.

gcloud config set project <YOUR_PROJECT_ID>

You can verify your current project ID by running

gcloud config get project

Next, configure your preferred region.

export REGION=<YOUR_REGION>

3. Create the Service

Although this codelab runs nodejs and python code in the sandbox, you can run code in any language. Ensure that any command or tool you run is installed in your container image, as you'll learn how to below.

First, create a directory for the source code and cd into that directory.

mkdir sandbox-codelab && cd $_

Next, create a Dockerfile.

FROM python:3.11-slim

# Install Node.js to run both python and nodejs in sandbox
RUN apt-get update && apt-get install -y curl \
    && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
    && apt-get install -y nodejs \
    && rm -rf /var/lib/apt/lists/*

# Set working directory
WORKDIR /app

# Copy requirements and install them
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy the application code
COPY main.py .

# Run the FastAPI application using python
CMD ["python", "main.py"]

Next, create a requirements.txt file with the following content:

fastapi
uvicorn

Create a main.py file with the following content:

import os
import sys
import subprocess
import shlex
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import uvicorn

app = FastAPI()

def run_in_sandbox(language: str, code: str, dependency: str = None):
    # Setup commands
    if language == "python":
        run_cmd = f"python3 -c {shlex.quote(code)}"
        install_cmd = f"pip install --no-cache-dir {dependency} >&2" if dependency else ""
    elif language in ("node", "nodejs"):
        run_cmd = f"node -e {shlex.quote(code)}"
        install_cmd = f"npm install --cache /tmp/.npm-cache {dependency} >&2" if dependency else ""
    else:
        raise ValueError(f"Unsupported language: {language}")

    # Combine install and execution commands if dependency exists
    full_inner_cmd = f"{install_cmd} && {run_cmd}" if dependency else run_cmd

    # Build sandbox command
    # This binary is automatically injected into the container via the --sandbox-launcher deployment flag
    sandbox_cmd = [
        "/usr/local/gcp/bin/sandbox", 
        "do",
    ]
    
    if dependency:
        sandbox_cmd.extend(["--write", "--allow-egress"])
        
    sandbox_cmd.extend(["--", "/bin/bash", "-c", full_inner_cmd])

    return subprocess.run(
        sandbox_cmd,
        capture_output=True,
        text=True,
        timeout=15, # Increased timeout to allow for package downloads
    )

@app.get("/python")
async def execute_python():
    sandbox_code = "print(20 + 45)"
    try:
        result = run_in_sandbox("python", sandbox_code)

        return {
            "stdout": result.stdout,
            "stderr": result.stderr,
            "exit_code": result.returncode,
        }
    except subprocess.TimeoutExpired:
        return JSONResponse(status_code=408, content={"error": "Execution timed out"})
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})

@app.get("/nodejs")
async def execute_nodejs():
    sandbox_code = "const isOdd = require('is-odd'); console.log('Is 13 odd?', isOdd(13));"
    dependency = "is-odd"
    try:
        result = run_in_sandbox("nodejs", sandbox_code, dependency)

        return {
            "stdout": result.stdout,
            "stderr": result.stderr,
            "exit_code": result.returncode,
        }
    except subprocess.CalledProcessError as e:
        return JSONResponse(status_code=400, content={"error": f"Failed to install dependency: {e.stderr}"})
    except subprocess.TimeoutExpired:
        return JSONResponse(status_code=408, content={"error": "Execution timed out"})
    except Exception as e:
        return JSONResponse(status_code=500, content={"error": str(e)})


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

4. Deploy and Test

Now deploy to Cloud Run. Note the --sandbox-launcher flag and the beta release level.

gcloud beta run deploy sandbox-executor \
    --source . \
    --region $REGION \
    --no-allow-unauthenticated \
    --sandbox-launcher

Once deployed, record the Service URL in an environment variable.

SERVICE_URL=$(gcloud run services describe sandbox-executor --region $REGION --format 'value(status.url)')

First, try calling the python endpoint, which adds two numbers within the sandbox.

curl -X GET $SERVICE_URL/python \
    -H "Authorization: Bearer $(gcloud auth print-identity-token)"

You should see the following returned for the Python code:

{"stdout":"65\n","stderr":"","exit_code":0}

Now try the nodejs endpoint, which installs a dependency (is-odd) and uses it in the sandbox.

curl -X GET $SERVICE_URL/nodejs \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)"

You should see the following in the response (along with some npm logs in stderr):

{"stdout":"Is 13 odd? true\n","stderr":"...","exit_code":0}

5. Congratulations!

Congratulations on completing the codelab!

We recommend reviewing the Cloud Run documentation for sandboxes and how to run code in a sandbox.

What we've covered

  • How to run code in a Cloud Run sandbox
  • How to install dependencies in a Cloud Run sandbox
  • How to use FastAPI with Cloud Run

6. Clean up

To avoid inadvertent charges, (for example, if the Cloud Run service sandbox-executor is inadvertently invoked more times than your monthly Cloud Run invocation allocation in the free tier), you can either delete the Cloud Run service or delete the project you created in Step 2.

To delete a Cloud Run service, go to Cloud Run in the Cloud Console at https://console.cloud.google.com/run/ and delete the service you created in this codelab.

If you choose to delete the entire project, you can go to https://console.cloud.google.com/cloud-resource-manager, select the project you created in Step 2, and choose Delete. If you delete the project, you'll need to change projects in your Cloud SDK. You can view the list of all available projects by running gcloud projects list.