Taking Advantage of Cloud Run Sandboxes with Google Apps Script for Google Workspace
Abstract
While secure sandboxes are pivotal for running Generative AI-generated code safely, connecting Google Cloud Run Sandboxes (gVisor) directly to Google Apps Script unlocks a vastly broader horizon. Beyond executing AI-drafted scripts on the fly, this complementary architecture empowers Google Workspace with deterministic Python data science (Pandas, Seaborn) and Bash execution in 200-450 ms. With zero-trust micro-isolation, zero-token data ingestion, and zero idle cost, it elevates Workspace automations far beyond standard V8 runtime constraints.
Introduction
Google Apps Script (GAS) Ref is a cornerstone of Google Workspace automation across Sheets, Docs, Forms, and Drive. Yet, developers often hit hard limits:
- Standard accounts enforce a strict 6-minute timeout.
- The environment runs only JavaScript on V8, precluding native Linux binaries or external compilers.
- When an unhandled exception occurs, the entire script halts abruptly.
Recently, in my article "Taking Advantage of Gemini Managed Agents with Google Apps Script" Ref , I showed how to break past these limits by connecting Apps Script to a persistent Linux sandbox provisioned by Gemini Managed Agents Ref . Using my Go CLI tool ggsrun Ref for direct streaming between the sandbox and Google Drive, that architecture handles heavy, multi-turn agentic workflows. Examples include Playwright scraping across multiple viewports and audio transcoding with FFmpeg.
Gemini Managed Agents excel at autonomous, multi-step reasoning. However, they rely on LLM prompts via the Interactions API. This adds conversational inference overhead, pushing response latencies to several seconds or tens of seconds while burning token quotas (such as 200k TPM) Ref . Many everyday Workspace automations do not need an LLM. Tasks like mathematical evaluations, string parsing, regular expression matching, and shell commands require deterministic, instant execution without prompt ambiguity or token limits.
The breakthrough moment came when I encountered Romin Irani's masterfully crafted and inspiring article, "Safely Running Untrusted Code: A Hands-On Guide to Google Cloud Run Sandboxes" Ref . In his exceptional guide, Irani brilliantly illuminated how Google Cloud Run Sandboxes leverage gVisor application kernel technology to deliver lightweight, ephemeral micro-isolation for arbitrary code execution with remarkable simplicity and elegance. Reading his hands-on exploration sparked an immediate insight: What if we connect this powerful sandbox directly to Google Apps Script? Could this be the key to supercharging Google Workspace automations with instant, secure dynamic execution?
That spark inspired me to plan, design, and thoroughly refine the project presented here. Fundamentally, secure sandboxes have become an indispensable cornerstone in the era of Generative AI. When large language models like Gemini generate code on the fly, they produce untrusted scripts that demand strict execution isolation to shield host environments from unintended side effects, resource exhaustion, or security compromises. I myself have continuously explored and proposed sandboxing approaches for Google Apps Script to safely execute AI-generated code Ref , Ref . Yet, liberating this sandboxed execution capability so that it can be directly orchestrated from Google Apps Script unlocks a vastly broader horizon. It transforms Apps Script from a bounded JavaScript runtime into an agile command center. Beyond safely running AI-generated scripts in real time, it empowers Google Workspace to seamlessly offload high-performance Python and Bash workloads-spanning advanced statistics, scientific plotting with Pandas and Seaborn, and complex data transformations-that were previously unattainable within Apps Script alone.
In this article, I introduce this complementary architecture powered by Google Cloud Run Sandboxes (--sandbox-launcher) Ref . By pairing gVisor Ref micro-virtualization with second-generation Cloud Run instances Ref , Apps Script can dispatch dynamic Python and Bash scripts over standard REST HTTP calls. The benefits are clear: sub-second execution (200 to 450 milliseconds), zero-trust process isolation, and zero idle maintenance costs. Together, Cloud Run Sandboxes and Gemini Managed Agents give developers a comprehensive automation toolkit for Google Workspace.
Architecture: Cloud Run Sandboxes for Google Apps Script
Cloud Run Sandboxes compartmentalize untrusted code execution using gVisor application kernel technology. Integrating this infrastructure with Google Apps Script offers four major benefits:
- Dynamic code execution without image rebuilding: You never need to rebuild or redeploy container images when script logic changes. Apps Script dynamically generates Python or Bash code strings and posts them to the Cloud Run runner for immediate execution.
- Crash resilience against runaway scripts: If an offloaded script triggers a segmentation fault or an infinite loop (
while True: pass), gVisor isolates and terminates only the child process via SIGKILL. The parent FastAPI runner remains healthy and returns a clean JSON error response. - Deterministic sub-second latency: Because the sandbox forks directly inside a running container, it avoids cold VM boots and prompt delays, running guest code in 200 to 450 milliseconds.
- Zero-idle cost management: Setting
--min-instances=0allows Cloud Run to scale to zero when idle. Combined with Google Cloud's Always Free tier Ref , everyday automation incurs zero idle maintenance cost.
System Architecture and Processing Workflow
The architecture connects three layers: the Google Apps Script orchestrator, the Cloud Run FastAPI proxy runner, and the gVisor micro-sandbox isolation layer. For complete, step-by-step setup and deployment instructions, please refer to the detailed guide in the GitHub Repository .
Execution flows through three sequential stages:
- Stage 1: Dispatch from Google Apps Script - Apps Script sends an HTTPS POST request with a JSON payload containing the code snippet, language (Python or Bash), timeout, and security override flags. Core logic is implemented in
gas/Code.jsandgas/Auth.js. - Stage 2: Execution by FastAPI Proxy Runner - A lightweight Python service on Cloud Run Gen2 (
cloud_run/main.py) receives the payload. It invokes/usr/local/gcp/bin/sandbox do -- <command>, capturing wall-clock runtime, exit codes, stdout, and stderr. - Stage 3: Ephemeral isolation in gVisor - The gVisor sandbox intercepts every guest system call. It blocks access to the Google Cloud Metadata Server (169.254.169.254) to eliminate SSRF risks, strips host environment variables, enforces a read-only root filesystem, and shuts down external network egress by default.
8-Axis Verification Suite from Google Apps Script
To verify both functional accuracy and security boundaries, I designed and executed an 8-axis test suite directly from Google Apps Script.
The complete suite is implemented in gas/TestCases.js. The core verification logic includes:
- TC-01: Basic Computation - Evaluates deterministic Python arithmetic (
print(2**32)). Expected result:4294967296with exit code 0. Full test definition:gas/TestCases.js:TC-01. - TC-02: Syntax Error Handling - Injects an invalid syntax payload (
print('unclosed string literal )) to verify crash resistance. Expected result: Structured error JSON containingSyntaxErrorwithout container failure. Full test definition:gas/TestCases.js:TC-02. - TC-03: Infinite Loop DoS Defense - Runs an infinite loop (
while True: pass) with a 2.0-second timeout. Expected result: gVisor terminates the guest process cleanly after 2.0 seconds via SIGKILL. Full test definition:gas/TestCases.js:TC-03. - TC-04: Metadata Server SSRF Isolation - Probes
169.254.169.254to attempt service account token extraction. Expected result: Request blocked withNetwork is unreachable. Full test definition:gas/TestCases.js:TC-04. - TC-05: Host Environment Variable Shielding - Dumps guest environment variables to check host credential leakage. Expected result: GCP credentials and host variables are completely absent. Full test definition:
gas/TestCases.js:TC-05. - TC-06: Filesystem Write Protection - Attempts to write to the container root filesystem. Expected result: Blocked with Read-only file system by default; allowed only in isolated tmpfs with
--write. Full test definition:gas/TestCases.js:TC-06. - TC-07: Outbound Network Egress Isolation - Attempts an outbound TCP connection to public DNS (
1.1.1.1:53). Expected result: Connection rejected by default; allowed only with--allow-egress. Full test definition:gas/TestCases.js:TC-07. - TC-08: Isolated Bash Subshell Execution - Runs
uname -a && idin a Bash subshell. Expected result: Returns the kernel signature4.19.0-gvisor, confirming gVisor containment. Full test definition:gas/TestCases.js:TC-08.
Execution Log and Verification Results
The following execution log was captured directly from the Google Apps Script logger during my verification run. Project hashes are sanitized as [PROJECT-HASH], container UUIDs are sanitized as [INSTANCE-UUID], and timestamps are normalized to start at 00:00:00:
00:00:00NoticeExecution started
00:00:00Info================================================================================
00:00:00InfoSTARTING CLOUD RUN SANDBOX TEST SUITE (GAS EXECUTION)
00:00:00InfoTarget Base URL: https://cr-gas-sandbox-[PROJECT-HASH]-uc.a.run.app
00:00:00InfoStarted At : 2026-09-09T00:00:00.000Z
00:00:00Info================================================================================
00:00:00InfoExecuting [TC-01] Basic Python Computation (2**32)...
00:00:04InfoExecuting [TC-02] Syntax Error Handling & Crash Resistance...
00:00:05InfoExecuting [TC-03] Infinite Loop DoS Defense (Timeout Enforcement)...
00:00:07InfoExecuting [TC-04] Metadata Server SSRF Isolation (169.254.169.254)...
00:00:08InfoExecuting [TC-05] Host Environment Variable Shielding...
00:00:09InfoExecuting [TC-06] Filesystem Write Protection (Ephemeral tmpfs)...
00:00:10InfoExecuting [TC-07] Outbound Network Egress Isolation...
00:00:12InfoExecuting [TC-08] Isolated Bash Subshell Command Execution...
00:00:13Info
๐ CLOUD RUN SANDBOX ร GAS VERIFICATION RUN REPORT
- Total Tests Executed: 8
- Passed: 8 / 8
- Failed: 0 / 8
- Total Execution Wall Time: 12.44 seconds
- Overall Verdict: โ ALL TESTS PASSED
| Test ID | Test Name | HTTP | Server Time | Network RTT | Sandbox Active | Status |
|---|---|---|---|---|---|---|
| TC-01 | Basic Python Computation (2**32) | 200 | 449.34 ms | 3609 ms | gVisor (True) | โ PASS |
| TC-02 | Syntax Error Handling & Crash Resistance | 200 | 201.43 ms | 322 ms | gVisor (True) | โ PASS |
| TC-03 | Infinite Loop DoS Defense (Timeout Enforcement) | 200 | 2003.96 ms | 2118 ms | gVisor (True) | โ PASS |
| TC-04 | Metadata Server SSRF Isolation (169.254.169.254) | 200 | 716.68 ms | 874 ms | gVisor (True) | โ PASS |
| TC-05 | Host Environment Variable Shielding | 200 | 411.31 ms | 539 ms | gVisor (True) | โ PASS |
| TC-06 | Filesystem Write Protection (Ephemeral tmpfs) | 200 | 641.73 ms | 757 ms | gVisor (True) | โ PASS |
| TC-07 | Outbound Network Egress Isolation | 200 | 992.04 ms | 1106 ms | gVisor (True) | โ PASS |
| TC-08 | Isolated Bash Subshell Command Execution | 200 | 338.78 ms | 460 ms | gVisor (True) | โ PASS |
๐ Detailed Execution Breakdown & Raw Outputs
[TC-01] Basic Python Computation (232)**
- Endpoint :
/run - Verdict: PASS - Correct computation result returned (4294967296)
- Timing : Server=449.34ms, RoundTrip=3609ms
- Sandbox Active : true
- stdout :
4294967296
[TC-02] Syntax Error Handling & Crash Resistance
- Endpoint :
/run - Verdict: PASS - Container remained healthy, structured error JSON safely returned
- Timing : Server=201.43ms, RoundTrip=322ms
- Sandbox Active : true
- stderr :
SyntaxError: unterminated string literal (detected at line 1)
[TC-03] Infinite Loop DoS Defense (Timeout Enforcement)
- Endpoint :
/run - Verdict: PASS - Process terminated cleanly after 2.0s without hanging server
- Timing : Server=2003.96ms, RoundTrip=2118ms
- Sandbox Active : true
- stderr :
Execution timed out after 2.0 seconds
[TC-04] Metadata Server SSRF Isolation (169.254.169.254)
- Endpoint :
/test/metadata-isolation - Verdict: PASS - Metadata server unreachable from sandbox (SSRF Blocked)
- Timing : Server=716.68ms, RoundTrip=874ms
- Sandbox Active : true
- details:
ACCESS_BLOCKED: URLError: <urlopen error [Errno 101] Network is unreachable>
[TC-05] Host Environment Variable Shielding
- Endpoint :
/test/env-isolation - Verdict: PASS - Host GCP credentials and environment variables fully masked
- Timing : Server=411.31ms, RoundTrip=539ms
- Sandbox Active : true
- details: Sensitive host environment variables are properly masked from sandbox guest.
[TC-06] Filesystem Write Protection (Ephemeral tmpfs)
- Endpoint :
/test/fs-isolation - Verdict: PASS - Read-only filesystem enforced by default; write permitted only with flag
- Timing : Server=641.73ms, RoundTrip=757ms
- Sandbox Active : true
- details: Write blocked without flag: PASS. Write permitted with flag: PASS.
Comments
No comments yet. Start the discussion.