Taking Advantage of Cloud Run Sandboxes with Google Apps Script for Google Workspace

Gists

Deterministic Sub-Second Python and Bash Execution, Zero-Trust gVisor Isolation, and Zero Idle Cost

top image

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 ms), 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:

Google Apps Script × Cloud Run Sandboxes Architecture Figure 1: Architectural workflow linking Google Apps Script, Cloud Run FastAPI Runner, and gVisor Micro-Sandbox.


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:


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.

Cloud Run Sandboxes Test Suite Matrix Figure 2: Comprehensive 8-axis test suite matrix evaluating deterministic execution and security isolation.

The complete suite is implemented in gas/TestCases.js. The core verification logic includes:


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:00	Notice	Execution started
00:00:00	Info	================================================================================
00:00:00	Info	STARTING CLOUD RUN SANDBOX TEST SUITE (GAS EXECUTION)
00:00:00	Info	Target Base URL: https://cr-gas-sandbox-[PROJECT-HASH]-uc.a.run.app
00:00:00	Info	Started At     : 2026-09-09T00:00:00.000Z
00:00:00	Info	================================================================================
00:00:00	Info	Executing [TC-01] Basic Python Computation (2**32)...
00:00:04	Info	Executing [TC-02] Syntax Error Handling & Crash Resistance...
00:00:05	Info	Executing [TC-03] Infinite Loop DoS Defense (Timeout Enforcement)...
00:00:07	Info	Executing [TC-04] Metadata Server SSRF Isolation (169.254.169.254)...
00:00:08	Info	Executing [TC-05] Host Environment Variable Shielding...
00:00:09	Info	Executing [TC-06] Filesystem Write Protection (Ephemeral tmpfs)...
00:00:10	Info	Executing [TC-07] Outbound Network Egress Isolation...
00:00:12	Info	Executing [TC-08] Isolated Bash Subshell Command Execution...
00:00:13	Info
### 📊 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 (2**32)
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.
--------------------------------------------------------------------------------
[TC-07] Outbound Network Egress Isolation
Endpoint       : /test/egress-isolation
Verdict        : PASS - Outbound network traffic blocked by default; enabled only with flag
Timing         : Server=992.04ms, RoundTrip=1106ms
Sandbox Active : true
details        : Egress blocked without flag: PASS. Egress allowed with flag: PASS.
--------------------------------------------------------------------------------
[TC-08] Isolated Bash Subshell Command Execution
Endpoint       : /run
Verdict        : PASS - Bash subshell executed securely inside sandbox
Timing         : Server=338.78ms, RoundTrip=460ms
Sandbox Active : true
stdout         : Linux sandbox-[INSTANCE-UUID] 4.19.0-gvisor #1 SMP Sun Jan 10 15:06:54 PST 2016 x86_64 GNU/Linux
--------------------------------------------------------------------------------
00:00:13	Notice	Execution completed

All eight test vectors achieved a 100% PASS rate. In particular, TC-08 explicitly returned the kernel signature 4.19.0-gvisor, confirming gVisor process containment.


Latency and Performance Analysis

Measuring execution telemetry reveals distinct performance profiles between cold starts and warm executions:

Latency Breakdown: Cold Start vs Warm Execution Figure 3: Latency breakdown between cold-start container provisioning and warm micro-sandbox execution.


Cost Analysis and Safety Guardrails

Running external cloud services for automation often raises concerns about unexpected billing. In this architecture, costs are bounded by Google Cloud policies Ref and explicit service guardrails:

Google Cloud Always Free Tier Allocations & Cost Architecture Figure 4: Google Cloud Always Free tier allocations and zero-idle cost architecture.


Practical Application: Generating Multivariate Correlation Heatmaps on Google Sheets

While unit tests validate security and latency, the real value of Cloud Run Sandboxes emerges in solving everyday Google Workspace challenges that Apps Script cannot address natively.

A prime example is advanced scientific visualization. While Google Sheets provides standard bar and line charts, it completely lacks native support for bivariate or multivariate statistical visualizations—such as Pearson correlation matrix heatmaps, kernel density estimates, or regression confidence bands. Traditionally, developers were forced to either export datasets to external desktop environments or configure cumbersome third-party visualization services.

By combining Google Apps Script with Cloud Run Sandboxes, developers can bridge this gap seamlessly:

The Dynamic Python Visualization Script

In gas/PracticalDemo.js, Apps Script dynamically constructs and dispatches the following Python script to the Cloud Run runner:

import os
os.environ['MPLCONFIGDIR'] = '/tmp/mpl'
import io, json, base64
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

# Injected empirical dataset from Google Sheets
records = [
  {"Math": 95, "Physics": 92, "Chemistry": 88, "English": 72, "History": 68},
  # ... (15 rows injected dynamically from spreadsheet)
]
df = pd.DataFrame(records)

# Calculate Pearson correlation matrix
corr = df.corr()

# Configure publication-grade styling
plt.figure(figsize=(6.8, 5.2), dpi=150)
sns.set_theme(style='white')
cmap = sns.diverging_palette(230, 20, as_cmap=True)
ax = sns.heatmap(corr, annot=True, fmt='.2f', cmap=cmap, vmin=-1.0, vmax=1.0,
                 square=True, linewidths=0.6, cbar_kws={'shrink': 0.8})
plt.title('Student Performance: Multivariate Correlation Heatmap', fontsize=11, fontweight='bold', pad=12)
plt.tight_layout()

# Encode plot to Base64 PNG buffer
buf = io.BytesIO()
plt.savefig(buf, format='png', dpi=150)
plt.close()
buf.seek(0)
b64_png = base64.b64encode(buf.getvalue()).decode('utf-8')

# Output structured JSON to stdout
print(json.dumps({
    'status': 'success',
    'image_base64': b64_png,
    'variables': list(df.columns),
    'records_processed': len(df)
}))

This Python script is engineered with four deliberate architectural techniques:

Dynamic Script Generation via Gemini API

An essential architectural advantage of this setup is that the Python script does not need to be hard-coded. Developers can call the Gemini API directly from Apps Script with a natural language prompt—such as “Generate a Python Seaborn script to compute a correlation heatmap from this JSON table and output Base64 PNG”—to dynamically synthesize the visualization code on demand.

This workflow unlocks a powerful synergy:

Operational Advantages over Gemini Managed Agents

In my previous article, Taking Advantage of Gemini Managed Agents with Google Apps Script, Gemini Managed Agents provisioned a heavy-duty container (4 vCPU / 16 GB RAM) with a multi-hour persistent session. That architecture excels at exploratory, conversational agentic workflows where the agent navigates ambiguous tasks and self-heals over multiple turns.

However, for automated spreadsheet recalculation, scheduled batch reporting, or user-facing UI triggers, Cloud Run Sandboxes provides a distinctly superior operational profile:

The implementation is available in the repository as gas/PracticalDemo.js. To support Google Sheets creation and image embedding, ensure your appsscript.json includes the "https://www.googleapis.com/auth/spreadsheets" and "https://www.googleapis.com/auth/drive" OAuth scopes as documented in gas/setup_instructions.md.

Google Sheets Correlation Heatmap Result Figure 5: Google Sheets generated with multivariate student data and an embedded correlation heatmap rendered by Cloud Run Sandboxes (Matplotlib & Seaborn).

Real-World Execution Telemetry and Perceptual Performance

When executing runPracticalHeatmapDemo() directly from Google Apps Script, the perceptual speed is electrifying. The actual execution log demonstrates this seamless end-to-end flow:

00:00:01	Notice	Execution started
00:00:02	Info	================================================================================
00:00:02	Info	STARTING PRACTICAL DEMO: SPREADSHEET HEATMAP VIA CLOUD RUN SANDBOX
00:00:02	Info	Target Base URL: https://cr-gas-sandbox-[PROJECT-HASH]-uc.a.run.app
00:00:02	Info	Started At     : 2026-09-09T00:00:02.275Z
00:00:02	Info	================================================================================
00:00:02	Info	[Step 1/4] Creating new Google Spreadsheet with multivariate student metrics...
00:00:04	Info	Spreadsheet created: https://docs.google.com/spreadsheets/d/[SPREADSHEET-ID]/edit
00:00:04	Info	[Step 2/4] Reading data from Sheet and constructing JSON matrix payload...
00:00:04	Info	Extracted 15 rows across 5 variables.
00:00:04	Info	[Step 3/4] Dispatching payload to Cloud Run Sandboxes (POST /run)...
00:00:08	Info	Sandbox Server Time : 4161.7 ms
00:00:08	Info	Network Round-Trip  : 4343 ms
00:00:08	Info	Is Sandboxed (gVisor): true
00:00:08	Info	[Step 4/4] Converting Base64 output to Blob and embedding onto Google Sheet...
00:00:09	Info	================================================================================
00:00:09	Info	DEMO COMPLETED SUCCESSFULLY!
00:00:09	Info	Spreadsheet URL : https://docs.google.com/spreadsheets/d/[SPREADSHEET-ID]/edit
00:00:09	Info	Execution Time  : Server 4161.7 ms | Total 4343 ms
00:00:09	Info	================================================================================
00:00:10	Notice	Execution completed

The entire pipeline—creating a new Google Spreadsheet, styling header rows, reading data back, dispatching across HTTPS to Cloud Run, cold-loading heavy scientific libraries (pandas, numpy, matplotlib, seaborn) inside a gVisor micro-sandbox, calculating Pearson correlation coefficients, rendering the plot, streaming the Base64 PNG back, decoding into a Blob, and embedding it into the Sheet—finished in just 9 seconds of total wall-clock time (with only 4.16 seconds of Cloud Run server compute).

Visual Layout and Analytical Fidelity

Examining the resulting Google Sheet (Figure 5) reveals exceptional publication quality:


Comparing Cloud Run Sandboxes and Gemini Managed Agents

Choosing between these two technologies from Google Apps Script requires evaluating the fundamental trade-offs between autonomous artificial intelligence and deterministic high-speed computation:

Cloud Run Sandboxes vs Gemini Managed Agents Figure 6: Strategic workload comparison: Cloud Run Sandboxes vs. Gemini Managed Agents.

Compute Specifications & Session Lifecycle Architecture Figure 7: Detailed compute specifications, hardware profiles, and session lifecycle comparison.

Architectural Trade-offs: Advantages and Limitations

Understanding the practical strengths and weaknesses of each runtime ensures optimal architectural decisions:

Practical Scenarios: When to Use Which Architecture

To maximize automation efficiency in Google Workspace, consider these proven deployment scenarios:


Summary

In this article, I demonstrated how to integrate Google Apps Script with Google Cloud Run Sandboxes to run dynamic Python and Bash workloads securely, deterministically, and with blistering speed. By offloading compute tasks to gVisor micro-sandboxes, Google Workspace automations gain the power to safely execute AI-generated scripts on demand and perform advanced data science without server maintenance overhead.

Key takeaways from this implementation:


Getting Started and Repository

For comprehensive step-by-step setup guides, prerequisite configurations, one-click deployment procedures, and troubleshooting instructions, please refer to the complete documentation in the GitHub repository:

 Share!