# SparkSandbox **Repository Path**: jiangbyte/SparkSandbox ## Basic Information - **Project Name**: SparkSandbox - **Description**: An HTTP service for isolated user-code execution - **Primary Language**: C++ - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-09-18 - **Last Updated**: 2026-09-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # SparkSandbox [English](README.md) | [中文](README.zh-CN.md) ![Version](https://img.shields.io/badge/version-0.1.1-blue) ![License](https://img.shields.io/badge/license-MIT-green) ![Platform](https://img.shields.io/badge/platform-Linux-lightgrey) ![C++](https://img.shields.io/badge/C%2B%2B-20-00599C?logo=cplusplus) ![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB?logo=python&logoColor=white) ![FastAPI](https://img.shields.io/badge/FastAPI-0.110%2B-009688?logo=fastapi&logoColor=white) An **HTTP service** for isolated user-code execution (not a public SDK): after you deploy it, callers use any language to send HTTP requests for compile/run, and implement HMAC verification themselves if needed. Responses include stdout, stderr, resource usage, and execution status; supports multi-case runs, checkers, interactive pipelines, a file store, and SSE. **No public client/SDK is provided**; Python modules and scripts in this repo are for development and testing only. | Layer | Implementation | Role | |-------|----------------|------| | Engine | C++20 `sparksandbox` (`src/`) | namespaces, cgroup, seccomp, fork/wait, status classification, interactive | | Orchestration | FastAPI `spark_sandbox` | HTTP, language table, worker pool, CompileCache, FileStore, multi-case parallelism | Runtime path: `routes` → `Orchestrator.run_limited` → `SandboxWorkerPool.borrow` → long-lived `sparksandbox worker` (NDJSON: `judge` / `interactive`). ## Execution status Aligned with `spark_sandbox.types.Status` / engine classification: | Value | Meaning | |-------|---------| | `succeeded` | Completed normally | | `compile_failed` | Compile failed | | `runtime_error` | Runtime error | | `time_limit_exceeded` | Timed out | | `memory_limit_exceeded` | Out of memory | | `output_limit_exceeded` | Output limit exceeded | | `security_violation` | Blocked by seccomp / security policy | | `internal_error` | Internal error | Process results also include `stage`: `none` / `compile` / `run`. ## Languages Commands, environment variables, and seccomp names live in [`configs/languages.yaml`](configs/languages.yaml); which languages are exposed is controlled by each service YAML’s `enabled_languages`. | Config | Enabled KEYs | |--------|--------------| | `default.yaml` / `dev.yaml` / code defaults | `c11` `cpp17` `python3` `java17` `go` `nodejs` | | `docker.yaml` (container default) | above + `rust` `sql_sqlite` | | Defined in YAML, not enabled by default | `sql_mysql` `sql_sqlserver` (need clients; inject connection params via request `variables`) | Seccomp names registered in the engine: `none`, `c_cpp`, `c_cpp_file_io`, `general`, `golang`, `node`, `sql_client` (`none` means no filter). ### Adding a language 1. Add an entry in `languages.yaml`; set `compile.seccomp` / `run.seccomp` to a registered name. 2. If that is not enough, register a new family under `src/seccomp/profiles/` and rebuild the engine (YAML may only reference registered names). 3. Add the KEY to the target config’s `enabled_languages`; install the toolchain on the host or base image. For remote SQL languages set `isolate_network: false`; pass connection params in the request body `variables`: `db_host` `db_port` `db_user` `db_password` `db_name`. ## Docker Two-layer images: toolchains in **base**; day-to-day code changes only rebuild **server**. Containers need `--privileged --cgroupns=host` (namespace + cgroup). ### Build base (language toolchains; usually once) ```bash bash scripts/build_base.sh # Default tag: spark-sandbox:base # Override tag: BASE_IMAGE=my/base:1 bash scripts/build_base.sh # Force-pull debian base layer: PULL=1 bash scripts/build_base.sh ``` ### Build server (engine + Python orchestration + configs) ```bash docker build --pull=false \ --build-arg BASE_IMAGE=spark-sandbox:base \ -f scripts/Dockerfile.server \ -t spark-sandbox:server . ``` ### Run a long-lived container ```bash docker rm -f spark-sandbox 2>/dev/null || true docker run -d --name spark-sandbox \ --privileged --cgroupns=host \ -p 8080:8080 \ spark-sandbox:server # Health check curl -fsS http://127.0.0.1:8080/v1/health ``` Image defaults: `SPARK_SANDBOX_BINARY=/usr/local/bin/sparksandbox`, `SPARK_SANDBOX_CONFIG=/app/configs/docker.yaml` (isolation on; languages include rust / sql_sqlite). Example with HMAC signing enabled: ```bash docker run -d --name spark-sandbox \ --privileged --cgroupns=host \ -p 8080:8080 \ -e SPARK_SANDBOX_SIGNING_ENABLED=1 \ -e SPARK_SANDBOX_SIGNING_SECRET='your-long-random-secret' \ spark-sandbox:server ``` ### One-shot e2e (build → ephemeral container → cleanup) From the repo root (needs local `.venv` and `pytest`): ```bash bash scripts/docker_e2e.sh ``` Sequence: build base if needed → build `spark-sandbox:server` → start a temporary container on `:18080` → run capability / security / all-language smoke / language bench / HTTP bench → write reports to `/tmp/spark-sandbox-e2e` → **remove the temporary container**. Common environment variables: | Variable | Default | Meaning | |----------|---------|---------| | `SKIP_BUILD=1` | `0` | Skip build; use existing `spark-sandbox:server` | | `BUILD_BASE=1` | `0` | Force rebuild base | | `HOST_PORT` | `18080` | Host port mapping | | `IMAGE` | `spark-sandbox:server` | Server image name | | `BASE_IMAGE` | `spark-sandbox:base` | Base image name | | `REPORT_DIR` | `/tmp/spark-sandbox-e2e` | Report directory | Example: image already built, tests only: ```bash SKIP_BUILD=1 bash scripts/docker_e2e.sh ``` ### Test against an already running service When the service is at `http://127.0.0.1:8080` (or e2e’s `18080`): ```bash export PYTHONPATH=. export SPARK_SANDBOX_BASE_URL=http://127.0.0.1:8080 # If the container has signing enabled: # export SPARK_SANDBOX_SIGNING_SECRET='your-long-random-secret' .venv/bin/python -m pytest tests/test_capability_suite.py -v .venv/bin/python -m pytest tests/test_security_boundaries.py -v .venv/bin/python scripts/smoke_languages.py .venv/bin/python scripts/bench_languages.py --count 24 --concurrency 4 --out /tmp/bench_langs.json .venv/bin/python scripts/bench_http.py --count 40 --concurrency 8 --out /tmp/bench.json ``` ## Local development Requirements: Linux (WSL recommended) + `g++` (C++20) + `libseccomp` + `pkg-config` + Python 3.10+. ```bash make python3 -m venv .venv && .venv/bin/pip install -r requirements.txt export SPARK_SANDBOX_BINARY=./build/sparksandbox export SPARK_SANDBOX_CONFIG=configs/dev.yaml export PYTHONPATH=. .venv/bin/python -m spark_sandbox --host 127.0.0.1 --port 8080 ``` Or `make run` (defaults to `configs/dev.yaml`). `dev.yaml` disables `isolation.enable_namespaces` and `cgroup.enabled` for unprivileged development; the engine can still install seccomp per language. You can also force-disable isolation with `SPARK_SANDBOX_DISABLE_ISOLATION=1`. ## API Full request/response/config docs: **[`docs/api.md`](docs/api.md)** (Limits, `result_policy`, multipart, file store, SSE, exec). Quick reference below. Convention: **GET / POST only** (delete via `POST /v1/files/delete`). ### Request signing (optional, toggleable) Controlled by config; unrelated to static tokens / Bearer: | Config / env | Default | Meaning | |--------------|---------|---------| | `signing_enabled` / `SPARK_SANDBOX_SIGNING_ENABLED` | `false` | Require signing | | `signing_secret` / `SPARK_SANDBOX_SIGNING_SECRET` | `""` | HMAC secret; **required when enabled**, otherwise the process refuses to start | | `auth_skew_seconds` / `SPARK_SANDBOX_AUTH_SKEW_SECONDS` | `300` | Allowed clock skew for `X-Spark-Timestamp` (seconds) | | `signing_enabled` | Behavior | |-------------------|----------| | `false` | **No route verifies signatures** (even if `signing_secret` is set) | | `true` | Routes marked “must sign” below require valid signature headers or **401**; public routes remain unsigned | #### When enabled: which requests must be signed **Must sign** (missing headers / bad signature / timestamp out of window / nonce replay → 401): | Method | Path | Description | |--------|------|-------------| | POST | `/v1/run` | Single compile/run | | POST | `/v1/run/stream` | SSE streaming run | | POST | `/v1/run_cases` | Multi-case | | POST | `/v1/run_cases/batch` | Batched multi-case | | POST | `/v1/run_pipeline` | checker / interactive | | POST | `/v1/exec` | Low-level command sequence | | GET | `/v1/files` | File-store list (GET also signs) | | POST | `/v1/files` | Single file upload | | POST | `/v1/files/batch` | Batch upload | | POST | `/v1/files/bundle` | Case-bundle upload | | GET | `/v1/files/{file_id}` | Download | | POST | `/v1/files/delete` | Delete | **Public (no signing required)** even when signing is on: | Method | Path | Description | |--------|------|-------------| | GET | `/` | Service name / docs entry | | GET | `/v1/health` | Health and pool stats | | GET | `/v1/version` | Version | | GET | `/v1/languages` | Enabled languages | | GET | `/v1/metrics` | Prometheus (`enable_metrics=false` → 404) | Protected routes use `Depends(verify_auth)`; public routes do not. #### Signature headers and algorithm Every **must-sign** request needs: | Header | Meaning | |--------|---------| | `X-Spark-Timestamp` | Unix seconds (UTC); must be within `auth_skew_seconds` | | `X-Spark-Nonce` | One-time random string (UUID recommended); same nonce cannot be reused within TTL | | `X-Spark-Signature` | `hex(HMAC-SHA256(signing_secret, canonical))` (lowercase hex) | **Canonical string** (two lines, one `\n` between): ``` {timestamp} {nonce} ``` `timestamp` / `nonce` must match the header strings exactly. Signing proves possession of the secret plus freshness/anti-replay; it does **not** bind METHOD, PATH, or body—request-body integrity is up to the transport or your application. `Authorization` and similar headers do **not** participate in or replace signing; Bearer alone still yields 401. #### Call examples Callers construct HTTP and signing themselves (reference only; not an official SDK). When `signing_enabled=false`, no signature headers: ```bash curl -s http://127.0.0.1:8080/v1/run -H 'Content-Type: application/json' \ -d '{"language":"python3","code":"print(input())","stdin":"hi"}' ``` When `signing_enabled=true`, sign yourself: ```python import hmac import hashlib import json import time import uuid import httpx secret = "your-secret" body = json.dumps({"language": "python3", "code": "print(1)"}).encode() ts = str(int(time.time())) nonce = uuid.uuid4().hex canonical = f"{ts}\n{nonce}" sig = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256).hexdigest() headers = { "Content-Type": "application/json", "X-Spark-Timestamp": ts, "X-Spark-Nonce": nonce, "X-Spark-Signature": sig, } httpx.post("http://127.0.0.1:8080/v1/run", content=body, headers=headers) ``` ### Outbound heartbeat (optional) The sandbox can **actively** POST to a caller URL on an interval (not an inbound `/v1/heartbeat`). Off by default. | Config / env | Default | Meaning | |--------------|---------|---------| | `heartbeat_enabled` / `SPARK_SANDBOX_HEARTBEAT_ENABLED` | `false` | Master switch | | `heartbeat_url` / `SPARK_SANDBOX_HEARTBEAT_URL` | `""` | Full URL that receives heartbeats | | `heartbeat_interval_seconds` / `SPARK_SANDBOX_HEARTBEAT_INTERVAL_SECONDS` | `30` | Interval (seconds, minimum 5) | When enabled, both a non-empty `heartbeat_url` and `signing_secret` are required or the process refuses to start. Heartbeats are **always signed** (three `X-Spark-*` headers) and the **body is always AES-256-GCM encrypted** (key derived from the same `signing_secret`), independent of inbound `signing_enabled`. Failures are logged only and do not take down the main service. On the wire the body is only a ciphertext envelope (no plaintext node/resource fields): ```json { "v": 1, "alg": "A256GCM", "iv": "", "ciphertext": "" } ``` **Decrypt (receiver)** 1. (Recommended) Verify the three `X-Spark-*` headers (same algorithm as inbound signing). 2. AES key: `SHA256("spark-sandbox-heartbeat-aes256-v1" || 0x00 || utf8(signing_secret))` (32 bytes). 3. AAD = `utf8(X-Spark-Timestamp)` (must match the header exactly). 4. Decrypt with `AES-256-GCM` using `iv` + `ciphertext` to get UTF-8 JSON plaintext. Example plaintext fields (after decrypt; identical to pre-encrypt): ```json { "service": "SparkSandbox", "version": "0.1.1", "status": "ok", "started_at": 1710000000.0, "sent_at": 1710000030.0, "uptime_seconds": 30.0, "node": { "hostname": "sandbox-1", "pid": 1, "platform": "Linux", "platform_release": "6.1.0", "arch": "x86_64", "python": "3.11.2", "ips": ["172.17.0.2"], "primary_ip": "172.17.0.2" }, "listen": { "host": "0.0.0.0", "port": 8080 }, "capacity": { "max_concurrency": 8, "worker_pool_size": 4 }, "resources": { "cpu_count": 4, "load_avg_1m": 0.12, "load_avg_5m": 0.08, "load_avg_15m": 0.05, "memory_total_bytes": 8589934592, "memory_available_bytes": 4294967296, "memory_used_bytes": 4294967296, "memory_used_percent": 50.0, "process_rss_bytes": 67108864, "process_vms_bytes": 268435456 }, "pool": { "pool_size": 4, "available_count": 4, "total_count": 4, "active_count": 0, "borrow_count": 0, "borrow_avg_wait_ms": 0, "borrow_last_wait_ms": 0, "borrow_max_wait_ms": 0, "waiting_count": 0, "emergency_count": 0, "queue_timeout_count": 0, "replaced_count": 0 }, "compile_cache": { "enabled": true, "entries": 0, "total_bytes": 0, "hits": 0, "misses": 0 }, "languages": { "keys": ["c11", "cpp17", "python3", "java17", "go", "nodejs", "rust", "sql_sqlite"], "languages": [ { "id": "python3", "label": "Python 3", "source_filename": "main.py" } ] } } ``` Encryption wraps one envelope only and **does not drop fields**; `pool` / `compile_cache` match `GET /v1/health`; `languages` matches `GET /v1/languages`. Without the key you cannot read plaintext. Python decrypt reference (not an SDK): ```python import base64, hashlib, json from cryptography.hazmat.primitives.ciphers.aead import AESGCM def decrypt_heartbeat(secret: str, envelope: dict, timestamp_header: str) -> dict: key = hashlib.sha256(b"spark-sandbox-heartbeat-aes256-v1\0" + secret.encode()).digest() iv = base64.b64decode(envelope["iv"]) ct = base64.b64decode(envelope["ciphertext"]) pt = AESGCM(key).decrypt(iv, ct, timestamp_header.encode()) return json.loads(pt) ``` ### Endpoint overview The “Sign” column applies only when `signing_enabled=true`. | Method | Path | Sign | Purpose | |--------|------|------|---------| | GET | `/v1/health` | No | Health; includes `pool`, `compile_cache` stats | | GET | `/v1/version` | No | `name` + `version` | | GET | `/v1/languages` | No | `keys` + public metadata | | GET | `/v1/metrics` | No | Prometheus text (`enable_metrics=false` → 404) | | POST | `/v1/run` | **Yes** | Single compile/run (field `code`) | | POST | `/v1/run/stream` | **Yes** | SSE stream (see below) | | POST | `/v1/run_cases` | **Yes** | Multi-case (field `source`; optional `checker`) | | POST | `/v1/run_cases/batch` | **Yes** | Bounded parallelism over `submissions[]` | | POST | `/v1/run_pipeline` | **Yes** | `mode=checker` \| `interactive` | | POST | `/v1/exec` | **Yes** | Run multiple commands in order | | GET | `/v1/files` | **Yes** | File-store metadata list | | POST | `/v1/files` | **Yes** | Single upload | | POST | `/v1/files/batch` | **Yes** | Batch upload | | POST | `/v1/files/bundle` | **Yes** | Case-bundle zip/tar → unpack into store | | GET | `/v1/files/{file_id}` | **Yes** | Download | | POST | `/v1/files/delete` | **Yes** | Delete (body: `file_id`) | Most execution endpoints accept JSON or **multipart** (form field `payload` = JSON + file fields); signing does not bind the body. ### `/v1/run` Main request fields: `language` `code` `stdin` `files` `fetch_files` `limits` `compile_limits` `result_policy` `output_mode` `max_stdout_bytes` `max_stderr_bytes` `session_id` `variables`. Response includes `status`, `compile` / `run` (`ProcessResult`), stdout/stderr (or `*_file_id` / `*_preview`), `feedback`, `session_id`. ### `/v1/run/stream` (SSE) Event names (`event:`): `compile_start` → `compile_done` → during run `stdout` / `stderr` → `metrics` → `done`; failures may be `error`. Shares the admission Semaphore with `/run`. ### Multi-case / pipeline - Case fields: `stdin` `stdin_file_id` `input_file_id` `answer_file_id` `files`; or `case_bundle_file_id` - `result_policy`: `auto` \| `inline` \| `file_id` \| `summary` (large output can go to FileStore; response paths are sanitized) - `checker` / `interactor`: compile and run per spec; return process results and raw `exit_code` - `interactive`: engine bidirectional pipes; both sides’ results returned together ```bash curl -s http://127.0.0.1:8080/v1/run -H 'Content-Type: application/json' \ -d '{"language":"python3","code":"print(input())","stdin":"hi"}' ``` ## Configuration | File | Purpose | |------|---------| | [`configs/default.yaml`](configs/default.yaml) | Full defaults (richest comments; isolation off) | | [`configs/dev.yaml`](configs/dev.yaml) | Local / WSL (namespaces / cgroup off) | | [`configs/docker.yaml`](configs/docker.yaml) | Container (isolation on; enables rust / sql_sqlite) | | [`configs/languages.yaml`](configs/languages.yaml) | Language compile/run commands and seccomp | Environment variables (see `spark_sandbox/config.py`; override YAML): | Variable | Meaning | |----------|---------| | `SPARK_SANDBOX_CONFIG` | Service YAML path | | `SPARK_SANDBOX_BINARY` | Engine binary | | `SPARK_SANDBOX_HOST` / `SPARK_SANDBOX_PORT` | Listen address | | `SPARK_SANDBOX_SIGNING_ENABLED` | Force HMAC signing | | `SPARK_SANDBOX_SIGNING_SECRET` | HMAC secret | | `SPARK_SANDBOX_AUTH_SKEW_SECONDS` | Signature timestamp skew (seconds) | | `SPARK_SANDBOX_HEARTBEAT_ENABLED` | Outbound heartbeat reporting | | `SPARK_SANDBOX_HEARTBEAT_URL` | Heartbeat receive URL | | `SPARK_SANDBOX_HEARTBEAT_INTERVAL_SECONDS` | Heartbeat interval (seconds, min 5) | | `SPARK_SANDBOX_DISABLE_ISOLATION` | `1` disables namespaces + cgroup | | `SPARK_SANDBOX_MAX_CONCURRENCY` | HTTP admission concurrency | | `SPARK_SANDBOX_WORKER_POOL_SIZE` | Long-lived worker count | | `SPARK_SANDBOX_CASE_PARALLELISM` | Per-request multi-case parallelism cap | | `SPARK_SANDBOX_BATCH_PARALLELISM` | Batch submission parallelism | | `SPARK_SANDBOX_ALLOW_EMERGENCY_WORKER` | Spawn temporary worker when pool is exhausted | | `SPARK_SANDBOX_MAX_QUEUE_WAIT_SECONDS` | Hard timeout waiting to borrow a worker | | `SPARK_SANDBOX_ENABLE_METRICS` | Expose `/v1/metrics` | ## Testing ```bash export SPARK_SANDBOX_BINARY=./build/sparksandbox PYTHONPATH=. .venv/bin/python -m pytest tests/ -q # Multi-language / files / concurrency PYTHONPATH=. .venv/bin/python -m pytest tests/test_capability_suite.py -v # TLE/OLE, path traversal, fork/network/disk writes, etc. PYTHONPATH=. .venv/bin/python -m pytest tests/test_security_boundaries.py -v # Against a running service SPARK_SANDBOX_BASE_URL=http://127.0.0.1:8080 PYTHONPATH=. \ .venv/bin/python scripts/smoke_languages.py SPARK_SANDBOX_BASE_URL=http://127.0.0.1:8080 PYTHONPATH=. \ .venv/bin/python scripts/bench_languages.py --out /tmp/bench_langs.json PYTHONPATH=. .venv/bin/python scripts/bench_http.py \ --base-url http://127.0.0.1:8080 --out /tmp/bench.json ``` `make test`: build engine + unit tests + smoke + HTTP integration. ## Layout ``` configs/ Service and language YAML include/ src/ C++ engine, seccomp profiles spark_sandbox/ HTTP orchestration (dev/test helpers are not a public SDK) scripts/ Dockerfile.base|server, e2e, smoke, bench tests/ pytest plus capability / security suites docs/api.md Full HTTP API docs (request / response / config) ``` ## License MIT