Skip to content

An open-source, faster Devin alternative

TypeScript

Add gRPC support for high-performance sandbox operations

motatoesb5a2fc52614b
diff --git a/Cargo.toml b/Cargo.toml
index 65e405d7..6e587d95 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
name = "isolate"
version = "0.1.0"
edition = "2021"
-description = "Minimal Linux sandbox with HTTP API"
+description = "Minimal Linux sandbox with HTTP API and gRPC support"
[target.'cfg(target_os = "linux")'.dependencies]
nix = { version = "0.29", features = ["process", "mount", "sched", "resource", "user", "fs", "signal"] }
@@ -18,3 +18,8 @@ uuid = { version = "1", features = ["v4"] }
tower-http = { version = "0.5", features = ["cors", "trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"
+tonic = "0.12"
+prost = "0.13"
+
+[build-dependencies]
+tonic-build = "0.12"
diff --git a/Dockerfile b/Dockerfile
index d0981e31..90a1a0bb 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,8 +1,14 @@
FROM rust:1.83-slim-bookworm AS builder
+# Install protobuf compiler for gRPC
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ protobuf-compiler \
+ && rm -rf /var/lib/apt/lists/*
+
WORKDIR /app
-COPY Cargo.toml ./
+COPY Cargo.toml build.rs ./
COPY src ./src
+COPY proto ./proto
# Build without Cargo.lock to avoid version mismatch
RUN cargo build --release
@@ -28,7 +34,8 @@ RUN curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o
COPY --from=builder /app/target/release/isolate /usr/local/bin/isolate
EXPOSE 8080
+EXPOSE 50051
-# Default to server mode
+# Default to server mode with both HTTP and gRPC
ENTRYPOINT ["/usr/local/bin/isolate"]
-CMD ["serve", "--port", "8080"]
+CMD ["serve", "--port", "8080", "--grpc-port", "50051"]
diff --git a/README.md b/README.md
index 45f0be8d..611f5c7d 100644
--- a/README.md
+++ b/README.md
@@ -23,6 +23,8 @@ Coding agent creating a PR in an isolated sandbox:
- **Resource limits** - CPU time, memory, file size, open files
- **Stateful sessions** - files and environment variables persist across requests
- **HTTP API** - easy integration with any language/tool
+- **gRPC API** - high-performance binary protocol for low-latency operations
+- **Python SDK** - native Python client with async support
## Quick Start
@@ -142,31 +144,38 @@ The sandbox includes:
## Architecture
```
-HTTP Request
- │
- ▼
-┌─────────────────┐
-│ Axum Server │
-└────────┬────────┘
- │
- ▼
-┌─────────────────┐
-│ spawn_blocking │ (tokio blocking task)
-└────────┬────────┘
- │
- ▼
-┌─────────────────┐
-│ clone() with │ CLONE_NEWPID | CLONE_NEWNS
-│ namespaces │
-└────────┬────────┘
- │
- ▼
-┌─────────────────┐
-│ Child Process │
-│ - chroot │
-│ - setrlimit │
-│ - execvpe │
-└─────────────────┘
+ HTTP Request (8080) gRPC Request (50051)
+ │ │
+ ▼ ▼
+ ┌───────────────┐ ┌───────────────┐
+ │ Axum Server │ │ Tonic Server │
+ └───────┬───────┘ └───────┬───────┘
+ │ │
+ └──────────┬───────────────────────┘
+ │
+ ▼
+ ┌─────────────────┐
+ │ Shared State │ (Sessions, Sandbox roots)
+ └────────┬────────┘
+ │
+ ▼
+ ┌─────────────────┐
+ │ spawn_blocking │ (tokio blocking task)
+ └────────┬────────┘
+ │
+ ▼
+ ┌─────────────────┐
+ │ clone() with │ CLONE_NEWPID | CLONE_NEWNS
+ │ namespaces │
+ └────────┬────────┘
+ │
+ ▼
+ ┌─────────────────┐
+ │ Child Process │
+ │ - chroot │
+ │ - setrlimit │
+ │ - execvpe │
+ └─────────────────┘
```
## Security Notes
@@ -248,18 +257,49 @@ curl https://your-app-name.fly.dev/health
## Benchmarks
-See [benchmarks/](./benchmarks/) for performance comparisons with E2B.
+See [benchmarks/](./benchmarks/) for full performance comparisons with E2B.
-**Summary (OpenSandbox on Fly.io vs E2B Cloud):**
+**Summary (OpenSandbox gRPC vs E2B Cloud):**
-| Metric | OpenSandbox | E2B | Notes |
-|--------|-------------|-----|-------|
-| Sandbox creation | 131ms | 274ms | OpenSandbox 2x faster |
-| Command execution | 111ms | 51ms | E2B faster (SDK vs HTTP) |
-| Git clone | 374ms | 648ms | OpenSandbox faster |
-| Concurrency (8x) | 14.9/sec | 2.55/sec | OpenSandbox 6x better throughput |
+| Metric | OpenSandbox | E2B | Winner |
+|--------|-------------|-----|--------|
+| Sandbox creation | 120ms | 232ms | **OpenSandbox 1.9x faster** |
+| Command execution | 28ms | 52ms | **OpenSandbox 1.9x faster** |
+| File write | 10ms | 34ms | **OpenSandbox 3.4x faster** |
+| File read | 9ms | 50ms | **OpenSandbox 5.5x faster** |
+| Git clone workflow | 756ms | 1322ms | **OpenSandbox 1.7x faster** |
+| Concurrency (8x) | 27.5/sec | 11.8/sec | **OpenSandbox 2.3x faster** |
-OpenSandbox excels at concurrent workloads and git operations. E2B has lower per-command latency due to native SDK (OpenSandbox SDK planned).
+**OpenSandbox wins every category** with the gRPC SDK and edge deployment.
+
+## Python SDK
+
+Install the SDK for high-performance gRPC access:
+
+```bash
+pip install opensandbox # or: pip install -e sdk/python
+```
+
+Usage:
+
+```python
+from opensandbox import OpenSandbox
+
+async with OpenSandbox("https://your-server.fly.dev") as client:
+ sandbox = await client.create()
+
+ # Run commands (fast - uses gRPC)
+ result = await sandbox.run("echo hello")
+ print(result.stdout)
+
+ # File operations (fast - native, no shell)
+ await sandbox.write_file("/tmp/test.py", "print('hello')")
+ content = await sandbox.read_file_text("/tmp/test.py")
+
+ await sandbox.destroy()
+```
+
+See [sdk/python/README.md](./sdk/python/README.md) for full documentation.
## Similar Projects & Inspiration
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 4b9bef92..212ded3f 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -4,95 +4,111 @@ Benchmark suite to compare OpenSandbox with E2B cloud sandboxes.
## Results Summary
-Benchmarks run against OpenSandbox deployed on Fly.io (`https://opensandbox-test.fly.dev`) and E2B cloud.
+Benchmarks run against OpenSandbox deployed on Fly.io (with gRPC SDK) and E2B cloud.
+
+### Overall: OpenSandbox Wins Every Category 🚀
+
+| Metric | OpenSandbox gRPC | E2B | Winner |
+|--------|------------------|-----|--------|
+| **Sandbox Creation** | 120 ms | 232 ms | **OpenSandbox 1.9x faster** |
+| **Sandbox Destroy** | 16 ms | 108 ms | **OpenSandbox 6.6x faster** |
+| **Command Execution** | 28 ms | 52 ms | **OpenSandbox 1.9x faster** |
+| **File Write** | 10 ms | 34 ms | **OpenSandbox 3.4x faster** |
+| **File Read** | 9 ms | 50 ms | **OpenSandbox 5.5x faster** |
+| **Workflow Total** | 756 ms | 1322 ms | **OpenSandbox 1.7x faster** |
+| **Concurrency (8x)** | 27.5/s | 11.8/s | **OpenSandbox 2.3x faster** |
### 1. Sandbox Creation Time
| Provider | Create Avg (ms) | Destroy Avg (ms) |
|----------|-----------------|------------------|
-| OpenSandbox | 131 | 85 |
-| E2B | 274 | 113 |
+| OpenSandbox gRPC | 120 | 16 |
+| E2B | 232 | 108 |
-**OpenSandbox is ~2x faster** at creating new sandbox sessions.
+**OpenSandbox is ~2x faster** at creating and **6.6x faster** at destroying sandbox sessions.
### 2. Command Execution Latency
-| Command | OpenSandbox (ms) | E2B (ms) | Winner |
+| Command | OpenSandbox gRPC (ms) | E2B (ms) | Winner |
|---------|------------------|----------|--------|
-| echo | 67 | 61 | E2B |
-| pwd | 89 | 39 | E2B |
-| ls | 93 | 42 | E2B |
-| uname | 65 | 38 | E2B |
-| git --version | 110 | 62 | E2B |
-| **Overall Avg** | **111** | **51** | **E2B** |
-
-**E2B is ~2x faster** for individual command execution. This is likely due to E2B's native SDK vs OpenSandbox's HTTP API overhead.
+| echo | 76 | 65 | E2B |
+| pwd | 40 | 88 | **OpenSandbox** |
+| ls | 43 | 72 | **OpenSandbox** |
+| env | 41 | 41 | Tie |
+| python_version | 12 | 50 | **OpenSandbox** |
+| git_version | 16 | 46 | **OpenSandbox** |
+| uname | 13 | 39 | **OpenSandbox** |
+| cat_etc_os | 13 | 43 | **OpenSandbox** |
+| loop_100 | 12 | 40 | **OpenSandbox** |
+| calculate | 11 | 36 | **OpenSandbox** |
+| **Overall Avg** | **28** | **52** | **OpenSandbox** |
+
+**OpenSandbox is ~1.9x faster** for command execution with the gRPC SDK.
### 3. File Operations
-| Operation | OpenSandbox (ms) | E2B (ms) |
-|-----------|------------------|----------|
-| Write 100B | 209 | 34 |
-| Write 1KB | 68 | 62 |
-| Read 100B | 114 | 33 |
-| Read 1KB | 204 | 32 |
+| Operation | OpenSandbox gRPC (ms) | E2B (ms) | Winner |
+|-----------|------------------|----------|--------|
+| Write 100B | 10 | 36 | **OpenSandbox 3.6x** |
+| Write 1KB | 10 | 32 | **OpenSandbox 3.2x** |
+| Read 100B | 9 | 36 | **OpenSandbox 4x** |
+| Read 1KB | 9 | 63 | **OpenSandbox 7x** |
-**E2B is faster** for file operations. OpenSandbox uses shell commands (base64 encoding) for file transfers while E2B has native file APIs.
+**OpenSandbox is 3-7x faster** for file operations with native gRPC file APIs (no shell/base64 overhead).
### 4. Realistic Workflow (Git Clone + Edit)
-| Step | OpenSandbox (ms) | E2B (ms) |
-|------|------------------|----------|
-| sandbox_create | 122 | 125 |
-| mkdir | 220 | 130 |
-| git_clone | 374 | 648 |
-| list_files | 69 | 43 |
-| write_file | 211 | 34 |
-| read_readme | 88 | 38 |
-| git_status | 67 | 38 |
-| git_diff | 73 | 60 |
-| cleanup | 95 | 45 |
-| sandbox_destroy | 201 | 107 |
-| **Total** | **1529** | **1268** |
-
-Mixed results. **OpenSandbox is faster for git clone** (374ms vs 648ms), but E2B wins on file operations and overall workflow time.
+| Step | OpenSandbox gRPC (ms) | E2B (ms) | Winner |
+|------|------------------|----------|--------|
+| sandbox_create | 45 | 129 | **OpenSandbox** |
+| mkdir | 70 | 157 | **OpenSandbox** |
+| git_clone | 539 | 653 | **OpenSandbox** |
+| list_files | 16 | 44 | **OpenSandbox** |
+| write_file | 9 | 36 | **OpenSandbox** |
+| read_readme | 12 | 45 | **OpenSandbox** |
+| git_status | 13 | 45 | **OpenSandbox** |
+| git_diff | 14 | 40 | **OpenSandbox** |
+| cleanup | 13 | 67 | **OpenSandbox** |
+| sandbox_destroy | 14 | 105 | **OpenSandbox** |
+| **Total** | **756** | **1322** | **OpenSandbox 1.7x** |
+
+**OpenSandbox wins every step** of the workflow, with a **1.7x faster total time**.
### 5. Concurrency (Parallel Sandboxes)
| Concurrency | OpenSandbox Wall Time | OpenSandbox Throughput/s | E2B Wall Time | E2B Throughput/s |
|-------------|----------------------|--------------------------|---------------|------------------|
-| 1 | 505ms | 1.98 | 483ms | 2.07 |
-| 2 | 408ms | 4.90 | 652ms | 3.07 |
-| 4 | 460ms | 8.69 | 584ms | 6.85 |
-| 8 | 537ms | **14.90** | 3139ms | 2.55 |
+| 1 | 469ms | 2.13 | 519ms | 1.93 |
+| 2 | 250ms | 8.02 | 528ms | 3.79 |
+| 4 | 245ms | 16.30 | 519ms | 7.70 |
+| 8 | 291ms | **27.49** | 677ms | 11.81 |
**OpenSandbox scales much better** with concurrent workloads:
-- At 8 concurrent sandboxes, OpenSandbox maintains ~537ms wall time while E2B degrades to 3.1 seconds
-- OpenSandbox achieves **14.9 sandboxes/sec** throughput vs E2B's **2.55 sandboxes/sec** at high concurrency
-- E2B appears to hit rate limiting or queuing at 8 concurrent requests
+- At 8 concurrent sandboxes, OpenSandbox achieves **27.5 sandboxes/sec** vs E2B's **11.8 sandboxes/sec**
+- OpenSandbox maintains consistent ~250-290ms wall time while E2B degrades to 677ms
+- **2.3x higher throughput** at scale
### Key Takeaways
-| Metric | Winner | Notes |
-|--------|--------|-------|
-| Sandbox creation | OpenSandbox | 2x faster startup |
-| Command execution | E2B | 2x lower latency per command |
-| File operations | E2B | Native SDK vs HTTP+shell |
-| Git clone | OpenSandbox | Faster network/clone performance |
-| Concurrency | OpenSandbox | 6x better throughput at scale |
-| Total workflow | E2B | 17% faster end-to-end |
-
-**Choose OpenSandbox when:**
-- Running many sandboxes in parallel (agent workloads)
-- Git operations are the bottleneck
-- Self-hosting is preferred
-
-**Choose E2B when:**
-- Single-sandbox workflows
-- Many small file operations
-- Minimal infrastructure management desired
-
-> **Note:** These benchmarks compare E2B's native Python SDK against OpenSandbox's HTTP API. The command execution and file operation differences are largely due to SDK vs HTTP overhead. A native OpenSandbox SDK is planned, which should significantly reduce per-operation latency and provide a more direct comparison. Results will be updated once the SDK is available.
+| Metric | Winner | Improvement |
+|--------|--------|-------------|
+| Sandbox creation | **OpenSandbox** | 1.9x faster |
+| Sandbox destroy | **OpenSandbox** | 6.6x faster |
+| Command execution | **OpenSandbox** | 1.9x faster |
+| File operations | **OpenSandbox** | 3-7x faster |
+| Git clone | **OpenSandbox** | 1.2x faster |
+| Concurrency | **OpenSandbox** | 2.3x throughput |
+| Total workflow | **OpenSandbox** | 1.7x faster |
+
+**OpenSandbox with gRPC wins across the board.**
+
+### What Changed?
+
+The gRPC implementation provides:
+- **Binary protocol** - No JSON serialization overhead
+- **Native file I/O** - Direct filesystem access, no shell commands
+- **Connection reuse** - Persistent gRPC channel
+- **Edge deployment** - Deploy close to users for low latency
---
diff --git a/benchmarks/benchmark_commands.py b/benchmarks/benchmark_commands.py
index 6a4be5b6..fbbb5c2e 100755
--- a/benchmarks/benchmark_commands.py
+++ b/benchmarks/benchmark_commands.py
@@ -181,7 +181,7 @@ if __name__ == "__main__":
import json
parser = argparse.ArgumentParser(description="Benchmark command execution latency")
- parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--provider", choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b"], default="opensandbox-grpc")
parser.add_argument("--iterations", type=int, default=3)
parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
diff --git a/benchmarks/benchmark_concurrency.py b/benchmarks/benchmark_concurrency.py
index 246a02e8..c7f92a3c 100755
--- a/benchmarks/benchmark_concurrency.py
+++ b/benchmarks/benchmark_concurrency.py
@@ -178,7 +178,7 @@ if __name__ == "__main__":
import json
parser = argparse.ArgumentParser(description="Benchmark concurrent sandbox operations")
- parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--provider", choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b"], default="opensandbox-grpc")
parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
args = parser.parse_args()
diff --git a/benchmarks/benchmark_creation.py b/benchmarks/benchmark_creation.py
index 17524862..c398adc3 100755
--- a/benchmarks/benchmark_creation.py
+++ b/benchmarks/benchmark_creation.py
@@ -123,7 +123,7 @@ if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Benchmark sandbox creation time")
- parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--provider", choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b"], default="opensandbox-grpc")
parser.add_argument("--iterations", type=int, default=3)
parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
diff --git a/benchmarks/benchmark_files.py b/benchmarks/benchmark_files.py
index 6cc3a3cd..c256f500 100755
--- a/benchmarks/benchmark_files.py
+++ b/benchmarks/benchmark_files.py
@@ -225,7 +225,7 @@ if __name__ == "__main__":
import json
parser = argparse.ArgumentParser(description="Benchmark file operations")
- parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--provider", choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b"], default="opensandbox-grpc")
parser.add_argument("--iterations", type=int, default=3)
parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
diff --git a/benchmarks/benchmark_workflow.py b/benchmarks/benchmark_workflow.py
index 96222445..a2b9a20b 100755
--- a/benchmarks/benchmark_workflow.py
+++ b/benchmarks/benchmark_workflow.py
@@ -228,7 +228,7 @@ if __name__ == "__main__":
import json
parser = argparse.ArgumentParser(description="Benchmark realistic workflow")
- parser.add_argument("--provider", choices=["opensandbox", "e2b"], default="opensandbox")
+ parser.add_argument("--provider", choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b"], default="opensandbox-grpc")
parser.add_argument("--iterations", type=int, default=3)
parser.add_argument("--opensandbox-url", default="https://opensandbox-test.fly.dev")
diff --git a/benchmarks/requirements.txt b/benchmarks/requirements.txt
index fe70d4a1..29f9dc18 100644
--- a/benchmarks/requirements.txt
+++ b/benchmarks/requirements.txt
@@ -3,3 +3,6 @@ e2b>=1.0.0
pydantic>=2.0.0
pydantic-settings>=2.0.0
tabulate>=0.9.0
+grpcio>=1.60.0
+grpcio-tools>=1.60.0
+protobuf>=4.25.0
diff --git a/benchmarks/run_benchmarks.py b/benchmarks/run_benchmarks.py
index d6e856dc..8f7e3a28 100755
--- a/benchmarks/run_benchmarks.py
+++ b/benchmarks/run_benchmarks.py
@@ -256,18 +256,20 @@ def main():
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
- python run_benchmarks.py # Run all benchmarks
- python run_benchmarks.py --provider opensandbox # Only test opensandbox
- python run_benchmarks.py --only creation # Only creation benchmark
- python run_benchmarks.py --iterations 5 # 5 iterations per test
+ python run_benchmarks.py # Run all benchmarks (HTTP, gRPC, E2B)
+ python run_benchmarks.py --provider opensandbox # Test opensandbox with gRPC
+ python run_benchmarks.py --provider opensandbox-http # Test opensandbox with HTTP only
+ python run_benchmarks.py --provider opensandbox-grpc # Test opensandbox with gRPC only
+ python run_benchmarks.py --only creation # Only creation benchmark
+ python run_benchmarks.py --iterations 5 # 5 iterations per test
"""
)
parser.add_argument(
"--provider",
- choices=["opensandbox", "e2b", "all"],
+ choices=["opensandbox", "opensandbox-http", "opensandbox-grpc", "e2b", "all"],
default="all",
- help="Which provider to benchmark (default: all)"
+ help="Which provider to benchmark: opensandbox (gRPC), opensandbox-http, opensandbox-grpc, e2b, all (default: all)"
)
parser.add_argument(
"--only",
@@ -297,14 +299,26 @@ Examples:
# Determine which providers to test
providers = []
- if args.provider in ["opensandbox", "all"]:
+ opensandbox_providers = ["opensandbox", "opensandbox-http", "opensandbox-grpc"]
+
+ # Check if we need to test any opensandbox variant
+ if args.provider in opensandbox_providers or args.provider == "all":
if check_opensandbox_available(args.opensandbox_url):
- providers.append("opensandbox")
- print(f"✓ OpenSandbox available at {args.opensandbox_url}")
+ if args.provider == "all":
+ # Test both HTTP and gRPC when running all
+ providers.extend(["opensandbox-http", "opensandbox-grpc"])
+ print(f"✓ OpenSandbox available at {args.opensandbox_url} (testing HTTP and gRPC)")
+ elif args.provider == "opensandbox":
+ # Default "opensandbox" uses gRPC
+ providers.append("opensandbox-grpc")
+ print(f"✓ OpenSandbox available at {args.opensandbox_url} (using gRPC)")
+ else:
+ providers.append(args.provider)
+ print(f"✓ OpenSandbox available at {args.opensandbox_url} (using {args.provider})")
else:
print(f"✗ OpenSandbox not available at {args.opensandbox_url}")
- if args.provider == "opensandbox":
- print(" Start it with: docker compose up --build")
+ if args.provider in opensandbox_providers:
+ print(" Start it with: fly deploy")
sys.exit(1)
if args.provider in ["e2b", "all"]:
diff --git a/benchmarks/sandbox_interface.py b/benchmarks/sandbox_interface.py
index ece8155b..d20bd9a0 100755
--- a/benchmarks/sandbox_interface.py
+++ b/benchmarks/sandbox_interface.py
@@ -1,12 +1,18 @@
"""Simplified sandbox interfaces for benchmarking."""
import os
+import sys
import time
import httpx
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Optional
+# Add SDK path for local development
+SDK_PATH = os.path.join(os.path.dirname(__file__), "..", "sdk", "python")
+if os.path.exists(SDK_PATH):
+ sys.path.insert(0, SDK_PATH)
+
@dataclass
class CommandResult:
@@ -53,7 +59,7 @@ class BaseSandbox(ABC):
class OpenSandboxClient(BaseSandbox):
- """OpenSandbox HTTP client for benchmarking."""
+ """OpenSandbox HTTP client for benchmarking (legacy, uses HTTP only)."""
def __init__(self, base_url: str = "http://localhost:8080"):
self.base_url = base_url
@@ -62,7 +68,7 @@ class OpenSandboxClient(BaseSandbox):
@property
def name(self) -> str:
- return "opensandbox"
+ return "opensandbox-http"
def create(self, timeout: int = 300) -> str:
response = self.client.post(
@@ -128,6 +134,139 @@ class OpenSandboxClient(BaseSandbox):
self.client.close()
+class OpenSandboxGrpcClient(BaseSandbox):
+ """OpenSandbox gRPC client for benchmarking (uses gRPC for operations)."""
+
+ def __init__(
+ self,
+ base_url: str = "http://localhost:8080",
+ grpc_port: int = 50051,
+ ):
+ self.base_url = base_url
+ self.grpc_port = grpc_port
+ self.session_id: Optional[str] = None
+ self.http_client = httpx.Client(timeout=300)
+ self._grpc_channel = None
+ self._stub = None
+
+ # Parse host for gRPC
+ from urllib.parse import urlparse
+ parsed = urlparse(base_url)
+ self._host = parsed.hostname or "localhost"
+ self._is_secure = parsed.scheme == "https"
+
+ def _ensure_grpc(self):
+ """Ensure gRPC connection is established."""
+ if self._grpc_channel is None:
+ import grpc
+ from opensandbox.proto import sandbox_pb2_grpc
+
+ grpc_target = f"{self._host}:{self.grpc_port}"
+ # Use insecure channel - Fly.io forwards raw TCP
+ self._grpc_channel = grpc.insecure_channel(grpc_target)
+ self._stub = sandbox_pb2_grpc.SandboxServiceStub(self._grpc_channel)
+
+ @property
+ def name(self) -> str:
+ return "opensandbox-grpc"
+
+ def create(self, timeout: int = 300) -> str:
+ response = self.http_client.post(
+ f"{self.base_url}/sessions",
+ json={"env": {}}
+ )
+ response.raise_for_status()
+ self.session_id = response.json()["session_id"]
+ self._ensure_grpc()
+ return self.session_id
+
+ def run_command(self, command: str) -> CommandResult:
+ if not self.session_id:
+ raise RuntimeError("Session not created")
+
+ from opensandbox.proto import sandbox_pb2
+
+ request = sandbox_pb2.RunCommandRequest(
+ session_id=self.session_id,
+ command=["/bin/sh", "-c", command],
+ time_ms=300000,
+ mem_kb=2097152,
+ fsize_kb=1048576,
+ nofile=256,
+ )
+
+ start = time.perf_counter()
+ response = self._stub.RunCommand(request)
+ duration_ms = (time.perf_counter() - start) * 1000
+
+ exit_code = response.exit_code
+ if response.signal:
+ exit_code = 128 + response.signal
+
+ return CommandResult(
+ stdout=response.stdout,
+ stderr=response.stderr,
+ exit_code=exit_code,
+ duration_ms=duration_ms
+ )
+
+ def write_file(self, path: str, content: str) -> float:
+ if not self.session_id:
+ raise RuntimeError("Session not created")
+
+ from opensandbox.proto import sandbox_pb2
+
+ request = sandbox_pb2.WriteFileRequest(
+ session_id=self.session_id,
+ path=path,
+ content=content.encode("utf-8"),
+ )
+
+ start = time.perf_counter()
+ response = self._stub.WriteFile(request)
+ duration_ms = (time.perf_counter() - start) * 1000
+
+ if not response.success:
+ raise RuntimeError(f"Write file failed: {response.error}")
+
+ return duration_ms
+
+ def read_file(self, path: str) -> tuple[str, float]:
+ if not self.session_id:
+ raise RuntimeError("Session not created")
+
+ from opensandbox.proto import sandbox_pb2
+
+ request = sandbox_pb2.ReadFileRequest(
+ session_id=self.session_id,
+ path=path,
+ )
+
+ start = time.perf_counter()
+ response = self._stub.ReadFile(request)
+ duration_ms = (time.perf_counter() - start) * 1000
+
+ if response.error:
+ raise RuntimeError(f"Read file failed: {response.error}")
+
+ return response.content.decode("utf-8"), duration_ms
+
+ def destroy(self) -> None:
+ if self.session_id:
+ try:
+ self.http_client.delete(f"{self.base_url}/sessions/{self.session_id}")
+ except Exception:
+ pass
+ self.session_id = None
+
+ if self._grpc_channel:
+ self._grpc_channel.close()
+ self._grpc_channel = None
+ self._stub = None
+
+ self.http_client.close()
+
+
class E2BSandboxClient(BaseSandbox):
"""E2B sandbox client for benchmarking."""
@@ -191,8 +330,19 @@ class E2BSandboxClient(BaseSandbox):
def get_sandbox(provider: str, **kwargs) -> BaseSandbox:
"""Factory function to get a sandbox instance."""
if provider == "opensandbox":
+ # Default to gRPC for better performance
+ base_url = kwargs.get("base_url", os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"))
+ grpc_port = kwargs.get("grpc_port", int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051")))
+ return OpenSandboxGrpcClient(base_url=base_url, grpc_port=grpc_port)
+ elif provider == "opensandbox-http":
+ # Legacy HTTP-only mode
base_url = kwargs.get("base_url", os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"))
return OpenSandboxClient(base_url=base_url)
+ elif provider == "opensandbox-grpc":
+ # Explicit gRPC mode
+ base_url = kwargs.get("base_url", os.environ.get("OPENSANDBOX_URL", "https://opensandbox-test.fly.dev"))
+ grpc_port = kwargs.get("grpc_port", int(os.environ.get("OPENSANDBOX_GRPC_PORT", "50051")))
+ return OpenSandboxGrpcClient(base_url=base_url, grpc_port=grpc_port)
elif provider == "e2b":
return E2BSandboxClient()
else:
diff --git a/build.rs b/build.rs
new file mode 100644
index 00000000..6fd1d729
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,4 @@
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ tonic_build::compile_protos("proto/sandbox.proto")?;
+ Ok(())
+}
diff --git a/docker-compose.yml b/docker-compose.yml
index 5938ccf1..79b9e952 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -4,3 +4,4 @@ services:
privileged: true
ports:
- "8080:8080"
+ - "50051:50051"
diff --git a/fly.toml b/fly.toml
new file mode 100644
index 00000000..0f20532d
--- /dev/null
+++ b/fly.toml
@@ -0,0 +1,43 @@
+# fly.toml app configuration file generated for opensandbox-test on 2026-01-30T16:08:35-08:00
+#
+# See https://fly.io/docs/reference/configuration/ for information about how to use this file.
+#
+
+app = 'opensandbox-test'
+primary_region = 'ord'
+
+[build]
+ dockerfile = 'Dockerfile'
+
+[http_service]
+ internal_port = 8080
+ force_https = true
+ auto_stop_machines = 'off'
+ auto_start_machines = true
+ min_machines_running = 1
+
+ [http_service.concurrency]
+ type = 'connections'
+ hard_limit = 25
+ soft_limit = 20
+
+ [[http_service.checks]]
+ interval = '30s'
+ timeout = '5s'
+ grace_period = '10s'
+ method = 'GET'
+ path = '/health'
+
+# Raw TCP for gRPC (no TLS - for benchmarking only)
+[[services]]
+ internal_port = 50051
+ protocol = "tcp"
+
+ [[services.ports]]
+ port = 50051
+
+[[vm]]
+ size = 'shared-cpu-2x'
+ memory = '2gb'
+ cpus = 2
+ memory_mb = 2048
diff --git a/proto/sandbox.proto b/proto/sandbox.proto
new file mode 100644
index 00000000..e6fbb7c1
--- /dev/null
+++ b/proto/sandbox.proto
@@ -0,0 +1,72 @@
+syntax = "proto3";
+package sandbox;
+
+service SandboxService {
+ // Run command in session
+ rpc RunCommand(RunCommandRequest) returns (RunCommandResponse);
+
+ // File operations
+ rpc WriteFile(WriteFileRequest) returns (WriteFileResponse);
+ rpc ReadFile(ReadFileRequest) returns (ReadFileResponse);
+
+ // Environment/CWD
+ rpc SetEnv(SetEnvRequest) returns (SetEnvResponse);
+ rpc SetCwd(SetCwdRequest) returns (SetCwdResponse);
+}
+
+message RunCommandRequest {
+ string session_id = 1;
+ repeated string command = 2;
+ uint64 time_ms = 3;
+ uint64 mem_kb = 4;
+ uint64 fsize_kb = 5;
+ uint64 nofile = 6;
+ map<string, string> env = 7;
+ string cwd = 8;
+}
+
+message RunCommandResponse {
+ string stdout = 1;
+ string stderr = 2;
+ int32 exit_code = 3;
+ int32 signal = 4;
+}
+
+message WriteFileRequest {
+ string session_id = 1;
+ string path = 2;
+ bytes content = 3;
+}
+
+message WriteFileResponse {
+ bool success = 1;
+ string error = 2;
+}
+
+message ReadFileRequest {
+ string session_id = 1;
+ string path = 2;
+}
+
+message ReadFileResponse {
+ bytes content = 1;
+ string error = 2;
+}
+
+message SetEnvRequest {
+ string session_id = 1;
+ map<string, string> env = 2;
+}
+
+message SetEnvResponse {
+ bool success = 1;
+}
+
+message SetCwdRequest {
+ string session_id = 1;
+ string cwd = 2;
+}
+
+message SetCwdResponse {
+ bool success = 1;
+}
diff --git a/sdk/python/README.md b/sdk/python/README.md
new file mode 100644
index 00000000..02087bde
--- /dev/null
+++ b/sdk/python/README.md
@@ -0,0 +1,162 @@
+# OpenSandbox Python SDK
+
+A high-performance Python client for [OpenSandbox](https://github.com/yourusername/opensandbox), using gRPC for fast command execution and file operations.
+
+## Installation
+
+```bash
+pip install opensandbox
+```
+
+Or install from source:
+
+```bash
+cd sdk/python
+pip install -e .
+```
+
+## Quick Start
+
+```python
+import asyncio
+from opensandbox import OpenSandbox
+
+async def main():
+ async with OpenSandbox("https://opensandbox.fly.dev") as client:
+ # Create a sandbox
+ sandbox = await client.create()
+
+ # Run commands
+ result = await sandbox.run("echo hello")
+ print(result.stdout) # "hello\n"
+
+ # Write and read files
+ await sandbox.write_file("/tmp/test.py", "print('hi')")
+ content = await sandbox.read_file_text("/tmp/test.py")
+
+ # Set environment variables
+ await sandbox.set_env({"MY_VAR": "value"})
+
+ # Set working directory
+ await sandbox.set_cwd("/tmp")
+
+ # Clean up
+ await sandbox.destroy()
+
+asyncio.run(main())
+```
+
+## API Reference
+
+### OpenSandbox
+
+The main client class for connecting to an OpenSandbox server.
+
+```python
+client = OpenSandbox(
+ base_url="https://opensandbox.fly.dev", # Server URL
+ grpc_port=50051, # gRPC port (default: 50051)
+ timeout=30.0, # HTTP timeout in seconds
+)
+```
+
+### Sandbox
+
+A sandbox session for executing commands and managing files.
+
+#### run(command, *, timeout_ms=300000, mem_kb=2097152, env=None, cwd=None)
+
+Execute a shell command in the sandbox.
+
+```python
+result = await sandbox.run("ls -la")
+print(result.stdout)
+print(result.stderr)
+print(result.exit_code)
+print(result.success) # True if exit_code == 0
+```
+
+#### write_file(path, content)
+
+Write content to a file in the sandbox.
+
+```python
+await sandbox.write_file("/tmp/script.py", "print('hello')")
+await sandbox.write_file("/tmp/data.bin", b"\x00\x01\x02") # bytes
+```
+
+#### read_file(path) / read_file_text(path)
+
+Read a file from the sandbox.
+
+```python
+content = await sandbox.read_file("/tmp/data.bin") # bytes
+text = await sandbox.read_file_text("/tmp/script.py") # str
+```
+
+#### set_env(env)
+
+Set environment variables for subsequent commands.
+
+```python
+await sandbox.set_env({"PATH": "/usr/bin:/bin", "MY_VAR": "value"})
+```
+
+#### set_cwd(cwd)
+
+Set the working directory for subsequent commands.
+
+```python
+await sandbox.set_cwd("/home/user")
+```
+
+#### destroy()
+
+Destroy the sandbox and clean up resources.
+
+```python
+await sandbox.destroy()
+```
+
+## Context Manager Support
+
+Both `OpenSandbox` and `Sandbox` support async context managers:
+
+```python
+async with OpenSandbox("https://opensandbox.fly.dev") as client:
+ async with await client.create() as sandbox:
+ result = await sandbox.run("echo hello")
+ # sandbox.destroy() called automatically
+ # client.close() called automatically
+```
+
+## Error Handling
+
+```python
+from opensandbox import (
+ OpenSandboxError,
+ SandboxNotFoundError,
+ SandboxConnectionError,
+ CommandExecutionError,
+ FileOperationError,
+)
+
+try:
+ result = await sandbox.run("invalid-command")
+except CommandExecutionError as e:
+ print(f"Command failed: {e}")
+ print(f"Exit code: {e.exit_code}")
+ print(f"Stderr: {e.stderr}")
+```
+
+## Architecture
+
+The SDK uses a hybrid approach:
+- **HTTP** for sandbox lifecycle (create/destroy) - reliable and works through all proxies
+- **gRPC** for fast operations (commands, file I/O) - low latency, binary protocol
+
+This gives you the best of both worlds: reliable session management and fast command execution.
+
+## License
+
+MIT
diff --git a/sdk/python/examples/basic_usage.py b/sdk/python/examples/basic_usage.py
new file mode 100644
index 00000000..7a7ad8b4
--- /dev/null
+++ b/sdk/python/examples/basic_usage.py
@@ -0,0 +1,47 @@
+#!/usr/bin/env python3
+"""Basic usage example for the OpenSandbox SDK."""
+
+import asyncio
+from opensandbox import OpenSandbox
+
+
+async def main():
+ # Connect to OpenSandbox server
+ async with OpenSandbox("https://opensandbox-test.fly.dev") as client:
+ # Create a new sandbox
+ sandbox = await client.create()
+ print(f"Created sandbox: {sandbox.session_id}")
+
+ try:
+ # Run a simple command
+ result = await sandbox.run("echo 'Hello, OpenSandbox!'")
+ print(f"Command output: {result.stdout}")
+ print(f"Exit code: {result.exit_code}")
+
+ # Write a file
+ await sandbox.write_file("/tmp/test.py", "print('Hello from Python!')")
+ print("Wrote file: /tmp/test.py")
+
+ # Read the file back
+ content = await sandbox.read_file_text("/tmp/test.py")
+ print(f"File content: {content}")
+
+ # Execute the Python script
+ result = await sandbox.run("python3 /tmp/test.py")
+ print(f"Script output: {result.stdout}")
+
+ # Set working directory
+ await sandbox.set_cwd("/tmp")
+
+ # Run command in the new directory
+ result = await sandbox.run("pwd")
+ print(f"Current directory: {result.stdout.strip()}")
+
+ finally:
+ # Clean up
+ await sandbox.destroy()
+ print("Sandbox destroyed")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/sdk/python/generate_proto.sh b/sdk/python/generate_proto.sh
new file mode 100755
index 00000000..c0063a06
--- /dev/null
+++ b/sdk/python/generate_proto.sh
@@ -0,0 +1,18 @@
+#!/bin/bash
+# Generate Python protobuf files from proto/sandbox.proto
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+PROTO_DIR="$SCRIPT_DIR/../../proto"
+OUT_DIR="$SCRIPT_DIR/opensandbox/proto"
+
+python -m grpc_tools.protoc \
+ -I"$PROTO_DIR" \
+ --python_out="$OUT_DIR" \
+ --grpc_python_out="$OUT_DIR" \
+ "$PROTO_DIR/sandbox.proto"
+
+# Fix the import path in the generated grpc file
+sed -i.bak 's/import sandbox_pb2/from . import sandbox_pb2/' "$OUT_DIR/sandbox_pb2_grpc.py"
+rm -f "$OUT_DIR/sandbox_pb2_grpc.py.bak"
+
+echo "Generated Python protobuf files in $OUT_DIR"
diff --git a/sdk/python/opensandbox/__init__.py b/sdk/python/opensandbox/__init__.py
new file mode 100644
index 00000000..59248bf1
--- /dev/null
+++ b/sdk/python/opensandbox/__init__.py
@@ -0,0 +1,42 @@
+"""OpenSandbox Python SDK.
+
+A high-performance Python client for OpenSandbox, using gRPC for
+fast command execution and file operations.
+
+Usage:
+ from opensandbox import OpenSandbox
+
+ async with OpenSandbox("https://opensandbox.fly.dev") as client:
+ sandbox = await client.create()
+
+ result = await sandbox.run("echo hello")
+ print(result.stdout)
+
+ await sandbox.write_file("/tmp/test.py", "print('hello')")
+ content = await sandbox.read_file("/tmp/test.py")
+
+ await sandbox.destroy()
+"""
+
+from .client import OpenSandbox
+from .sandbox import Sandbox, CommandResult
+from .exceptions import (
+ OpenSandboxError,
+ SandboxNotFoundError,
+ SandboxConnectionError,
+ CommandExecutionError,
+ FileOperationError,
+)
+
+__version__ = "0.1.0"
+
+__all__ = [
+ "OpenSandbox",
+ "Sandbox",
+ "CommandResult",
+ "OpenSandboxError",
+ "SandboxNotFoundError",
+ "SandboxConnectionError",
+ "CommandExecutionError",
+ "FileOperationError",
+]
diff --git a/sdk/python/opensandbox/client.py b/sdk/python/opensandbox/client.py
new file mode 100644
index 00000000..6626d834
--- /dev/null
+++ b/sdk/python/opensandbox/client.py
@@ -0,0 +1,124 @@
+"""OpenSandbox client for creating and managing sandbox sessions."""
+
+from typing import Optional, Dict
+from urllib.parse import urlparse
+
+import grpc
+import httpx
+
+from .sandbox import Sandbox
+from .exceptions import SandboxConnectionError
+
+
+class OpenSandbox:
+ """Client for connecting to an OpenSandbox server.
+
+ This client uses HTTP for sandbox lifecycle (create/destroy) and
+ gRPC for fast command execution and file operations.
+
+ Usage:
+ async with OpenSandbox("https://opensandbox.example.com") as client:
+ sandbox = await client.create()
+ result = await sandbox.run("echo hello")
+ print(result.stdout)
+ await sandbox.destroy()
+ """
+
+ def __init__(
+ self,
+ base_url: str,
+ *,
+ grpc_port: Optional[int] = None,
+ timeout: float = 30.0,
+ ):
+ """Initialize the OpenSandbox client.
+
+ Args:
+ base_url: Base URL of the OpenSandbox server (e.g., "https://opensandbox.fly.dev").
+ grpc_port: gRPC port (default: 50051). If None, uses 50051.
+ timeout: Default timeout for HTTP requests in seconds.
+ """
+ self._base_url = base_url.rstrip("/")
+ self._grpc_port = grpc_port or 50051
+ self._timeout = timeout
+ self._http_client: Optional[httpx.AsyncClient] = None
+ self._grpc_channel: Optional[grpc.aio.Channel] = None
+
+ # Parse the URL to get host for gRPC
+ parsed = urlparse(self._base_url)
+ self._host = parsed.hostname or "localhost"
+ self._is_secure = parsed.scheme == "https"
+
+ async def _ensure_connected(self) -> None:
+ """Ensure HTTP and gRPC connections are established."""
+ if self._http_client is None:
+ self._http_client = httpx.AsyncClient(timeout=self._timeout)
+
+ if self._grpc_channel is None:
+ grpc_target = f"{self._host}:{self._grpc_port}"
+ if self._is_secure:
+ # Use secure channel for HTTPS
+ credentials = grpc.ssl_channel_credentials()
+ self._grpc_channel = grpc.aio.secure_channel(grpc_target, credentials)
+ else:
+ # Use insecure channel for HTTP (local dev)
+ self._grpc_channel = grpc.aio.insecure_channel(grpc_target)
+
+ async def create(
+ self,
+ *,
+ env: Optional[Dict[str, str]] = None,
+ timeout: int = 300,
+ ) -> Sandbox:
+ """Create a new sandbox session.
+
+ Args:
+ env: Initial environment variables for the sandbox.
+ timeout: Sandbox timeout in seconds.
+
+ Returns:
+ A Sandbox instance ready for use.
+
+ Raises:
+ SandboxConnectionError: If connection to the server fails.
+ """
+ await self._ensure_connected()
+
+ try:
+ response = await self._http_client.post(
+ f"{self._base_url}/sessions",
+ json={"env": env or {}},
+ timeout=timeout,
+ )
+ response.raise_for_status()
+ data = response.json()
+ session_id = data["session_id"]
+ except httpx.HTTPError as e:
+ raise SandboxConnectionError(f"Failed to create sandbox: {e}") from e
+
+ return Sandbox(
+ session_id=session_id,
+ grpc_channel=self._grpc_channel,
+ http_base_url=self._base_url,
+ http_client=self._http_client,
+ )
+
+ async def close(self) -> None:
+ """Close all connections to the server."""
+ if self._grpc_channel is not None:
+ await self._grpc_channel.close()
+ self._grpc_channel = None
+
+ if self._http_client is not None:
+ await self._http_client.aclose()
+ self._http_client = None
+
+ async def __aenter__(self):
+ """Async context manager entry."""
+ await self._ensure_connected()
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ """Async context manager exit."""
+ await self.close()
+ return False
diff --git a/sdk/python/opensandbox/exceptions.py b/sdk/python/opensandbox/exceptions.py
new file mode 100644
index 00000000..42b91964
--- /dev/null
+++ b/sdk/python/opensandbox/exceptions.py
@@ -0,0 +1,31 @@
+"""Custom exceptions for the OpenSandbox SDK."""
+
+
+class OpenSandboxError(Exception):
+ """Base exception for OpenSandbox errors."""
+ pass
+
+
+class SandboxNotFoundError(OpenSandboxError):
+ """Raised when a sandbox session is not found."""
+ pass
+
+
+class SandboxConnectionError(OpenSandboxError):
+ """Raised when connection to the sandbox server fails."""
+ pass
+
+
+class CommandExecutionError(OpenSandboxError):
+ """Raised when a command execution fails."""
+
+ def __init__(self, message: str, exit_code: int = 1, stdout: str = "", stderr: str = ""):
+ super().__init__(message)
+ self.exit_code = exit_code
+ self.stdout = stdout
+ self.stderr = stderr
+
+
+class FileOperationError(OpenSandboxError):
+ """Raised when a file operation fails."""
+ pass
diff --git a/sdk/python/opensandbox/proto/__init__.py b/sdk/python/opensandbox/proto/__init__.py
new file mode 100644
index 00000000..d2a6063b
--- /dev/null
+++ b/sdk/python/opensandbox/proto/__init__.py
@@ -0,0 +1,7 @@
+"""Generated protobuf modules for gRPC communication."""
+
+# Import from generated files
+from . import sandbox_pb2
+from . import sandbox_pb2_grpc
+
+__all__ = ["sandbox_pb2", "sandbox_pb2_grpc"]
diff --git a/sdk/python/opensandbox/proto/sandbox_pb2.py b/sdk/python/opensandbox/proto/sandbox_pb2.py
new file mode 100644
index 00000000..26a43fd4
--- /dev/null
+++ b/sdk/python/opensandbox/proto/sandbox_pb2.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# NO CHECKED-IN PROTOBUF GENCODE
+# source: sandbox.proto
+# Protobuf Python Version: 6.31.1
+"""Generated protocol buffer code."""
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import descriptor_pool as _descriptor_pool
+from google.protobuf import runtime_version as _runtime_version
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf.internal import builder as _builder
+_runtime_version.ValidateProtobufRuntimeVersion(
+ _runtime_version.Domain.PUBLIC,
+ 6,
+ 31,
+ 1,
+ '',
+ 'sandbox.proto'
+)
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\rsandbox.proto\x12\x07sandbox\"\xe6\x01\n\x11RunCommandRequest\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12\x0f\n\x07\x63ommand\x18\x02 \x03(\t\x12\x0f\n\x07time_ms\x18\x03 \x01(\x04\x12\x0e\n\x06mem_kb\x18\x04 \x01(\x04\x12\x10\n\x08\x66size_kb\x18\x05 \x01(\x04\x12\x0e\n\x06nofile\x18\x06 \x01(\x04\x12\x30\n\x03\x65nv\x18\x07 \x03(\x0b\x32#.sandbox.RunCommandRequest.EnvEntry\x12\x0b\n\x03\x63wd\x18\x08 \x01(\t\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"W\n\x12RunCommandResponse\x12\x0e\n\x06stdout\x18\x01 \x01(\t\x12\x0e\n\x06stderr\x18\x02 \x01(\t\x12\x11\n\texit_code\x18\x03 \x01(\x05\x12\x0e\n\x06signal\x18\x04 \x01(\x05\"E\n\x10WriteFileRequest\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\t\x12\x0f\n\x07\x63ontent\x18\x03 \x01(\x0c\"3\n\x11WriteFileResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"3\n\x0fReadFileRequest\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12\x0c\n\x04path\x18\x02 \x01(\t\"2\n\x10ReadFileResponse\x12\x0f\n\x07\x63ontent\x18\x01 \x01(\x0c\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"}\n\rSetEnvRequest\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sandbox.SetEnvRequest.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"!\n\x0eSetEnvResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\"0\n\rSetCwdRequest\x12\x12\n\nsession_id\x18\x01 \x01(\t\x12\x0b\n\x03\x63wd\x18\x02 \x01(\t\"!\n\x0eSetCwdResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x32\xd2\x02\n\x0eSandboxService\x12\x45\n\nRunCommand\x12\x1a.sandbox.RunCommandRequest\x1a\x1b.sandbox.RunCommandResponse\x12\x42\n\tWriteFile\x12\x19.sandbox.WriteFileRequest\x1a\x1a.sandbox.WriteFileResponse\x12?\n\x08ReadFile\x12\x18.sandbox.ReadFileRequest\x1a\x19.sandbox.ReadFileResponse\x12\x39\n\x06SetEnv\x12\x16.sandbox.SetEnvRequest\x1a\x17.sandbox.SetEnvResponse\x12\x39\n\x06SetCwd\x12\x16.sandbox.SetCwdRequest\x1a\x17.sandbox.SetCwdResponseb\x06proto3')
+
+_globals = globals()
+_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sandbox_pb2', _globals)
+if not _descriptor._USE_C_DESCRIPTORS:
+ DESCRIPTOR._loaded_options = None
+ _globals['_RUNCOMMANDREQUEST_ENVENTRY']._loaded_options = None
+ _globals['_RUNCOMMANDREQUEST_ENVENTRY']._serialized_options = b'8\001'
+ _globals['_SETENVREQUEST_ENVENTRY']._loaded_options = None
+ _globals['_SETENVREQUEST_ENVENTRY']._serialized_options = b'8\001'
+ _globals['_RUNCOMMANDREQUEST']._serialized_start=27
+ _globals['_RUNCOMMANDREQUEST']._serialized_end=257
+ _globals['_RUNCOMMANDREQUEST_ENVENTRY']._serialized_start=215
+ _globals['_RUNCOMMANDREQUEST_ENVENTRY']._serialized_end=257
+ _globals['_RUNCOMMANDRESPONSE']._serialized_start=259
+ _globals['_RUNCOMMANDRESPONSE']._serialized_end=346
+ _globals['_WRITEFILEREQUEST']._serialized_start=348
+ _globals['_WRITEFILEREQUEST']._serialized_end=417
+ _globals['_WRITEFILERESPONSE']._serialized_start=419
+ _globals['_WRITEFILERESPONSE']._serialized_end=470
+ _globals['_READFILEREQUEST']._serialized_start=472
+ _globals['_READFILEREQUEST']._serialized_end=523
+ _globals['_READFILERESPONSE']._serialized_start=525
+ _globals['_READFILERESPONSE']._serialized_end=575
+ _globals['_SETENVREQUEST']._serialized_start=577
+ _globals['_SETENVREQUEST']._serialized_end=702
+ _globals['_SETENVREQUEST_ENVENTRY']._serialized_start=215
+ _globals['_SETENVREQUEST_ENVENTRY']._serialized_end=257
+ _globals['_SETENVRESPONSE']._serialized_start=704
+ _globals['_SETENVRESPONSE']._serialized_end=737
+ _globals['_SETCWDREQUEST']._serialized_start=739
+ _globals['_SETCWDREQUEST']._serialized_end=787
+ _globals['_SETCWDRESPONSE']._serialized_start=789
+ _globals['_SETCWDRESPONSE']._serialized_end=822
+ _globals['_SANDBOXSERVICE']._serialized_start=825
+ _globals['_SANDBOXSERVICE']._serialized_end=1163
+# @@protoc_insertion_point(module_scope)
diff --git a/sdk/python/opensandbox/proto/sandbox_pb2_grpc.py b/sdk/python/opensandbox/proto/sandbox_pb2_grpc.py
new file mode 100644
index 00000000..0debf458
--- /dev/null
+++ b/sdk/python/opensandbox/proto/sandbox_pb2_grpc.py
@@ -0,0 +1,272 @@
+# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
+"""Client and server classes corresponding to protobuf-defined services."""
+import grpc
+import warnings
+
+from . import sandbox_pb2 as sandbox__pb2
+
+GRPC_GENERATED_VERSION = '1.76.0'
+GRPC_VERSION = grpc.__version__
+_version_not_supported = False
+
+try:
+ from grpc._utilities import first_version_is_lower
+ _version_not_supported = first_version_is_lower(GRPC_VERSION, GRPC_GENERATED_VERSION)
+except ImportError:
+ _version_not_supported = True
+
+if _version_not_supported:
+ raise RuntimeError(
+ f'The grpc package installed is at version {GRPC_VERSION},'
+ + ' but the generated code in sandbox_pb2_grpc.py depends on'
+ + f' grpcio>={GRPC_GENERATED_VERSION}.'
+ + f' Please upgrade your grpc module to grpcio>={GRPC_GENERATED_VERSION}'
+ + f' or downgrade your generated code using grpcio-tools<={GRPC_VERSION}.'
+ )
+
+
+class SandboxServiceStub(object):
+ """Missing associated documentation comment in .proto file."""
+
+ def __init__(self, channel):
+ """Constructor.
+
+ Args:
+ channel: A grpc.Channel.
+ """
+ self.RunCommand = channel.unary_unary(
+ '/sandbox.SandboxService/RunCommand',
+ request_serializer=sandbox__pb2.RunCommandRequest.SerializeToString,
+ response_deserializer=sandbox__pb2.RunCommandResponse.FromString,
+ _registered_method=True)
+ self.WriteFile = channel.unary_unary(
+ '/sandbox.SandboxService/WriteFile',
+ request_serializer=sandbox__pb2.WriteFileRequest.SerializeToString,
+ response_deserializer=sandbox__pb2.WriteFileResponse.FromString,
+ _registered_method=True)
+ self.ReadFile = channel.unary_unary(
+ '/sandbox.SandboxService/ReadFile',
+ request_serializer=sandbox__pb2.ReadFileRequest.SerializeToString,
+ response_deserializer=sandbox__pb2.ReadFileResponse.FromString,
+ _registered_method=True)
+ self.SetEnv = channel.unary_unary(
+ '/sandbox.SandboxService/SetEnv',
+ request_serializer=sandbox__pb2.SetEnvRequest.SerializeToString,
+ response_deserializer=sandbox__pb2.SetEnvResponse.FromString,
+ _registered_method=True)
+ self.SetCwd = channel.unary_unary(
+ '/sandbox.SandboxService/SetCwd',
+ request_serializer=sandbox__pb2.SetCwdRequest.SerializeToString,
+ response_deserializer=sandbox__pb2.SetCwdResponse.FromString,
+ _registered_method=True)
+
+
+class SandboxServiceServicer(object):
+ """Missing associated documentation comment in .proto file."""
+
+ def RunCommand(self, request, context):
+ """Run command in session
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+ def WriteFile(self, request, context):
+ """File operations
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+ def ReadFile(self, request, context):
+ """Missing associated documentation comment in .proto file."""
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+ def SetEnv(self, request, context):
+ """Environment/CWD
+ """
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+ def SetCwd(self, request, context):
+ """Missing associated documentation comment in .proto file."""
+ context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+ context.set_details('Method not implemented!')
+ raise NotImplementedError('Method not implemented!')
+
+
+def add_SandboxServiceServicer_to_server(servicer, server):
+ rpc_method_handlers = {
+ 'RunCommand': grpc.unary_unary_rpc_method_handler(
+ servicer.RunCommand,
+ request_deserializer=sandbox__pb2.RunCommandRequest.FromString,
+ response_serializer=sandbox__pb2.RunCommandResponse.SerializeToString,
+ ),
+ 'WriteFile': grpc.unary_unary_rpc_method_handler(
+ servicer.WriteFile,
+ request_deserializer=sandbox__pb2.WriteFileRequest.FromString,
+ response_serializer=sandbox__pb2.WriteFileResponse.SerializeToString,
+ ),
+ 'ReadFile': grpc.unary_unary_rpc_method_handler(
+ servicer.ReadFile,
+ request_deserializer=sandbox__pb2.ReadFileRequest.FromString,
+ response_serializer=sandbox__pb2.ReadFileResponse.SerializeToString,
+ ),
+ 'SetEnv': grpc.unary_unary_rpc_method_handler(
+ servicer.SetEnv,
+ request_deserializer=sandbox__pb2.SetEnvRequest.FromString,
+ response_serializer=sandbox__pb2.SetEnvResponse.SerializeToString,
+ ),
+ 'SetCwd': grpc.unary_unary_rpc_method_handler(
+ servicer.SetCwd,
+ request_deserializer=sandbox__pb2.SetCwdRequest.FromString,
+ response_serializer=sandbox__pb2.SetCwdResponse.SerializeToString,
+ ),
+ }
+ generic_handler = grpc.method_handlers_generic_handler(
+ 'sandbox.SandboxService', rpc_method_handlers)
+ server.add_generic_rpc_handlers((generic_handler,))
+ server.add_registered_method_handlers('sandbox.SandboxService', rpc_method_handlers)
+
+
+ # This class is part of an EXPERIMENTAL API.
+class SandboxService(object):
+ """Missing associated documentation comment in .proto file."""
+
+ @staticmethod
+ def RunCommand(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ '/sandbox.SandboxService/RunCommand',
+ sandbox__pb2.RunCommandRequest.SerializeToString,
+ sandbox__pb2.RunCommandResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def WriteFile(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ '/sandbox.SandboxService/WriteFile',
+ sandbox__pb2.WriteFileRequest.SerializeToString,
+ sandbox__pb2.WriteFileResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def ReadFile(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ '/sandbox.SandboxService/ReadFile',
+ sandbox__pb2.ReadFileRequest.SerializeToString,
+ sandbox__pb2.ReadFileResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SetEnv(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ '/sandbox.SandboxService/SetEnv',
+ sandbox__pb2.SetEnvRequest.SerializeToString,
+ sandbox__pb2.SetEnvResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
+
+ @staticmethod
+ def SetCwd(request,
+ target,
+ options=(),
+ channel_credentials=None,
+ call_credentials=None,
+ insecure=False,
+ compression=None,
+ wait_for_ready=None,
+ timeout=None,
+ metadata=None):
+ return grpc.experimental.unary_unary(
+ request,
+ target,
+ '/sandbox.SandboxService/SetCwd',
+ sandbox__pb2.SetCwdRequest.SerializeToString,
+ sandbox__pb2.SetCwdResponse.FromString,
+ options,
+ channel_credentials,
+ insecure,
+ call_credentials,
+ compression,
+ wait_for_ready,
+ timeout,
+ metadata,
+ _registered_method=True)
diff --git a/sdk/python/opensandbox/sandbox.py b/sdk/python/opensandbox/sandbox.py
new file mode 100644
index 00000000..86366601
--- /dev/null
+++ b/sdk/python/opensandbox/sandbox.py
@@ -0,0 +1,258 @@
+"""Sandbox session class for interacting with a running sandbox."""
+
+from dataclasses import dataclass
+from typing import Optional, Dict
+import grpc
+
+from .proto import sandbox_pb2, sandbox_pb2_grpc
+from .exceptions import (
+ CommandExecutionError,
+ FileOperationError,
+ SandboxNotFoundError,
+)
+
+
+@dataclass
+class CommandResult:
+ """Result of a command execution."""
+ stdout: str
+ stderr: str
+ exit_code: int
+ signal: int = 0
+
+ @property
+ def success(self) -> bool:
+ """Returns True if the command exited with code 0."""
+ return self.exit_code == 0
+
+
+class Sandbox:
+ """A sandbox session that can execute commands and manage files.
+
+ This class uses gRPC for fast command execution and file operations.
+ """
+
+ def __init__(
+ self,
+ session_id: str,
+ grpc_channel: grpc.Channel,
+ http_base_url: str,
+ http_client,
+ ):
+ """Initialize a sandbox session.
+
+ Args:
+ session_id: The unique session ID from the server.
+ grpc_channel: The gRPC channel for fast operations.
+ http_base_url: Base URL for HTTP API (used for destroy).
+ http_client: HTTP client instance.
+ """
+ self.session_id = session_id
+ self._grpc_channel = grpc_channel
+ self._stub = sandbox_pb2_grpc.SandboxServiceStub(grpc_channel)
+ self._http_base_url = http_base_url
+ self._http_client = http_client
+ self._destroyed = False
+
+ async def run(
+ self,
+ command: str,
+ *,
+ timeout_ms: int = 300000,
+ mem_kb: int = 2097152,
+ env: Optional[Dict[str, str]] = None,
+ cwd: Optional[str] = None,
+ ) -> CommandResult:
+ """Execute a shell command in the sandbox.
+
+ Args:
+ command: The shell command to execute.
+ timeout_ms: CPU time limit in milliseconds.
+ mem_kb: Memory limit in KB.
+ env: Additional environment variables.
+ cwd: Working directory for the command.
+
+ Returns:
+ CommandResult with stdout, stderr, exit_code, and signal.
+
+ Raises:
+ SandboxNotFoundError: If the session no longer exists.
+ CommandExecutionError: If there was an error executing the command.
+ """
+ if self._destroyed:
+ raise SandboxNotFoundError("Sandbox has been destroyed")
+
+ request = sandbox_pb2.RunCommandRequest(
+ session_id=self.session_id,
+ command=["/bin/sh", "-c", command],
+ time_ms=timeout_ms,
+ mem_kb=mem_kb,
+ fsize_kb=1048576,
+ nofile=256,
+ env=env or {},
+ cwd=cwd or "",
+ )
+
+ try:
+ response = await self._stub.RunCommand(request)
+ return CommandResult(
+ stdout=response.stdout,
+ stderr=response.stderr,
+ exit_code=response.exit_code,
+ signal=response.signal,
+ )
+ except grpc.RpcError as e:
+ if e.code() == grpc.StatusCode.NOT_FOUND:
+ raise SandboxNotFoundError("Session not found") from e
+ raise CommandExecutionError(f"gRPC error: {e.details()}") from e
+
+ async def write_file(self, path: str, content: str | bytes) -> None:
+ """Write content to a file in the sandbox.
+
+ Args:
+ path: Absolute path in the sandbox filesystem.
+ content: File content (string or bytes).
+
+ Raises:
+ SandboxNotFoundError: If the session no longer exists.
+ FileOperationError: If the file cannot be written.
+ """
+ if self._destroyed:
+ raise SandboxNotFoundError("Sandbox has been destroyed")
+
+ if isinstance(content, str):
+ content = content.encode("utf-8")
+
+ request = sandbox_pb2.WriteFileRequest(
+ session_id=self.session_id,
+ path=path,
+ content=content,
+ )
+
+ try:
+ response = await self._stub.WriteFile(request)
+ if not response.success:
+ raise FileOperationError(f"Failed to write file: {response.error}")
+ except grpc.RpcError as e:
+ if e.code() == grpc.StatusCode.NOT_FOUND:
+ raise SandboxNotFoundError("Session not found") from e
+ raise FileOperationError(f"gRPC error: {e.details()}") from e
+
+ async def read_file(self, path: str) -> bytes:
+ """Read a file from the sandbox.
+
+ Args:
+ path: Absolute path in the sandbox filesystem.
+
+ Returns:
+ The file contents as bytes.
+
+ Raises:
+ SandboxNotFoundError: If the session no longer exists.
+ FileOperationError: If the file cannot be read.
+ """
+ if self._destroyed:
+ raise SandboxNotFoundError("Sandbox has been destroyed")
+
+ request = sandbox_pb2.ReadFileRequest(
+ session_id=self.session_id,
+ path=path,
+ )
+
+ try:
+ response = await self._stub.ReadFile(request)
+ if response.error:
+ raise FileOperationError(f"Failed to read file: {response.error}")
+ return response.content
+ except grpc.RpcError as e:
+ if e.code() == grpc.StatusCode.NOT_FOUND:
+ raise SandboxNotFoundError("Session not found") from e
+ raise FileOperationError(f"gRPC error: {e.details()}") from e
+
+ async def read_file_text(self, path: str, encoding: str = "utf-8") -> str:
+ """Read a text file from the sandbox.
+
+ Args:
+ path: Absolute path in the sandbox filesystem.
+ encoding: Text encoding (default: utf-8).
+
+ Returns:
+ The file contents as a string.
+ """
+ content = await self.read_file(path)
+ return content.decode(encoding)
+
+ async def set_env(self, env: Dict[str, str]) -> None:
+ """Set environment variables for subsequent commands.
+
+ Args:
+ env: Dictionary of environment variables to set.
+
+ Raises:
+ SandboxNotFoundError: If the session no longer exists.
+ """
+ if self._destroyed:
+ raise SandboxNotFoundError("Sandbox has been destroyed")
+
+ request = sandbox_pb2.SetEnvRequest(
+ session_id=self.session_id,
+ env=env,
+ )
+
+ try:
+ await self._stub.SetEnv(request)
+ except grpc.RpcError as e:
+ if e.code() == grpc.StatusCode.NOT_FOUND:
+ raise SandboxNotFoundError("Session not found") from e
+ raise
+
+ async def set_cwd(self, cwd: str) -> None:
+ """Set the working directory for subsequent commands.
+
+ Args:
+ cwd: The new working directory path.
+
+ Raises:
+ SandboxNotFoundError: If the session no longer exists.
+ """
+ if self._destroyed:
+ raise SandboxNotFoundError("Sandbox has been destroyed")
+
+ request = sandbox_pb2.SetCwdRequest(
+ session_id=self.session_id,
+ cwd=cwd,
+ )
+
+ try:
+ await self._stub.SetCwd(request)
+ except grpc.RpcError as e:
+ if e.code() == grpc.StatusCode.NOT_FOUND:
+ raise SandboxNotFoundError("Session not found") from e
+ raise
+
+ async def destroy(self) -> None:
+ """Destroy this sandbox session.
+
+ After calling this method, the sandbox cannot be used anymore.
+ """
+ if self._destroyed:
+ return
+
+ try:
+ response = await self._http_client.delete(
+ f"{self._http_base_url}/sessions/{self.session_id}"
+ )
+ response.raise_for_status()
+ except Exception:
+ pass # Best effort cleanup
+ finally:
+ self._destroyed = True
+
+ async def __aenter__(self):
+ """Async context manager entry."""
+ return self
+
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
+ """Async context manager exit - destroys the sandbox."""
+ await self.destroy()
+ return False
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
new file mode 100644
index 00000000..ab4ca415
--- /dev/null
+++ b/sdk/python/pyproject.toml
@@ -0,0 +1,47 @@
+[build-system]
+requires = ["setuptools>=61.0", "grpcio-tools>=1.60.0"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "opensandbox"
+version = "0.1.0"
+description = "Python SDK for OpenSandbox - High-performance Linux sandbox with gRPC support"
+readme = "README.md"
+requires-python = ">=3.9"
+license = {text = "MIT"}
+authors = [
+ {name = "OpenSandbox Team"}
+]
+classifiers = [
+ "Development Status :: 4 - Beta",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+]
+dependencies = [
+ "grpcio>=1.60.0",
+ "grpcio-tools>=1.60.0",
+ "protobuf>=4.25.0",
+ "httpx>=0.27.0",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=7.0.0",
+ "pytest-asyncio>=0.21.0",
+]
+
+[project.urls]
+"Homepage" = "https://github.com/yourusername/opensandbox"
+"Bug Tracker" = "https://github.com/yourusername/opensandbox/issues"
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["opensandbox*"]
+
+[tool.setuptools.package-data]
+opensandbox = ["proto/*.py"]
diff --git a/src/grpc_server.rs b/src/grpc_server.rs
new file mode 100644
index 00000000..a53d6ad6
--- /dev/null
+++ b/src/grpc_server.rs
@@ -0,0 +1,203 @@
+//! gRPC server implementation using Tonic.
+
+use crate::sandbox::{self, RunConfig};
+use crate::state::AppState;
+use std::net::SocketAddr;
+use std::time::Instant;
+use tonic::{Request, Response, Status};
+use tracing::info;
+
+// Import generated protobuf types
+pub mod proto {
+ tonic::include_proto!("sandbox");
+}
+
+use proto::sandbox_service_server::{SandboxService, SandboxServiceServer};
+use proto::{
+ ReadFileRequest, ReadFileResponse, RunCommandRequest, RunCommandResponse,
+ SetCwdRequest, SetCwdResponse, SetEnvRequest, SetEnvResponse,
+ WriteFileRequest, WriteFileResponse,
+};
+
+/// gRPC service implementation.
+pub struct SandboxServiceImpl {
+ state: AppState,
+}
+
+impl SandboxServiceImpl {
+ pub fn new(state: AppState) -> Self {
+ Self { state }
+ }
+}
+
+#[tonic::async_trait]
+impl SandboxService for SandboxServiceImpl {
+ async fn run_command(
+ &self,
+ request: Request<RunCommandRequest>,
+ ) -> Result<Response<RunCommandResponse>, Status> {
+ let req = request.into_inner();
+ info!("gRPC RunCommand: session={}, command={:?}", req.session_id, req.command);
+
+ // Get session info
+ let (sandbox_root, mut env, cwd) = {
+ let mut sessions = self.state.sessions.write().await;
+ let session = sessions
+ .get_mut(&req.session_id)
+ .ok_or_else(|| Status::not_found("Session not found"))?;
+ session.last_used = Instant::now();
+ (session.sandbox_root.clone(), session.env.clone(), session.cwd.clone())
+ };
+
+ // Merge request env with session env
+ env.extend(req.env);
+ let cwd = if !req.cwd.is_empty() && req.cwd != "/" { req.cwd } else { cwd };
+
+ let config = RunConfig {
+ command: req.command,
+ time_ms: if req.time_ms > 0 { req.time_ms } else { 300000 },
+ mem_kb: if req.mem_kb > 0 { req.mem_kb } else { 2097152 },
+ fsize_kb: if req.fsize_kb > 0 { req.fsize_kb } else { 1048576 },
+ nofile: if req.nofile > 0 { req.nofile } else { 256 },
+ env,
+ cwd,
+ };
+
+ let result = tokio::task::spawn_blocking(move || {
+ sandbox::run_in_session(&sandbox_root, &config)
+ })
+ .await
+ .map_err(|e| Status::internal(e.to_string()))?
+ .map_err(|e| Status::internal(e))?;
+
+ Ok(Response::new(RunCommandResponse {
+ stdout: result.stdout,
+ stderr: result.stderr,
+ exit_code: result.exit_code.unwrap_or(0),
+ signal: result.signal.unwrap_or(0),
+ }))
+ }
+
+ async fn write_file(
+ &self,
+ request: Request<WriteFileRequest>,
+ ) -> Result<Response<WriteFileResponse>, Status> {
+ let req = request.into_inner();
+ info!("gRPC WriteFile: session={}, path={}", req.session_id, req.path);
+
+ // Get sandbox root
+ let sandbox_root = {
+ let mut sessions = self.state.sessions.write().await;
+ let session = sessions
+ .get_mut(&req.session_id)
+ .ok_or_else(|| Status::not_found("Session not found"))?;
+ session.last_used = Instant::now();
+ session.sandbox_root.clone()
+ };
+
+ // Write file directly (no shell command needed)
+ let path = req.path;
+ let content = req.content;
+ let result = tokio::task::spawn_blocking(move || {
+ sandbox::write_file_in_sandbox(&sandbox_root, &path, &content)
+ })
+ .await
+ .map_err(|e| Status::internal(e.to_string()))?;
+
+ match result {
+ Ok(()) => Ok(Response::new(WriteFileResponse {
+ success: true,
+ error: String::new(),
+ })),
+ Err(e) => Ok(Response::new(WriteFileResponse {
+ success: false,
+ error: e,
+ })),
+ }
+ }
+
+ async fn read_file(
+ &self,
+ request: Request<ReadFileRequest>,
+ ) -> Result<Response<ReadFileResponse>, Status> {
+ let req = request.into_inner();
+ info!("gRPC ReadFile: session={}, path={}", req.session_id, req.path);
+
+ // Get sandbox root
+ let sandbox_root = {
+ let mut sessions = self.state.sessions.write().await;
+ let session = sessions
+ .get_mut(&req.session_id)
+ .ok_or_else(|| Status::not_found("Session not found"))?;
+ session.last_used = Instant::now();
+ session.sandbox_root.clone()
+ };
+
+ // Read file directly (no shell command needed)
+ let path = req.path;
+ let result = tokio::task::spawn_blocking(move || {
+ sandbox::read_file_in_sandbox(&sandbox_root, &path)
+ })
+ .await
+ .map_err(|e| Status::internal(e.to_string()))?;
+
+ match result {
+ Ok(content) => Ok(Response::new(ReadFileResponse {
+ content,
+ error: String::new(),
+ })),
+ Err(e) => Ok(Response::new(ReadFileResponse {
+ content: Vec::new(),
+ error: e,
+ })),
+ }
+ }
+
+ async fn set_env(
+ &self,
+ request: Request<SetEnvRequest>,
+ ) -> Result<Response<SetEnvResponse>, Status> {
+ let req = request.into_inner();
+ info!("gRPC SetEnv: session={}", req.session_id);
+
+ let mut sessions = self.state.sessions.write().await;
+ let session = sessions
+ .get_mut(&req.session_id)
+ .ok_or_else(|| Status::not_found("Session not found"))?;
+ session.env.extend(req.env);
+ session.last_used = Instant::now();
+
+ Ok(Response::new(SetEnvResponse { success: true }))
+ }
+
+ async fn set_cwd(
+ &self,
+ request: Request<SetCwdRequest>,
+ ) -> Result<Response<SetCwdResponse>, Status> {
+ let req = request.into_inner();
+ info!("gRPC SetCwd: session={}, cwd={}", req.session_id, req.cwd);
+
+ let mut sessions = self.state.sessions.write().await;
+ let session = sessions
+ .get_mut(&req.session_id)
+ .ok_or_else(|| Status::not_found("Session not found"))?;
+ session.cwd = req.cwd;
+ session.last_used = Instant::now();
+
+ Ok(Response::new(SetCwdResponse { success: true }))
+ }
+}
+
+/// Run the gRPC server on the given port with the provided state.
+pub async fn run_server(port: u16, state: AppState) {
+ let addr = SocketAddr::from(([0, 0, 0, 0], port));
+ info!("Starting gRPC server on {}", addr);
+
+ let service = SandboxServiceImpl::new(state);
+
+ tonic::transport::Server::builder()
+ .add_service(SandboxServiceServer::new(service))
+ .serve(addr)
+ .await
+ .unwrap();
+}
diff --git a/src/http_server.rs b/src/http_server.rs
new file mode 100644
index 00000000..a286ec85
--- /dev/null
+++ b/src/http_server.rs
@@ -0,0 +1,296 @@
+//! HTTP server implementation using Axum.
+
+use crate::sandbox::{self, RunConfig, RunResult};
+use crate::state::{AppState, Session, Sessions, SESSION_TTL_SECS};
+use axum::{
+ extract::{Path, State},
+ http::StatusCode,
+ routing::{delete, get, post},
+ Json, Router,
+};
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::time::{Duration, Instant};
+use tokio::time::interval;
+use tracing::info;
+
+// Request/Response types
+#[derive(Deserialize)]
+struct CreateSessionRequest {
+ #[serde(default)]
+ env: HashMap<String, String>,
+}
+
+#[derive(Serialize)]
+struct CreateSessionResponse {
+ session_id: String,
+}
+
+#[derive(Deserialize)]
+struct RunRequest {
+ command: Vec<String>,
+ #[serde(default = "default_time")]
+ time: u64,
+ #[serde(default = "default_mem")]
+ mem: u64,
+ #[serde(default = "default_fsize")]
+ fsize: u64,
+ #[serde(default = "default_nofile")]
+ nofile: u64,
+ #[serde(default)]
+ env: HashMap<String, String>,
+ #[serde(default = "default_cwd")]
+ cwd: String,
+}
+
+fn default_time() -> u64 { 300000 }
+fn default_mem() -> u64 { 2097152 }
+fn default_nofile() -> u64 { 256 }
+fn default_fsize() -> u64 { 1048576 }
+fn default_cwd() -> String { "/".to_string() }
+
+#[derive(Serialize)]
+struct SessionInfo {
+ id: String,
+ env: HashMap<String, String>,
+ cwd: String,
+ age_secs: u64,
+ idle_secs: u64,
+}
+
+#[derive(Deserialize)]
+struct SetEnvRequest {
+ env: HashMap<String, String>,
+}
+
+#[derive(Deserialize)]
+struct SetCwdRequest {
+ cwd: String,
+}
+
+/// Run the HTTP server on the given port with the provided state.
+pub async fn run_server(port: u16, state: AppState) {
+ // Spawn cleanup task
+ let sessions_clone = state.sessions.clone();
+ tokio::spawn(async move {
+ let mut interval = interval(Duration::from_secs(60));
+ loop {
+ interval.tick().await;
+ cleanup_expired_sessions(&sessions_clone).await;
+ }
+ });
+
+ let app = Router::new()
+ // Session management
+ .route("/sessions", post(create_session))
+ .route("/sessions", get(list_sessions))
+ .route("/sessions/:id", get(get_session))
+ .route("/sessions/:id", delete(delete_session))
+ .route("/sessions/:id/run", post(run_in_session))
+ .route("/sessions/:id/env", post(set_env))
+ .route("/sessions/:id/cwd", post(set_cwd))
+ // Stateless run
+ .route("/run", post(run_oneshot))
+ // Health check
+ .route("/health", get(health))
+ .with_state(state);
+
+ let addr = SocketAddr::from(([0, 0, 0, 0], port));
+ info!("Starting HTTP server on {}", addr);
+
+ let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
+ axum::serve(listener, app).await.unwrap();
+}
+
+async fn health() -> &'static str {
+ "OK"
+}
+
+async fn create_session(
+ State(state): State<AppState>,
+ Json(req): Json<CreateSessionRequest>,
+) -> Result<Json<CreateSessionResponse>, (StatusCode, String)> {
+ let session_id = uuid::Uuid::new_v4().to_string();
+
+ let sandbox_root = tokio::task::spawn_blocking({
+ let session_id = session_id.clone();
+ move || sandbox::create_session_sandbox(&session_id)
+ })
+ .await
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
+
+ let session = Session {
+ id: session_id.clone(),
+ sandbox_root,
+ env: req.env,
+ cwd: "/".to_string(),
+ created_at: Instant::now(),
+ last_used: Instant::now(),
+ };
+
+ state.sessions.write().await.insert(session_id.clone(), session);
+ info!("Created session: {}", session_id);
+
+ Ok(Json(CreateSessionResponse { session_id }))
+}
+
+async fn list_sessions(
+ State(state): State<AppState>,
+) -> Json<Vec<SessionInfo>> {
+ let sessions = state.sessions.read().await;
+ let now = Instant::now();
+ let list: Vec<SessionInfo> = sessions
+ .values()
+ .map(|s| SessionInfo {
+ id: s.id.clone(),
+ env: s.env.clone(),
+ cwd: s.cwd.clone(),
+ age_secs: now.duration_since(s.created_at).as_secs(),
+ idle_secs: now.duration_since(s.last_used).as_secs(),
+ })
+ .collect();
+ Json(list)
+}
+
+async fn get_session(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+) -> Result<Json<SessionInfo>, StatusCode> {
+ let sessions = state.sessions.read().await;
+ let session = sessions.get(&id).ok_or(StatusCode::NOT_FOUND)?;
+ let now = Instant::now();
+ Ok(Json(SessionInfo {
+ id: session.id.clone(),
+ env: session.env.clone(),
+ cwd: session.cwd.clone(),
+ age_secs: now.duration_since(session.created_at).as_secs(),
+ idle_secs: now.duration_since(session.last_used).as_secs(),
+ }))
+}
+
+async fn delete_session(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+) -> Result<StatusCode, StatusCode> {
+ let mut sessions = state.sessions.write().await;
+ if let Some(session) = sessions.remove(&id) {
+ let sandbox_root = session.sandbox_root;
+ tokio::task::spawn_blocking(move || {
+ sandbox::destroy_session_sandbox(&sandbox_root);
+ });
+ info!("Deleted session: {}", id);
+ Ok(StatusCode::NO_CONTENT)
+ } else {
+ Err(StatusCode::NOT_FOUND)
+ }
+}
+
+async fn set_env(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ Json(req): Json<SetEnvRequest>,
+) -> Result<StatusCode, StatusCode> {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&id).ok_or(StatusCode::NOT_FOUND)?;
+ session.env.extend(req.env);
+ session.last_used = Instant::now();
+ Ok(StatusCode::OK)
+}
+
+async fn set_cwd(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ Json(req): Json<SetCwdRequest>,
+) -> Result<StatusCode, StatusCode> {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions.get_mut(&id).ok_or(StatusCode::NOT_FOUND)?;
+ session.cwd = req.cwd;
+ session.last_used = Instant::now();
+ Ok(StatusCode::OK)
+}
+
+async fn run_in_session(
+ State(state): State<AppState>,
+ Path(id): Path<String>,
+ Json(req): Json<RunRequest>,
+) -> Result<Json<RunResult>, (StatusCode, String)> {
+ // Get session info
+ let (sandbox_root, mut env, cwd) = {
+ let mut sessions = state.sessions.write().await;
+ let session = sessions
+ .get_mut(&id)
+ .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;
+ session.last_used = Instant::now();
+ (session.sandbox_root.clone(), session.env.clone(), session.cwd.clone())
+ };
+
+ // Merge request env with session env
+ env.extend(req.env);
+ let cwd = if req.cwd != "/" { req.cwd } else { cwd };
+
+ let config = RunConfig {
+ command: req.command,
+ time_ms: req.time,
+ mem_kb: req.mem,
+ fsize_kb: req.fsize,
+ nofile: req.nofile,
+ env,
+ cwd,
+ };
+
+ let result = tokio::task::spawn_blocking(move || {
+ sandbox::run_in_session(&sandbox_root, &config)
+ })
+ .await
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
+
+ Ok(Json(result))
+}
+
+async fn run_oneshot(
+ Json(req): Json<RunRequest>,
+) -> Result<Json<RunResult>, (StatusCode, String)> {
+ info!("POST /run - command: {:?}", req.command);
+ let config = RunConfig {
+ command: req.command,
+ time_ms: req.time,
+ mem_kb: req.mem,
+ fsize_kb: req.fsize,
+ nofile: req.nofile,
+ env: req.env,
+ cwd: req.cwd,
+ };
+
+ let result = tokio::task::spawn_blocking(move || sandbox::run_oneshot(&config))
+ .await
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
+ .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
+
+ info!("POST /run - result: exit={:?} signal={:?}", result.exit_code, result.signal);
+ Ok(Json(result))
+}
+
+async fn cleanup_expired_sessions(sessions: &Sessions) {
+ let mut sessions = sessions.write().await;
+ let now = Instant::now();
+ let ttl = Duration::from_secs(SESSION_TTL_SECS);
+
+ let expired: Vec<String> = sessions
+ .iter()
+ .filter(|(_, s)| now.duration_since(s.last_used) > ttl)
+ .map(|(id, _)| id.clone())
+ .collect();
+
+ for id in expired {
+ if let Some(session) = sessions.remove(&id) {
+ info!("Cleaning up expired session: {}", id);
+ let sandbox_root = session.sandbox_root;
+ tokio::task::spawn_blocking(move || {
+ sandbox::destroy_session_sandbox(&sandbox_root);
+ });
+ }
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index 310d7790..b291e186 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,12 +1,21 @@
-//! Isolate - Linux sandbox with HTTP API and stateful sessions.
+//! OpenSandbox - Linux sandbox with HTTP API and gRPC support.
//!
//! Usage:
-//! isolate serve [--port 8080] # Start HTTP server
-//! isolate --run -- <command> [args] # CLI mode (original)
+//! opensandbox serve [--port 8080] [--grpc-port 50051] # Start HTTP + gRPC servers
+//! opensandbox --run -- <command> [args] # CLI mode (original)
#[cfg(not(target_os = "linux"))]
compile_error!("This program only works on Linux.");
+#[cfg(target_os = "linux")]
+mod grpc_server;
+#[cfg(target_os = "linux")]
+mod http_server;
+#[cfg(target_os = "linux")]
+mod sandbox;
+#[cfg(target_os = "linux")]
+mod state;
+
#[cfg(target_os = "linux")]
use clap::{Parser, Subcommand};
#[cfg(target_os = "linux")]
@@ -14,8 +23,8 @@ use std::collections::HashMap;
#[cfg(target_os = "linux")]
#[derive(Parser, Debug)]
-#[command(name = "isolate")]
-#[command(about = "Linux sandbox with HTTP API")]
+#[command(name = "opensandbox")]
+#[command(about = "Linux sandbox with HTTP API and gRPC support")]
struct Args {
#[command(subcommand)]
command: Option<Commands>,
@@ -48,11 +57,15 @@ struct Args {
#[cfg(target_os = "linux")]
#[derive(Subcommand, Debug)]
enum Commands {
- /// Start the HTTP server
+ /// Start the HTTP and gRPC servers
Serve {
- /// Port to listen on
+ /// HTTP port to listen on
#[arg(long, default_value = "8080")]
port: u16,
+
+ /// gRPC port to listen on
+ #[arg(long, default_value = "50051")]
+ grpc_port: u16,
},
}
@@ -72,8 +85,27 @@ async fn main() {
}
match args.command {
- Some(Commands::Serve { port }) => {
- server::run_server(port).await;
+ Some(Commands::Serve { port, grpc_port }) => {
+ // Create shared state
+ let state = state::AppState::new();
+
+ // Spawn HTTP server
+ let http_state = state.clone();
+ let http_handle = tokio::spawn(async move {
+ http_server::run_server(port, http_state).await;
+ });
+
+ // Spawn gRPC server
+ let grpc_state = state.clone();
+ let grpc_handle = tokio::spawn(async move {
+ grpc_server::run_server(grpc_port, grpc_state).await;
+ });
+
+ // Wait for both servers (they run forever)
+ tokio::select! {
+ _ = http_handle => eprintln!("HTTP server exited"),
+ _ = grpc_handle => eprintln!("gRPC server exited"),
+ }
}
None if args.run => {
// Legacy CLI mode
@@ -114,664 +146,3 @@ fn main() {
eprintln!("This program only works on Linux.");
std::process::exit(1);
}
-
-// ============================================================================
-// Sandbox module
-// ============================================================================
-#[cfg(target_os = "linux")]
-mod sandbox {
- use nix::mount::{mount, umount2, MntFlags, MsFlags};
- use nix::sched::{clone, CloneFlags};
- use nix::sys::resource::{setrlimit, Resource};
- use nix::sys::signal::Signal;
- use nix::sys::wait::{waitpid, WaitStatus};
- use nix::unistd::{chdir, chroot, execvpe, pipe, setgid, setuid, Gid, Uid};
- use std::collections::HashMap;
- use std::ffi::CString;
- use std::fs;
- use std::io::{Read, Write};
- use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
- use std::os::unix::fs::PermissionsExt;
- use std::path::{Path, PathBuf};
- use tracing::info;
-
- const NOBODY_UID: u32 = 65534;
- const NOBODY_GID: u32 = 65534;
-
- #[derive(Debug, Clone)]
- pub struct RunConfig {
- pub command: Vec<String>,
- pub time_ms: u64,
- pub mem_kb: u64,
- pub fsize_kb: u64,
- pub nofile: u64,
- pub env: HashMap<String, String>,
- pub cwd: String,
- }
-
- #[derive(Debug, Clone, serde::Serialize)]
- pub struct RunResult {
- pub stdout: String,
- pub stderr: String,
- pub exit_code: Option<i32>,
- pub signal: Option<i32>,
- }
-
- /// Run a command in a fresh sandbox (no session, cleanup after)
- pub fn run_oneshot(config: &RunConfig) -> Result<RunResult, String> {
- info!("=== run_oneshot called ===");
- info!(command = ?config.command, "Command to run");
- let sandbox_root = PathBuf::from("/tmp/sandbox-oneshot");
- info!("Setting up sandbox dir...");
- setup_sandbox_dir(&sandbox_root)?;
- info!("Sandbox dir ready, running command...");
- let result = run_in_sandbox(&sandbox_root, config);
- info!(result = ?result, "Command finished");
- cleanup_sandbox(&sandbox_root);
- result
- }
-
- /// Run a command in an existing session sandbox
- pub fn run_in_session(sandbox_root: &Path, config: &RunConfig) -> Result<RunResult, String> {
- run_in_sandbox(sandbox_root, config)
- }
-
- /// Create a new session sandbox directory
- pub fn create_session_sandbox(session_id: &str) -> Result<PathBuf, String> {
- let sandbox_root = PathBuf::from(format!("/tmp/sandbox-{}", session_id));
- setup_sandbox_dir(&sandbox_root)?;
- Ok(sandbox_root)
- }
-
- /// Cleanup a session sandbox
- pub fn destroy_session_sandbox(sandbox_root: &Path) {
- cleanup_sandbox(sandbox_root);
- }
-
- fn setup_sandbox_dir(sandbox_root: &Path) -> Result<(), String> {
- // Clean up if exists
- if sandbox_root.exists() {
- cleanup_sandbox(sandbox_root);
- }
-
- fs::create_dir_all(sandbox_root).map_err(|e| format!("mkdir: {}", e))?;
-
- // Mount tmpfs at sandbox root
- mount(
- Some("tmpfs"),
- sandbox_root,
- Some("tmpfs"),
- MsFlags::MS_NOSUID | MsFlags::MS_NODEV,
- Some("size=2G,mode=755"), // Large repos need more space
- )
- .map_err(|e| format!("mount tmpfs: {}", e))?;
-
- // Bind mount system directories
- let bind_dirs = ["/bin", "/lib", "/lib64", "/usr", "/etc"];
- for dir in &bind_dirs {
- let target = sandbox_root.join(&dir[1..]);
- if Path::new(dir).exists() {
- fs::create_dir_all(&target).map_err(|e| format!("mkdir {}: {}", dir, e))?;
- mount(
- Some(*dir),
- &target,
- None::<&str>,
- MsFlags::MS_BIND | MsFlags::MS_REC,
- None::<&str>,
- )
- .map_err(|e| format!("bind mount {}: {}", dir, e))?;
- mount(
- None::<&str>,
- &target,
- None::<&str>,
- MsFlags::MS_BIND | MsFlags::MS_REMOUNT | MsFlags::MS_RDONLY | MsFlags::MS_REC,
- None::<&str>,
- )
- .map_err(|e| format!("remount ro {}: {}", dir, e))?;
- }
- }
-
- // Create writable directories
- let tmp_dir = sandbox_root.join("tmp");
- fs::create_dir_all(&tmp_dir).map_err(|e| format!("mkdir tmp: {}", e))?;
- fs::set_permissions(&tmp_dir, fs::Permissions::from_mode(0o1777))
- .map_err(|e| format!("chmod tmp: {}", e))?;
-
- let dev_dir = sandbox_root.join("dev");
- fs::create_dir_all(&dev_dir).map_err(|e| format!("mkdir dev: {}", e))?;
-
- // Create essential device nodes by bind mounting from host
- let devices = [("null", 0o666), ("zero", 0o666), ("urandom", 0o666), ("random", 0o666)];
- for (dev, _mode) in &devices {
- let host_dev = format!("/dev/{}", dev);
- let sandbox_dev = dev_dir.join(dev);
- if Path::new(&host_dev).exists() {
- // Create empty file to mount over
- fs::write(&sandbox_dev, "").map_err(|e| format!("touch {}: {}", dev, e))?;
- mount(
- Some(host_dev.as_str()),
- &sandbox_dev,
- None::<&str>,
- MsFlags::MS_BIND,
- None::<&str>,
- )
- .map_err(|e| format!("bind mount {}: {}", dev, e))?;
- }
- }
-
- // Mount proc
- let proc_dir = sandbox_root.join("proc");
- fs::create_dir_all(&proc_dir).map_err(|e| format!("mkdir proc: {}", e))?;
- mount(
- Some("proc"),
- &proc_dir,
- Some("proc"),
- MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC,
- None::<&str>,
- )
- .map_err(|e| format!("mount proc: {}", e))?;
-
- // Create home directory for the sandbox
- let home_dir = sandbox_root.join("home");
- fs::create_dir_all(&home_dir).map_err(|e| format!("mkdir home: {}", e))?;
- fs::set_permissions(&home_dir, fs::Permissions::from_mode(0o755))
- .map_err(|e| format!("chmod home: {}", e))?;
-
- Ok(())
- }
-
- fn run_in_sandbox(sandbox_root: &Path, config: &RunConfig) -> Result<RunResult, String> {
- info!(command = ?config.command, "Running command");
- info!(sandbox_root = ?sandbox_root, "Sandbox root");
- info!(time_ms = config.time_ms, mem_kb = config.mem_kb,
- fsize_kb = config.fsize_kb, nofile = config.nofile, "Limits");
-
- // Create pipes for stdout/stderr capture
- let (stdout_read, stdout_write) = pipe().map_err(|e| format!("pipe: {}", e))?;
- let (stderr_read, stderr_write) = pipe().map_err(|e| format!("pipe: {}", e))?;
-
- // Get raw fds for the child process
- let stdout_write_fd = stdout_write.as_raw_fd();
- let stderr_write_fd = stderr_write.as_raw_fd();
-
- let sandbox_root = sandbox_root.to_path_buf();
- let config = config.clone();
-
- const STACK_SIZE: usize = 1024 * 1024;
- let mut stack = vec![0u8; STACK_SIZE];
-
- let clone_flags = CloneFlags::CLONE_NEWPID | CloneFlags::CLONE_NEWNS;
-
- let child_fn = Box::new(move || {
- // Redirect stdout/stderr to pipes
- unsafe {
- libc::dup2(stdout_write_fd, 1);
- libc::dup2(stderr_write_fd, 2);
- libc::close(stdout_write_fd);
- libc::close(stderr_write_fd);
- }
-
- if let Err(e) = run_child(&sandbox_root, &config) {
- eprintln!("Child error: {}", e);
- return 1;
- }
- 0
- });
-
- info!("Calling clone()...");
- let child_pid = unsafe {
- clone(
- child_fn,
- &mut stack,
- clone_flags,
- Some(Signal::SIGCHLD as i32),
- )
- }
- .map_err(|e| format!("clone: {}", e))?;
- info!(child_pid = ?child_pid, "Child spawned");
-
- // Close write ends in parent (drop the OwnedFds)
- drop(stdout_write);
- drop(stderr_write);
-
- // Wait for child
- info!("Waiting for child...");
- let status = waitpid(child_pid, None).map_err(|e| format!("waitpid: {}", e))?;
- info!(status = ?status, "Child exited");
-
- // Read output from pipes
- let stdout = read_from_fd(stdout_read);
- let stderr = read_from_fd(stderr_read);
- info!(stdout_len = stdout.len(), stderr_len = stderr.len(), "Output captured");
-
- let (exit_code, signal) = match status {
- WaitStatus::Exited(_, code) => (Some(code), None),
- WaitStatus::Signaled(_, sig, _) => (None, Some(sig as i32)),
- _ => (None, None),
- };
-
- Ok(RunResult {
- stdout,
- stderr,
- exit_code,
- signal,
- })
- }
-
- fn read_from_fd(fd: OwnedFd) -> String {
- let mut file = unsafe { std::fs::File::from_raw_fd(fd.as_raw_fd()) };
- std::mem::forget(fd); // Don't double-close
- let mut output = String::new();
- let _ = file.read_to_string(&mut output);
- output
- }
-
- fn run_child(sandbox_root: &Path, config: &RunConfig) -> Result<(), String> {
- eprintln!("[child] Starting, sandbox_root={:?}", sandbox_root);
-
- // chroot into sandbox
- eprintln!("[child] chroot...");
- chroot(sandbox_root).map_err(|e| format!("chroot: {}", e))?;
- eprintln!("[child] chdir to {:?}...", config.cwd);
- chdir(config.cwd.as_str()).map_err(|e| format!("chdir: {}", e))?;
-
- // Set resource limits
- eprintln!("[child] Setting resource limits...");
- set_resource_limits(config)?;
- eprintln!("[child] Resource limits set");
-
- // TODO: Fix privilege dropping - currently disabled due to deadlock in multi-threaded context
- // The sandbox is still isolated by PID namespace, mount namespace, and chroot
- eprintln!("[child] Skipping privilege drop (sandbox still isolated by namespaces)");
-
- // Execute command
- let cmd = CString::new(config.command[0].as_str()).map_err(|e| format!("cmd: {}", e))?;
- let args: Vec<CString> = config
- .command
- .iter()
- .map(|s| CString::new(s.as_str()).unwrap())
- .collect();
-
- // Build environment
- let mut env: Vec<CString> = config
- .env
- .iter()
- .map(|(k, v)| CString::new(format!("{}={}", k, v)).unwrap())
- .collect();
- env.push(CString::new("PATH=/usr/bin:/bin").unwrap());
- env.push(CString::new("HOME=/home").unwrap());
-
- eprintln!("[child] About to exec: {:?}", config.command);
- eprintln!("[child] Flushing stderr before exec...");
- let _ = std::io::stderr().flush();
- execvpe(&cmd, &args, &env).map_err(|e| format!("exec: {}", e))?;
- Ok(())
- }
-
- fn set_resource_limits(config: &RunConfig) -> Result<(), String> {
- let cpu_seconds = std::cmp::max(1, config.time_ms / 1000);
- eprintln!("[rlimit] CPU: {} seconds", cpu_seconds);
- setrlimit(Resource::RLIMIT_CPU, cpu_seconds, cpu_seconds)
- .map_err(|e| format!("rlimit cpu: {}", e))?;
-
- let mem_bytes = config.mem_kb * 1024;
- eprintln!("[rlimit] AS (mem): {} bytes ({} MB)", mem_bytes, mem_bytes / 1024 / 1024);
- setrlimit(Resource::RLIMIT_AS, mem_bytes, mem_bytes)
- .map_err(|e| format!("rlimit as: {}", e))?;
-
- let fsize_bytes = config.fsize_kb * 1024;
- eprintln!("[rlimit] FSIZE: {} bytes", fsize_bytes);
- setrlimit(Resource::RLIMIT_FSIZE, fsize_bytes, fsize_bytes)
- .map_err(|e| format!("rlimit fsize: {}", e))?;
-
- eprintln!("[rlimit] NOFILE: {}", config.nofile);
- setrlimit(Resource::RLIMIT_NOFILE, config.nofile, config.nofile)
- .map_err(|e| format!("rlimit nofile: {}", e))?;
-
- eprintln!("[rlimit] CORE: 0");
- setrlimit(Resource::RLIMIT_CORE, 0, 0).map_err(|e| format!("rlimit core: {}", e))?;
-
- eprintln!("[rlimit] NPROC: 64");
- setrlimit(Resource::RLIMIT_NPROC, 64, 64).map_err(|e| format!("rlimit nproc: {}", e))?;
-
- eprintln!("[rlimit] All limits set successfully");
- Ok(())
- }
-
- fn cleanup_sandbox(sandbox_root: &Path) {
- let mount_points = ["proc", "etc", "usr", "lib64", "lib", "bin"];
- for mp in &mount_points {
- let path = sandbox_root.join(mp);
- if path.exists() {
- let _ = umount2(&path, MntFlags::MNT_DETACH);
- }
- }
- let _ = umount2(sandbox_root, MntFlags::MNT_DETACH);
- let _ = fs::remove_dir_all(sandbox_root);
- }
-}
-
-// ============================================================================
-// HTTP Server module
-// ============================================================================
-#[cfg(target_os = "linux")]
-mod server {
- use crate::sandbox::{self, RunConfig, RunResult};
- use axum::{
- extract::{Path, State},
- http::StatusCode,
- routing::{delete, get, post},
- Json, Router,
- };
- use serde::{Deserialize, Serialize};
- use std::collections::HashMap;
- use std::net::SocketAddr;
- use std::path::PathBuf;
- use std::sync::Arc;
- use std::time::{Duration, Instant};
- use tokio::sync::RwLock;
- use tokio::time::interval;
- use tracing::info;
-
- const SESSION_TTL_SECS: u64 = 300; // 5 minutes
-
- #[derive(Debug)]
- struct Session {
- id: String,
- sandbox_root: PathBuf,
- env: HashMap<String, String>,
- cwd: String,
- created_at: Instant,
- last_used: Instant,
- }
-
- type Sessions = Arc<RwLock<HashMap<String, Session>>>;
-
- #[derive(Clone)]
- struct AppState {
- sessions: Sessions,
- }
-
- // Request/Response types
- #[derive(Deserialize)]
- struct CreateSessionRequest {
- #[serde(default)]
- env: HashMap<String, String>,
- }
-
- #[derive(Serialize)]
- struct CreateSessionResponse {
- session_id: String,
- }
-
- #[derive(Deserialize)]
- struct RunRequest {
- command: Vec<String>,
- #[serde(default = "default_time")]
- time: u64,
- #[serde(default = "default_mem")]
- mem: u64,
- #[serde(default = "default_fsize")]
- fsize: u64,
- #[serde(default = "default_nofile")]
- nofile: u64,
- #[serde(default)]
- env: HashMap<String, String>,
- #[serde(default = "default_cwd")]
- cwd: String,
- }
-
- fn default_time() -> u64 { 300000 } // 5 minutes - network operations like git clone need more time
- fn default_mem() -> u64 { 2097152 } // 2GB - Go programs need lots of virtual address space
- fn default_nofile() -> u64 { 256 } // Git operations need more file descriptors
- fn default_fsize() -> u64 { 1048576 } // 1GB - large repos have big pack files
- fn default_cwd() -> String { "/".to_string() }
-
- #[derive(Serialize)]
- struct SessionInfo {
- id: String,
- env: HashMap<String, String>,
- cwd: String,
- age_secs: u64,
- idle_secs: u64,
- }
-
- #[derive(Deserialize)]
- struct SetEnvRequest {
- env: HashMap<String, String>,
- }
-
- #[derive(Deserialize)]
- struct SetCwdRequest {
- cwd: String,
- }
-
- pub async fn run_server(port: u16) {
- let state = AppState {
- sessions: Arc::new(RwLock::new(HashMap::new())),
- };
-
- // Spawn cleanup task
- let sessions_clone = state.sessions.clone();
- tokio::spawn(async move {
- let mut interval = interval(Duration::from_secs(60));
- loop {
- interval.tick().await;
- cleanup_expired_sessions(&sessions_clone).await;
- }
- });
-
- let app = Router::new()
- // Session management
- .route("/sessions", post(create_session))
- .route("/sessions", get(list_sessions))
- .route("/sessions/:id", get(get_session))
- .route("/sessions/:id", delete(delete_session))
- .route("/sessions/:id/run", post(run_in_session))
- .route("/sessions/:id/env", post(set_env))
- .route("/sessions/:id/cwd", post(set_cwd))
- // Stateless run
- .route("/run", post(run_oneshot))
- // Health check
- .route("/health", get(health))
- .with_state(state);
-
- let addr = SocketAddr::from(([0, 0, 0, 0], port));
- info!("Starting server on {}", addr);
-
- let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
- axum::serve(listener, app).await.unwrap();
- }
-
- async fn health() -> &'static str {
- "OK"
- }
-
- async fn create_session(
- State(state): State<AppState>,
- Json(req): Json<CreateSessionRequest>,
- ) -> Result<Json<CreateSessionResponse>, (StatusCode, String)> {
- let session_id = uuid::Uuid::new_v4().to_string();
-
- let sandbox_root = tokio::task::spawn_blocking({
- let session_id = session_id.clone();
- move || sandbox::create_session_sandbox(&session_id)
- })
- .await
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
-
- let session = Session {
- id: session_id.clone(),
- sandbox_root,
- env: req.env,
- cwd: "/".to_string(),
- created_at: Instant::now(),
- last_used: Instant::now(),
- };
-
- state.sessions.write().await.insert(session_id.clone(), session);
- info!("Created session: {}", session_id);
-
- Ok(Json(CreateSessionResponse { session_id }))
- }
-
- async fn list_sessions(
- State(state): State<AppState>,
- ) -> Json<Vec<SessionInfo>> {
- let sessions = state.sessions.read().await;
- let now = Instant::now();
- let list: Vec<SessionInfo> = sessions
- .values()
- .map(|s| SessionInfo {
- id: s.id.clone(),
- env: s.env.clone(),
- cwd: s.cwd.clone(),
- age_secs: now.duration_since(s.created_at).as_secs(),
- idle_secs: now.duration_since(s.last_used).as_secs(),
- })
- .collect();
- Json(list)
- }
-
- async fn get_session(
- State(state): State<AppState>,
- Path(id): Path<String>,
- ) -> Result<Json<SessionInfo>, StatusCode> {
- let sessions = state.sessions.read().await;
- let session = sessions.get(&id).ok_or(StatusCode::NOT_FOUND)?;
- let now = Instant::now();
- Ok(Json(SessionInfo {
- id: session.id.clone(),
- env: session.env.clone(),
- cwd: session.cwd.clone(),
- age_secs: now.duration_since(session.created_at).as_secs(),
- idle_secs: now.duration_since(session.last_used).as_secs(),
- }))
- }
-
- async fn delete_session(
- State(state): State<AppState>,
- Path(id): Path<String>,
- ) -> Result<StatusCode, StatusCode> {
- let mut sessions = state.sessions.write().await;
- if let Some(session) = sessions.remove(&id) {
- let sandbox_root = session.sandbox_root;
- tokio::task::spawn_blocking(move || {
- sandbox::destroy_session_sandbox(&sandbox_root);
- });
- info!("Deleted session: {}", id);
- Ok(StatusCode::NO_CONTENT)
- } else {
- Err(StatusCode::NOT_FOUND)
- }
- }
-
- async fn set_env(
- State(state): State<AppState>,
- Path(id): Path<String>,
- Json(req): Json<SetEnvRequest>,
- ) -> Result<StatusCode, StatusCode> {
- let mut sessions = state.sessions.write().await;
- let session = sessions.get_mut(&id).ok_or(StatusCode::NOT_FOUND)?;
- session.env.extend(req.env);
- session.last_used = Instant::now();
- Ok(StatusCode::OK)
- }
-
- async fn set_cwd(
- State(state): State<AppState>,
- Path(id): Path<String>,
- Json(req): Json<SetCwdRequest>,
- ) -> Result<StatusCode, StatusCode> {
- let mut sessions = state.sessions.write().await;
- let session = sessions.get_mut(&id).ok_or(StatusCode::NOT_FOUND)?;
- session.cwd = req.cwd;
- session.last_used = Instant::now();
- Ok(StatusCode::OK)
- }
-
- async fn run_in_session(
- State(state): State<AppState>,
- Path(id): Path<String>,
- Json(req): Json<RunRequest>,
- ) -> Result<Json<RunResult>, (StatusCode, String)> {
- // Get session info
- let (sandbox_root, mut env, cwd) = {
- let mut sessions = state.sessions.write().await;
- let session = sessions
- .get_mut(&id)
- .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;
- session.last_used = Instant::now();
- (session.sandbox_root.clone(), session.env.clone(), session.cwd.clone())
- };
-
- // Merge request env with session env
- env.extend(req.env);
- let cwd = if req.cwd != "/" { req.cwd } else { cwd };
-
- let config = RunConfig {
- command: req.command,
- time_ms: req.time,
- mem_kb: req.mem,
- fsize_kb: req.fsize,
- nofile: req.nofile,
- env,
- cwd,
- };
-
- let result = tokio::task::spawn_blocking(move || {
- sandbox::run_in_session(&sandbox_root, &config)
- })
- .await
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
-
- Ok(Json(result))
- }
-
- async fn run_oneshot(
- Json(req): Json<RunRequest>,
- ) -> Result<Json<RunResult>, (StatusCode, String)> {
- info!("POST /run - command: {:?}", req.command);
- let config = RunConfig {
- command: req.command,
- time_ms: req.time,
- mem_kb: req.mem,
- fsize_kb: req.fsize,
- nofile: req.nofile,
- env: req.env,
- cwd: req.cwd,
- };
-
- let result = tokio::task::spawn_blocking(move || sandbox::run_oneshot(&config))
- .await
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?;
-
- info!("POST /run - result: exit={:?} signal={:?}", result.exit_code, result.signal);
- Ok(Json(result))
- }
-
- async fn cleanup_expired_sessions(sessions: &Sessions) {
- let mut sessions = sessions.write().await;
- let now = Instant::now();
- let ttl = Duration::from_secs(SESSION_TTL_SECS);
-
- let expired: Vec<String> = sessions
- .iter()
- .filter(|(_, s)| now.duration_since(s.last_used) > ttl)
- .map(|(id, _)| id.clone())
- .collect();
-
- for id in expired {
- if let Some(session) = sessions.remove(&id) {
- info!("Cleaning up expired session: {}", id);
- let sandbox_root = session.sandbox_root;
- tokio::task::spawn_blocking(move || {
- sandbox::destroy_session_sandbox(&sandbox_root);
- });
- }
- }
- }
-}
diff --git a/src/sandbox.rs b/src/sandbox.rs
new file mode 100644
index 00000000..09266fa4
--- /dev/null
+++ b/src/sandbox.rs
@@ -0,0 +1,376 @@
+//! Core sandbox execution logic.
+
+use nix::mount::{mount, umount2, MntFlags, MsFlags};
+use nix::sched::{clone, CloneFlags};
+use nix::sys::resource::{setrlimit, Resource};
+use nix::sys::signal::Signal;
+use nix::sys::wait::{waitpid, WaitStatus};
+use nix::unistd::{chdir, chroot, execvpe};
+use std::collections::HashMap;
+use std::ffi::CString;
+use std::fs;
+use std::io::{Read, Write};
+use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
+use std::os::unix::fs::PermissionsExt;
+use std::path::{Path, PathBuf};
+use tracing::info;
+
+/// Configuration for running a command in the sandbox.
+#[derive(Debug, Clone)]
+pub struct RunConfig {
+ pub command: Vec<String>,
+ pub time_ms: u64,
+ pub mem_kb: u64,
+ pub fsize_kb: u64,
+ pub nofile: u64,
+ pub env: HashMap<String, String>,
+ pub cwd: String,
+}
+
+/// Result of running a command.
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct RunResult {
+ pub stdout: String,
+ pub stderr: String,
+ pub exit_code: Option<i32>,
+ pub signal: Option<i32>,
+}
+
+/// Run a command in a fresh sandbox (no session, cleanup after).
+pub fn run_oneshot(config: &RunConfig) -> Result<RunResult, String> {
+ info!("=== run_oneshot called ===");
+ info!(command = ?config.command, "Command to run");
+ let sandbox_root = PathBuf::from("/tmp/sandbox-oneshot");
+ info!("Setting up sandbox dir...");
+ setup_sandbox_dir(&sandbox_root)?;
+ info!("Sandbox dir ready, running command...");
+ let result = run_in_sandbox(&sandbox_root, config);
+ info!(result = ?result, "Command finished");
+ cleanup_sandbox(&sandbox_root);
+ result
+}
+
+/// Run a command in an existing session sandbox.
+pub fn run_in_session(sandbox_root: &Path, config: &RunConfig) -> Result<RunResult, String> {
+ run_in_sandbox(sandbox_root, config)
+}
+
+/// Create a new session sandbox directory.
+pub fn create_session_sandbox(session_id: &str) -> Result<PathBuf, String> {
+ let sandbox_root = PathBuf::from(format!("/tmp/sandbox-{}", session_id));
+ setup_sandbox_dir(&sandbox_root)?;
+ Ok(sandbox_root)
+}
+
+/// Cleanup a session sandbox.
+pub fn destroy_session_sandbox(sandbox_root: &Path) {
+ cleanup_sandbox(sandbox_root);
+}
+
+/// Write a file directly into the sandbox filesystem.
+pub fn write_file_in_sandbox(sandbox_root: &Path, path: &str, content: &[u8]) -> Result<(), String> {
+ // Normalize the path to be relative to sandbox root
+ let normalized_path = if path.starts_with('/') {
+ path.trim_start_matches('/')
+ } else {
+ path
+ };
+
+ let full_path = sandbox_root.join(normalized_path);
+
+ // Ensure parent directory exists
+ if let Some(parent) = full_path.parent() {
+ fs::create_dir_all(parent).map_err(|e| format!("mkdir parent: {}", e))?;
+ }
+
+ fs::write(&full_path, content).map_err(|e| format!("write file: {}", e))?;
+
+ // Make file accessible
+ fs::set_permissions(&full_path, fs::Permissions::from_mode(0o644))
+ .map_err(|e| format!("chmod: {}", e))?;
+
+ Ok(())
+}
+
+/// Read a file directly from the sandbox filesystem.
+pub fn read_file_in_sandbox(sandbox_root: &Path, path: &str) -> Result<Vec<u8>, String> {
+ // Normalize the path to be relative to sandbox root
+ let normalized_path = if path.starts_with('/') {
+ path.trim_start_matches('/')
+ } else {
+ path
+ };
+
+ let full_path = sandbox_root.join(normalized_path);
+
+ fs::read(&full_path).map_err(|e| format!("read file: {}", e))
+}
+
+fn setup_sandbox_dir(sandbox_root: &Path) -> Result<(), String> {
+ // Clean up if exists
+ if sandbox_root.exists() {
+ cleanup_sandbox(sandbox_root);
+ }
+
+ fs::create_dir_all(sandbox_root).map_err(|e| format!("mkdir: {}", e))?;
+
+ // Mount tmpfs at sandbox root
+ mount(
+ Some("tmpfs"),
+ sandbox_root,
+ Some("tmpfs"),
+ MsFlags::MS_NOSUID | MsFlags::MS_NODEV,
+ Some("size=2G,mode=755"),
+ )
+ .map_err(|e| format!("mount tmpfs: {}", e))?;
+
+ // Bind mount system directories
+ let bind_dirs = ["/bin", "/lib", "/lib64", "/usr", "/etc"];
+ for dir in &bind_dirs {
+ let target = sandbox_root.join(&dir[1..]);
+ if Path::new(dir).exists() {
+ fs::create_dir_all(&target).map_err(|e| format!("mkdir {}: {}", dir, e))?;
+ mount(
+ Some(*dir),
+ &target,
+ None::<&str>,
+ MsFlags::MS_BIND | MsFlags::MS_REC,
+ None::<&str>,
+ )
+ .map_err(|e| format!("bind mount {}: {}", dir, e))?;
+ mount(
+ None::<&str>,
+ &target,
+ None::<&str>,
+ MsFlags::MS_BIND | MsFlags::MS_REMOUNT | MsFlags::MS_RDONLY | MsFlags::MS_REC,
+ None::<&str>,
+ )
+ .map_err(|e| format!("remount ro {}: {}", dir, e))?;
+ }
+ }
+
+ // Create writable directories
+ let tmp_dir = sandbox_root.join("tmp");
+ fs::create_dir_all(&tmp_dir).map_err(|e| format!("mkdir tmp: {}", e))?;
+ fs::set_permissions(&tmp_dir, fs::Permissions::from_mode(0o1777))
+ .map_err(|e| format!("chmod tmp: {}", e))?;
+
+ let dev_dir = sandbox_root.join("dev");
+ fs::create_dir_all(&dev_dir).map_err(|e| format!("mkdir dev: {}", e))?;
+
+ // Create essential device nodes by bind mounting from host
+ let devices = [("null", 0o666), ("zero", 0o666), ("urandom", 0o666), ("random", 0o666)];
+ for (dev, _mode) in &devices {
+ let host_dev = format!("/dev/{}", dev);
+ let sandbox_dev = dev_dir.join(dev);
+ if Path::new(&host_dev).exists() {
+ fs::write(&sandbox_dev, "").map_err(|e| format!("touch {}: {}", dev, e))?;
+ mount(
+ Some(host_dev.as_str()),
+ &sandbox_dev,
+ None::<&str>,
+ MsFlags::MS_BIND,
+ None::<&str>,
+ )
+ .map_err(|e| format!("bind mount {}: {}", dev, e))?;
+ }
+ }
+
+ // Mount proc
+ let proc_dir = sandbox_root.join("proc");
+ fs::create_dir_all(&proc_dir).map_err(|e| format!("mkdir proc: {}", e))?;
+ mount(
+ Some("proc"),
+ &proc_dir,
+ Some("proc"),
+ MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC,
+ None::<&str>,
+ )
+ .map_err(|e| format!("mount proc: {}", e))?;
+
+ // Create home directory for the sandbox
+ let home_dir = sandbox_root.join("home");
+ fs::create_dir_all(&home_dir).map_err(|e| format!("mkdir home: {}", e))?;
+ fs::set_permissions(&home_dir, fs::Permissions::from_mode(0o755))
+ .map_err(|e| format!("chmod home: {}", e))?;
+
+ Ok(())
+}
+
+fn run_in_sandbox(sandbox_root: &Path, config: &RunConfig) -> Result<RunResult, String> {
+ info!(command = ?config.command, "Running command");
+ info!(sandbox_root = ?sandbox_root, "Sandbox root");
+ info!(time_ms = config.time_ms, mem_kb = config.mem_kb,
+ fsize_kb = config.fsize_kb, nofile = config.nofile, "Limits");
+
+ // Create pipes for stdout/stderr capture
+ let (stdout_read, stdout_write) = nix::unistd::pipe().map_err(|e| format!("pipe: {}", e))?;
+ let (stderr_read, stderr_write) = nix::unistd::pipe().map_err(|e| format!("pipe: {}", e))?;
+
+ // Get raw fds for the child process
+ let stdout_write_fd = stdout_write.as_raw_fd();
+ let stderr_write_fd = stderr_write.as_raw_fd();
+
+ let sandbox_root = sandbox_root.to_path_buf();
+ let config = config.clone();
+
+ const STACK_SIZE: usize = 1024 * 1024;
+ let mut stack = vec![0u8; STACK_SIZE];
+
+ let clone_flags = CloneFlags::CLONE_NEWPID | CloneFlags::CLONE_NEWNS;
+
+ let child_fn = Box::new(move || {
+ // Redirect stdout/stderr to pipes
+ unsafe {
+ libc::dup2(stdout_write_fd, 1);
+ libc::dup2(stderr_write_fd, 2);
+ libc::close(stdout_write_fd);
+ libc::close(stderr_write_fd);
+ }
+
+ if let Err(e) = run_child(&sandbox_root, &config) {
+ eprintln!("Child error: {}", e);
+ return 1;
+ }
+ 0
+ });
+
+ info!("Calling clone()...");
+ let child_pid = unsafe {
+ clone(
+ child_fn,
+ &mut stack,
+ clone_flags,
+ Some(Signal::SIGCHLD as i32),
+ )
+ }
+ .map_err(|e| format!("clone: {}", e))?;
+ info!(child_pid = ?child_pid, "Child spawned");
+
+ // Close write ends in parent
+ drop(stdout_write);
+ drop(stderr_write);
+
+ // Wait for child
+ info!("Waiting for child...");
+ let status = waitpid(child_pid, None).map_err(|e| format!("waitpid: {}", e))?;
+ info!(status = ?status, "Child exited");
+
+ // Read output from pipes
+ let stdout = read_from_fd(stdout_read);
+ let stderr = read_from_fd(stderr_read);
+ info!(stdout_len = stdout.len(), stderr_len = stderr.len(), "Output captured");
+
+ let (exit_code, signal) = match status {
+ WaitStatus::Exited(_, code) => (Some(code), None),
+ WaitStatus::Signaled(_, sig, _) => (None, Some(sig as i32)),
+ _ => (None, None),
+ };
+
+ Ok(RunResult {
+ stdout,
+ stderr,
+ exit_code,
+ signal,
+ })
+}
+
+fn read_from_fd(fd: OwnedFd) -> String {
+ let mut file = unsafe { std::fs::File::from_raw_fd(fd.as_raw_fd()) };
+ std::mem::forget(fd); // Don't double-close
+ let mut output = String::new();
+ let _ = file.read_to_string(&mut output);
+ output
+}
+
+fn run_child(sandbox_root: &Path, config: &RunConfig) -> Result<(), String> {
+ eprintln!("[child] Starting, sandbox_root={:?}", sandbox_root);
+
+ // chroot into sandbox
+ eprintln!("[child] chroot...");
+ chroot(sandbox_root).map_err(|e| format!("chroot: {}", e))?;
+ eprintln!("[child] chdir to {:?}...", config.cwd);
+ chdir(config.cwd.as_str()).map_err(|e| format!("chdir: {}", e))?;
+
+ // Set resource limits
+ eprintln!("[child] Setting resource limits...");
+ set_resource_limits(config)?;
+ eprintln!("[child] Resource limits set");
+
+ eprintln!("[child] Skipping privilege drop (sandbox still isolated by namespaces)");
+
+ // Execute command
+ let cmd = CString::new(config.command[0].as_str()).map_err(|e| format!("cmd: {}", e))?;
+ let args: Vec<CString> = config
+ .command
+ .iter()
+ .map(|s| CString::new(s.as_str()).unwrap())
+ .collect();
+
+ // Build environment
+ let mut env: Vec<CString> = config
+ .env
+ .iter()
+ .map(|(k, v)| CString::new(format!("{}={}", k, v)).unwrap())
+ .collect();
+ env.push(CString::new("PATH=/usr/bin:/bin").unwrap());
+ env.push(CString::new("HOME=/home").unwrap());
+
+ eprintln!("[child] About to exec: {:?}", config.command);
+ eprintln!("[child] Flushing stderr before exec...");
+ let _ = std::io::stderr().flush();
+ execvpe(&cmd, &args, &env).map_err(|e| format!("exec: {}", e))?;
+ Ok(())
+}
+
+fn set_resource_limits(config: &RunConfig) -> Result<(), String> {
+ let cpu_seconds = std::cmp::max(1, config.time_ms / 1000);
+ eprintln!("[rlimit] CPU: {} seconds", cpu_seconds);
+ setrlimit(Resource::RLIMIT_CPU, cpu_seconds, cpu_seconds)
+ .map_err(|e| format!("rlimit cpu: {}", e))?;
+
+ let mem_bytes = config.mem_kb * 1024;
+ eprintln!("[rlimit] AS (mem): {} bytes ({} MB)", mem_bytes, mem_bytes / 1024 / 1024);
+ setrlimit(Resource::RLIMIT_AS, mem_bytes, mem_bytes)
+ .map_err(|e| format!("rlimit as: {}", e))?;
+
+ let fsize_bytes = config.fsize_kb * 1024;
+ eprintln!("[rlimit] FSIZE: {} bytes", fsize_bytes);
+ setrlimit(Resource::RLIMIT_FSIZE, fsize_bytes, fsize_bytes)
+ .map_err(|e| format!("rlimit fsize: {}", e))?;
+
+ eprintln!("[rlimit] NOFILE: {}", config.nofile);
+ setrlimit(Resource::RLIMIT_NOFILE, config.nofile, config.nofile)
+ .map_err(|e| format!("rlimit nofile: {}", e))?;
+
+ eprintln!("[rlimit] CORE: 0");
+ setrlimit(Resource::RLIMIT_CORE, 0, 0).map_err(|e| format!("rlimit core: {}", e))?;
+
+ eprintln!("[rlimit] NPROC: 64");
+ setrlimit(Resource::RLIMIT_NPROC, 64, 64).map_err(|e| format!("rlimit nproc: {}", e))?;
+
+ eprintln!("[rlimit] All limits set successfully");
+ Ok(())
+}
+
+fn cleanup_sandbox(sandbox_root: &Path) {
+ let mount_points = ["proc", "etc", "usr", "lib64", "lib", "bin"];
+ for mp in &mount_points {
+ let path = sandbox_root.join(mp);
+ if path.exists() {
+ let _ = umount2(&path, MntFlags::MNT_DETACH);
+ }
+ }
+ // Unmount device bind mounts
+ let dev_dir = sandbox_root.join("dev");
+ if dev_dir.exists() {
+ for dev in &["null", "zero", "urandom", "random"] {
+ let dev_path = dev_dir.join(dev);
+ if dev_path.exists() {
+ let _ = umount2(&dev_path, MntFlags::MNT_DETACH);
+ }
+ }
+ }
+ let _ = umount2(sandbox_root, MntFlags::MNT_DETACH);
+ let _ = fs::remove_dir_all(sandbox_root);
+}
diff --git a/src/state.rs b/src/state.rs
new file mode 100644
index 00000000..31bfd66f
--- /dev/null
+++ b/src/state.rs
@@ -0,0 +1,44 @@
+//! Shared application state and session types.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::time::Instant;
+use tokio::sync::RwLock;
+
+/// Session TTL in seconds (5 minutes)
+pub const SESSION_TTL_SECS: u64 = 300;
+
+/// A sandbox session with persistent environment and working directory.
+#[derive(Debug)]
+pub struct Session {
+ pub id: String,
+ pub sandbox_root: PathBuf,
+ pub env: HashMap<String, String>,
+ pub cwd: String,
+ pub created_at: Instant,
+ pub last_used: Instant,
+}
+
+/// Thread-safe session storage.
+pub type Sessions = Arc<RwLock<HashMap<String, Session>>>;
+
+/// Shared application state.
+#[derive(Clone)]
+pub struct AppState {
+ pub sessions: Sessions,
+}
+
+impl AppState {
+ pub fn new() -> Self {
+ Self {
+ sessions: Arc::new(RwLock::new(HashMap::new())),
+ }
+ }
+}
+
+impl Default for AppState {
+ fn default() -> Self {
+ Self::new()
+ }
+}