An open-source, faster Devin alternative
TypeScript
Merge origin/main: secrets proxy, template golden, docs
Brian Reardonb1868f43f260
diff --cc .claude/skills/openqemu/SKILL.mdindex 00000000,00000000..03bf4299new file mode 100644--- /dev/null+++ b/.claude/skills/openqemu/SKILL.md@@@ -1,0 -1,0 +1,177 @@@++---++name: openqemu++description: Create and interact with OpenSandbox QEMU sandboxes — create, exec, read/write files, list, destroy, hibernate/wake, checkpoint/fork, scale resources++disable-model-invocation: false++user-invocable: true++allowed-tools: Bash, Read, Write++---++++# OpenSandbox Skill++++You have access to OpenSandbox, a cloud sandbox environment running QEMU VMs. Use it to run code, test commands, and manipulate files in isolated Linux environments.++++## Configuration++++```++API_URL=http://3.148.184.81:8080++API_KEY=test-dev-key++```++++All requests require `-H 'X-API-Key: test-dev-key'` and `-H 'Content-Type: application/json'`.++++## Available Operations++++### Create a sandbox++```bash++curl -s -X POST $API_URL/api/sandboxes \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"timeout":3600}'++```++Returns JSON with `sandboxID`, `status`, `token`.++++### Run a command (fire-and-forget, returns stdout/stderr)++```bash++curl -s -X POST $API_URL/api/sandboxes/{SANDBOX_ID}/exec/run \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"cmd":"python3","args":["-c","print(1+1)"],"timeout":30}'++```++Returns JSON with `exitCode`, `stdout`, `stderr`. This is the simplest way to run commands.++++### Create an exec session (long-lived, for streaming)++```bash++curl -s -X POST $API_URL/api/sandboxes/{SANDBOX_ID}/exec \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"cmd":"bash","args":["-c","echo hello"]}'++```++++### Read a file++```bash++curl -s $API_URL/api/sandboxes/{SANDBOX_ID}/files?path=/etc/os-release \++ -H 'X-API-Key: test-dev-key'++```++++### Write a file++```bash++curl -s -X PUT "$API_URL/api/sandboxes/{SANDBOX_ID}/files?path=/tmp/test.py" \++ -H 'X-API-Key: test-dev-key' \++ -H 'Content-Type: application/octet-stream' \++ --data-binary 'print("hello world")'++```++++### List directory++```bash++curl -s "$API_URL/api/sandboxes/{SANDBOX_ID}/files/list?path=/workspace" \++ -H 'X-API-Key: test-dev-key'++```++++### List sandboxes++```bash++curl -s $API_URL/api/sandboxes \++ -H 'X-API-Key: test-dev-key'++```++++### Destroy a sandbox++```bash++curl -s -X DELETE $API_URL/api/sandboxes/{SANDBOX_ID} \++ -H 'X-API-Key: test-dev-key'++```++++### Hibernate / Wake++```bash++# Hibernate (saves state to S3, stops billing)++curl -s -X POST $API_URL/api/sandboxes/{SANDBOX_ID}/hibernate \++ -H 'X-API-Key: test-dev-key'++++# Wake (golden restore ~520ms, workspace + rootfs preserved)++curl -s -X POST $API_URL/api/sandboxes/{SANDBOX_ID}/wake \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"timeout":300}'++```++++### Checkpoint / Fork++```bash++# Create checkpoint (savevm snapshot inside qcow2)++curl -s -X POST $API_URL/api/sandboxes/{SANDBOX_ID}/checkpoints \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"name":"my-checkpoint"}'++# Returns JSON with `id`, `status` (processing → ready)++++# Fork a new sandbox from a checkpoint++curl -s -X POST $API_URL/api/sandboxes/from-checkpoint/{CHECKPOINT_ID} \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"timeout":3600}'++# Returns JSON with `sandboxID` (status: creating → running)++```++++### Resource Scaling++++Scale sandbox resources at runtime. Memory hotplug adds real RAM to the VM (not just cgroup limits).++Pricing model: 1 vCPU per 1GB RAM (linear scaling). Setting memoryMB auto-calculates CPU.++++#### External API (from your client/SDK)++```bash++# Scale up to 2GB RAM + 2 vCPUs++curl -s -X PUT $API_URL/api/sandboxes/{SANDBOX_ID}/limits \++ -H 'Content-Type: application/json' \++ -H 'X-API-Key: test-dev-key' \++ -d '{"maxMemoryMB": 2048, "cpuPercent": 200, "maxPids": 256}'++```++++#### Internal API (from inside the sandbox — 169.254.169.254)++```bash++# From inside the sandbox:++curl -s http://169.254.169.254/v1/status++# → {"sandboxId":"sb-xxx","uptime":42.5}++++curl -s http://169.254.169.254/v1/limits++# → {"cpuPercent":100,"memUsage":52428800,"memLimit":907051008,"pids":3}++++curl -s -X POST http://169.254.169.254/v1/scale -d '{"memoryMB": 4096}'++# → {"ok":true,"memoryMB":4096,"cpuPercent":400,"maxPids":0}++# Auto-calculates: 4GB RAM → 400% CPU (4 vCPUs)++++curl -s http://169.254.169.254/v1/metadata++# → {"region":"use2","template":"default"}++```++++#### Default cgroup limits++- `pids.max = 128` (prevents fork bombs)++- `memory.max = 90% of VM RAM`++- `cpu.max = 80% of vCPUs` (reserves 20% for agent)++- Fork bomb protection: cgroup kill on exec timeout++++## Architecture++++- **Agent communication**: virtio-serial (survives QEMU migration, enables sub-second wake)++- **Storage**: rootfs qcow2 (COW overlay on base image) + workspace qcow2 (separate /workspace drive)++- **Persistence**: rootfs installs (apt/pip) AND /workspace files survive hibernate/wake. Only /tmp (tmpfs) is lost.++- **Resource isolation**: cgroup v2 inside guest — agent (PID 1) in root cgroup, user processes in /sandbox cgroup++- **Fork bomb protection**: pids.max + cpu.max + cgroup kill on exec timeout++++## Workflow++++When the user asks you to use a sandbox, or asks $ARGUMENTS:++++1. **Create a sandbox** if one isn't already active in this conversation. Save the `sandboxID`. Always use `"timeout":3600` (1 hour idle timeout).++2. **Use `exec/run`** for commands that produce output — it returns stdout/stderr directly.++3. **Use `files` API** for reading/writing files in the sandbox.++4. **Clean up** — destroy the sandbox when done, or let it time out (1 hour of inactivity).++++## Tips++++- Sandbox VMs run Ubuntu with python3, git, curl, jq, and standard Linux tools.++- Default timeout is 300s (5 min). Pass `"timeout":3600` for longer sessions.++- The `exec/run` endpoint is synchronous — it waits for the command to finish and returns the result. Use this for most operations.++- For exec/run, the JSON field for the command binary is `cmd` (not `command`), and arguments go in `args`.++- Environment variables can be passed as `"envs":{"KEY":"VALUE"}`.++- Working directory can be set with `"cwd":"/path"`.++- **Background processes**: Use `setsid cmd </dev/null >/dev/null 2>&1 &` in one exec, then interact in a separate exec.++- **Persistence**: `/workspace/` and rootfs changes (apt install, pip install) survive hibernate/wake. `/tmp/` does not (tmpfs).++- **Checkpoints**: Use `POST /checkpoints` to snapshot, then `POST /from-checkpoint/{id}` to fork. Wait for fork status to become "running" before executing commands.++- **Pricing model**: 1 vCPU per 1GB RAM (linear scaling, 256MB–16GB). Per-second billing. Hibernated VMs are free.diff --cc cmd/server/main.goindex ddad1641,920aa4de..a3b03752--- a/cmd/server/main.go+++ b/cmd/server/main.go@@@ -16,7 -16,9 +16,8 @@@ import"github.com/opensandbox/opensandbox/internal/compute""github.com/opensandbox/opensandbox/internal/config""github.com/opensandbox/opensandbox/internal/controlplane"+ "github.com/opensandbox/opensandbox/internal/crypto""github.com/opensandbox/opensandbox/internal/db"- "github.com/opensandbox/opensandbox/internal/ecr""github.com/opensandbox/opensandbox/internal/proxy""github.com/opensandbox/opensandbox/internal/sandbox""github.com/opensandbox/opensandbox/internal/storage"diff --cc cmd/worker/main.goindex c0ac7dc3,881427fa..8bd41b14--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@@ -14,15 -14,17 +14,15 @@@ import"github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/config""github.com/opensandbox/opensandbox/internal/db"-- fc "github.com/opensandbox/opensandbox/internal/firecracker"- qm "github.com/opensandbox/opensandbox/internal/qemu"- agentpb "github.com/opensandbox/opensandbox/proto/agent""github.com/opensandbox/opensandbox/internal/metrics"- "github.com/opensandbox/opensandbox/internal/podman""github.com/opensandbox/opensandbox/internal/proxy"++ qm "github.com/opensandbox/opensandbox/internal/qemu""github.com/opensandbox/opensandbox/internal/sandbox"+ "github.com/opensandbox/opensandbox/internal/secretsproxy""github.com/opensandbox/opensandbox/internal/storage"- "github.com/opensandbox/opensandbox/internal/template""github.com/opensandbox/opensandbox/internal/worker""github.com/opensandbox/opensandbox/pkg/types"+ agentpb "github.com/opensandbox/opensandbox/proto/agent")func main() {@@@ -35,195 -37,199 +35,129 @@@ctx := context.Background()- // Initialize Firecracker-based sandbox manager- fcCfg := fc.Config{- DataDir: cfg.DataDir,- KernelPath: cfg.KernelPath,- ImagesDir: cfg.ImagesDir,- FirecrackerBin: cfg.FirecrackerBin,- DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,- DefaultCPUs: cfg.DefaultSandboxCPUs,- DefaultDiskMB: cfg.DefaultSandboxDiskMB,- }+ var mgr sandbox.Manager- fcMgr, err := fc.NewManager(fcCfg)- if err != nil {- log.Fatalf("failed to initialize Firecracker manager: %v", err)- }- defer fcMgr.Close()- log.Println("opensandbox-worker: Firecracker VM manager initialized")+ // Backend-specific exec session factory+ var execSessionFactory func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error)+ // Backend-specific PTY session factory+ var ptySessionFactory func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error)+ // Backend-specific autosaver syncer+ var autosaverSyncer worker.SyncFSer+ // Backend-specific graceful shutdown+ var doGracefulShutdown func(checkpointStore *storage.CheckpointStore, store *db.Store)- switch cfg.VMBackend {- case "firecracker":- fcCfg := fc.Config{- DataDir: cfg.DataDir,- KernelPath: cfg.KernelPath,- ImagesDir: cfg.ImagesDir,- FirecrackerBin: cfg.FirecrackerBin,- DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,- DefaultCPUs: cfg.DefaultSandboxCPUs,- DefaultDiskMB: cfg.DefaultSandboxDiskMB,- }-- fcMgr, err := fc.NewManager(fcCfg)+ // Initialize secrets proxy for MITM token substitution.+ // Runs on :3128 — VMs route HTTPS through this to keep real secrets off-VM.+ secretsCA, err := secretsproxy.LoadOrCreateCA(filepath.Join(cfg.DataDir, "proxy-ca"))+ if err != nil {+ log.Printf("opensandbox-worker: secrets proxy CA failed: %v (secrets proxy disabled)", err)+ }+ var secretsProxy *secretsproxy.SecretsProxy+ if secretsCA != nil {+ secretsProxy, err = secretsproxy.NewSecretsProxy(secretsCA, "0.0.0.0:3128")if err != nil {- log.Fatalf("failed to initialize Firecracker manager: %v", err)- }- defer fcMgr.Close()- log.Println("opensandbox-worker: Firecracker VM manager initialized")-- fcMgr.CleanupOrphanedProcesses()-- go func() {- if err := fcMgr.PrepareGoldenSnapshot(); err != nil {- log.Printf("opensandbox-worker: golden snapshot preparation failed: %v (cold boot fallback active)", err)- }- }()-- mgr = fcMgr- autosaverSyncer = fcMgr-- execSessionFactory = func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)- if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)- }- return createExecSession(agent, sandboxID, req)- }-- ptySessionFactory = func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)- if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)- }- vsockPath, err := fcMgr.GetVsockPath(sandboxID)- if err != nil {- return nil, fmt.Errorf("get vsock path for %s: %w", sandboxID, err)- }- return createPTYSessionFC(agent, vsockPath, sandboxID, req)- }-- doGracefulShutdown = func(checkpointStore *storage.CheckpointStore, store *db.Store) {- if checkpointStore == nil {- return- }- vms, _ := mgr.List(context.Background())- if len(vms) == 0 {- return- }- log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))- shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- results := fcMgr.HibernateAll(shutCtx, checkpointStore)- cancel()- processHibernateResults(results, store, func(r interface{}) (string, string, error) {- hr := r.(fc.HibernateAllResult)- return hr.SandboxID, hr.HibernationKey, hr.Err- })- log.Println("opensandbox-worker: waiting for S3 uploads...")- fcMgr.WaitUploads(3 * time.Minute)- log.Println("opensandbox-worker: graceful shutdown complete")- }-- // Local recovery for Firecracker- defer func() {- // Recovery is done below after DB connection- }()-- // Wire up local recovery- if dbURL := getDBURL(cfg); dbURL != "" {- if store, err := db.NewStore(ctx, dbURL); err == nil {- defer store.Close()- recoverLocalFC(ctx, fcMgr, store, cfg)- }+ log.Printf("opensandbox-worker: secrets proxy listen failed: %v", err)+ } else {+ secretsProxy.Start()+ defer secretsProxy.Stop()+ log.Println("opensandbox-worker: secrets proxy started on :3128")- // Wire secrets proxy into VM lifecycle- fcMgr.SetSecretsProxy(secretsProxy)}+ }-- // Clean up orphaned Firecracker processes + TAP devices BEFORE starting golden snapshot.- // Must run first to avoid killing the golden snapshot VM (race condition).- fcMgr.CleanupOrphanedProcesses()-- // Prepare golden snapshot for fast default VM creation (~500ms vs ~2s cold boot)- go func() {- if err := fcMgr.PrepareGoldenSnapshot(); err != nil {- log.Printf("opensandbox-worker: golden snapshot preparation failed: %v (cold boot fallback active)", err)++ _ = secretsProxy // TODO: wire into QEMU manager lifecycle+- case "qemu":++ // QEMU backend++ {+ qmCfg := qm.Config{+ DataDir: cfg.DataDir,+ KernelPath: cfg.KernelPath,+ ImagesDir: cfg.ImagesDir,+ QEMUBin: cfg.QEMUBin,+ DefaultMemoryMB: cfg.DefaultSandboxMemoryMB,+ DefaultCPUs: cfg.DefaultSandboxCPUs,+ DefaultDiskMB: cfg.DefaultSandboxDiskMB,}- }()- // The Firecracker manager implements sandbox.Manager- var mgr sandbox.Manager = fcMgr-- // Initialize PTY manager using Firecracker agent gRPC- // Initialize exec session manager using Firecracker agent gRPC- execMgr := sandbox.NewAgentExecSessionManager(func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)+ qmMgr, err := qm.NewManager(qmCfg)if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)+ log.Fatalf("failed to initialize QEMU manager: %v", err)}+ defer qmMgr.Close()+ log.Println("opensandbox-worker: QEMU VM manager initialized")- agentPB := &agentpb.ExecSessionCreateRequest{- Command: req.Command,- Args: req.Args,- Envs: req.Env,- Cwd: req.Cwd,- TimeoutSeconds: int32(req.Timeout),- MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),- }+ qmMgr.CleanupOrphanedProcesses()- sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)- if err != nil {- return nil, fmt.Errorf("create exec session in VM: %w", err)+ // Prepare golden snapshot for fast VM creation+ if err := qmMgr.PrepareGoldenSnapshot(); err != nil {+ log.Printf("opensandbox-worker: WARNING: golden snapshot failed, using cold boot: %v", err)}- scrollback := sandbox.NewScrollbackBuffer(0)- done := make(chan struct{})-- // Create a pipe for stdin: writes to stdinW are forwarded to the gRPC stream- stdinR, stdinW := io.Pipe()-- handle := &sandbox.ExecSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- Command: req.Command,- Args: req.Args,- Running: true,- StartedAt: time.Now(),- Done: done,- Scrollback: scrollback,- StdinWriter: stdinW,- OnKill: func(signal int) error {- stdinW.Close()- return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))- },- }+ mgr = qmMgr+ autosaverSyncer = qmMgr- // Attach to the session to pipe output into the host-side scrollback- go func() {- defer close(done)- defer stdinR.Close()- stream, err := agent.ExecSessionAttach(context.Background())+ // Start metadata server (169.254.169.254 equivalent, served on :8888)+ metadataSrv := worker.NewMetadataServer(qmMgr, cfg.Region)+ metadataSrv.Start(":8888")+ defer metadataSrv.Close()+ qmMgr.SetMetadataCallbacks(metadataSrv.RegisterSandbox, metadataSrv.UnregisterSandbox)+ log.Println("opensandbox-worker: metadata server started on :8888")++ execSessionFactory = func(sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agent, err := qmMgr.GetAgent(sandboxID)if err != nil {- return+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)}- // Send first message with session_id- if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {- return- }-- // Forward stdin pipe to gRPC stream in a separate goroutine- go func() {- buf := make([]byte, 4096)- for {- n, err := stdinR.Read(buf)- if err != nil {- return- }- if n > 0 {- data := make([]byte, n)- copy(data, buf[:n])- if err := stream.Send(&agentpb.ExecSessionInput{Stdin: data}); err != nil {- return- }- }- }- }()+ return createExecSessionQEMU(agent, sandboxID, req)+ }- for {- msg, err := stream.Recv()- if err != nil {- return- }- switch msg.Type {- case agentpb.ExecSessionOutput_STDOUT:- scrollback.Write(1, msg.Data)- case agentpb.ExecSessionOutput_STDERR:- scrollback.Write(2, msg.Data)- case agentpb.ExecSessionOutput_EXIT:- exitCode := int(msg.ExitCode)- handle.ExitCode = &exitCode- handle.Running = false- return- case agentpb.ExecSessionOutput_SCROLLBACK_END:- // Transition from scrollback replay to live- }+ ptySessionFactory = func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ agent, err := qmMgr.GetAgent(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)}- }()-- return handle, nil- })- defer execMgr.CloseAll()-- // Initialize PTY manager using Firecracker agent gRPC- ptyMgr := sandbox.NewAgentPTYManager(func(sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {- agent, err := fcMgr.GetAgent(sandboxID)- if err != nil {- return nil, fmt.Errorf("get agent for %s: %w", sandboxID, err)- }- vsockPath, err := fcMgr.GetVsockPath(sandboxID)- if err != nil {- return nil, fmt.Errorf("get vsock path for %s: %w", sandboxID, err)+ guestCID, err := qmMgr.GetGuestCID(sandboxID)+ if err != nil {+ return nil, fmt.Errorf("get guest CID for %s: %w", sandboxID, err)+ }+ return createPTYSessionQEMU(agent, guestCID, sandboxID, req)}- cols := int32(req.Cols)- if cols <= 0 {- cols = 80- }- rows := int32(req.Rows)- if rows <= 0 {- rows = 24+ doGracefulShutdown = func(checkpointStore *storage.CheckpointStore, store *db.Store) {+ if checkpointStore == nil {+ return+ }+ vms, _ := mgr.List(context.Background())+ if len(vms) == 0 {+ return+ }+ log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))+ shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ results := qmMgr.HibernateAll(shutCtx, checkpointStore)+ cancel()+ processHibernateResults(results, store, func(r interface{}) (string, string, error) {+ hr := r.(qm.HibernateAllResult)+ return hr.SandboxID, hr.HibernationKey, hr.Err+ })+ log.Println("opensandbox-worker: waiting for S3 uploads...")+ qmMgr.WaitUploads(3 * time.Minute)+ log.Println("opensandbox-worker: graceful shutdown complete")}- sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)- if err != nil {- return nil, fmt.Errorf("create PTY in VM: %w", err)+ // Wire up local recovery+ if dbURL := getDBURL(cfg); dbURL != "" {+ if store, err := db.NewStore(ctx, dbURL); err == nil {+ defer store.Close()+ recoverLocalQEMU(ctx, qmMgr, store, cfg)+ }}- default:- log.Fatalf("unknown VM backend %q (expected 'firecracker' or 'qemu')", cfg.VMBackend)- // Connect to the PTY data stream via vsock- conn, err := agent.ConnectPTYData(vsockPath, dataPort)- if err != nil {- _ = agent.PTYKill(context.Background(), sessionID)- return nil, fmt.Errorf("connect PTY data: %w", err)- }+ }- done := make(chan struct{})+ // Initialize exec session manager+ execMgr := sandbox.NewAgentExecSessionManager(execSessionFactory)+ defer execMgr.CloseAll()- return &sandbox.PTYSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- PTY: conn,- Done: done,- }, nil- })+ // Initialize PTY manager+ ptyMgr := sandbox.NewAgentPTYManager(ptySessionFactory)defer ptyMgr.CloseAll()// Initialize per-sandbox SQLite manager@@@ -317,8 -358,23 +251,8 @@@defer metricsSrv.Close()log.Println("opensandbox-worker: metrics server started on :9091")- // gRPC server- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, store)- // Initialize template builder (Podman as build tool → ext4 images)- var builder *template.Builder- podmanClient, podmanErr := podman.NewClient()- if podmanErr != nil {- log.Printf("opensandbox-worker: podman not available: %v (template building disabled)", podmanErr)- } else {- imagesDir := fcCfg.ImagesDir- agentPath := filepath.Join(filepath.Dir(os.Args[0]), "osb-agent")- if _, err := os.Stat(agentPath); err != nil {- agentPath = "/usr/local/bin/osb-agent"- }- builder = template.NewBuilder(podmanClient, imagesDir, agentPath)- log.Printf("opensandbox-worker: template builder configured (images=%s, agent=%s)", imagesDir, agentPath)- }-- // Start gRPC server for control plane communication- grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, builder, store)++ // gRPC server (nil builder — template building via podman not needed for QEMU)++ grpcServer := worker.NewGRPCServer(mgr, ptyMgr, execMgr, sandboxDBMgr, checkpointStore, sbRouter, nil, store)grpcAddr := ":9090"log.Printf("opensandbox-worker: starting gRPC server on %s", grpcAddr)go func() {@@@ -436,332 -458,42 +370,197 @@@log.Printf("error closing HTTP server: %v", err)}- // Stop autosaver before hibernatingautosaver.Stop()- // 2. Hibernate all running sandboxes for seamless resume- if checkpointStore != nil {- vms, _ := mgr.List(context.Background())- if len(vms) > 0 {- log.Printf("opensandbox-worker: hibernating %d sandboxes...", len(vms))- shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)- results := fcMgr.HibernateAll(shutCtx, checkpointStore)- cancel()+ doGracefulShutdown(checkpointStore, store)+}- for _, r := range results {- if r.Err != nil {- log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)- if store != nil {- errMsg := "hibernate failed on shutdown: " + r.Err.Error()- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)- }- continue- }- log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)+// getDBURL returns the database URL from config or environment.+func getDBURL(cfg *config.Config) string {+ if cfg.DatabaseURL != "" {+ return cfg.DatabaseURL+ }+ return os.Getenv("DATABASE_URL")+}+- // createExecSession creates an exec session using a Firecracker agent client.- func createExecSession(agent *fc.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {- agentPB := &agentpb.ExecSessionCreateRequest{- Command: req.Command,- Args: req.Args,- Envs: req.Env,- Cwd: req.Cwd,- TimeoutSeconds: int32(req.Timeout),- MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),- }-- sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)- if err != nil {- return nil, fmt.Errorf("create exec session in VM: %w", err)- }-- scrollback := sandbox.NewScrollbackBuffer(0)- done := make(chan struct{})- stdinR, stdinW := io.Pipe()-- handle := &sandbox.ExecSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- Command: req.Command,- Args: req.Args,- Running: true,- StartedAt: time.Now(),- Done: done,- Scrollback: scrollback,- StdinWriter: stdinW,- OnKill: func(signal int) error {- stdinW.Close()- return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))- },- }-- go runExecStream(agent, sessionID, stdinR, done, scrollback, handle)-- return handle, nil- }-+// createExecSessionQEMU creates an exec session using a QEMU agent client.+func createExecSessionQEMU(agent *qm.AgentClient, sandboxID string, req types.ExecSessionCreateRequest) (*sandbox.ExecSessionHandle, error) {+ agentPB := &agentpb.ExecSessionCreateRequest{+ Command: req.Command,+ Args: req.Args,+ Envs: req.Env,+ Cwd: req.Cwd,+ TimeoutSeconds: int32(req.Timeout),+ MaxRunAfterDisconnect: int32(req.MaxRunAfterDisconnect),+ }++ sessionID, err := agent.ExecSessionCreate(context.Background(), agentPB)+ if err != nil {+ return nil, fmt.Errorf("create exec session in VM: %w", err)+ }++ scrollback := sandbox.NewScrollbackBuffer(0)+ done := make(chan struct{})+ stdinR, stdinW := io.Pipe()++ handle := &sandbox.ExecSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ Command: req.Command,+ Args: req.Args,+ Running: true,+ StartedAt: time.Now(),+ Done: done,+ Scrollback: scrollback,+ StdinWriter: stdinW,+ OnKill: func(signal int) error {+ stdinW.Close()+ return agent.ExecSessionKill(context.Background(), sessionID, int32(signal))+ },+ }++ go runExecStreamQEMU(agent, sessionID, stdinR, done, scrollback, handle)++ return handle, nil+}+- // runExecStream attaches to an exec session stream (Firecracker backend).- func runExecStream(agent *fc.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {- defer close(done)- defer stdinR.Close()- stream, err := agent.ExecSessionAttach(context.Background())- if err != nil {- return- }- if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {- return- }- go forwardStdin(stdinR, stream)- consumeExecOutput(stream, scrollback, handle)- }-+// runExecStreamQEMU attaches to an exec session stream (QEMU backend).+func runExecStreamQEMU(agent *qm.AgentClient, sessionID string, stdinR *io.PipeReader, done chan struct{}, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+ defer close(done)+ defer stdinR.Close()+ stream, err := agent.ExecSessionAttach(context.Background())+ if err != nil {+ return+ }+ if err := stream.Send(&agentpb.ExecSessionInput{SessionId: sessionID}); err != nil {+ return+ }+ go forwardStdin(stdinR, stream)+ consumeExecOutput(stream, scrollback, handle)+}++// forwardStdin pipes stdin data to a gRPC stream.+func forwardStdin(stdinR *io.PipeReader, stream agentpb.SandboxAgent_ExecSessionAttachClient) {+ buf := make([]byte, 4096)+ for {+ n, err := stdinR.Read(buf)+ if err != nil {+ return+ }+ if n > 0 {+ data := make([]byte, n)+ copy(data, buf[:n])+ if err := stream.Send(&agentpb.ExecSessionInput{Stdin: data}); err != nil {+ return+ }+ }+ }+}++// consumeExecOutput reads output from a gRPC exec stream into a scrollback buffer.+func consumeExecOutput(stream agentpb.SandboxAgent_ExecSessionAttachClient, scrollback *sandbox.ScrollbackBuffer, handle *sandbox.ExecSessionHandle) {+ for {+ msg, err := stream.Recv()+ if err != nil {+ return+ }+ switch msg.Type {+ case agentpb.ExecSessionOutput_STDOUT:+ scrollback.Write(1, msg.Data)+ case agentpb.ExecSessionOutput_STDERR:+ scrollback.Write(2, msg.Data)+ case agentpb.ExecSessionOutput_EXIT:+ exitCode := int(msg.ExitCode)+ handle.ExitCode = &exitCode+ handle.Running = false+ return+ case agentpb.ExecSessionOutput_SCROLLBACK_END:+ // Transition from scrollback replay to live+ }+ }+}+- // createPTYSessionFC creates a PTY session using Firecracker's vsock UDS protocol.- func createPTYSessionFC(agent *fc.AgentClient, vsockPath, sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {- cols := int32(req.Cols)- if cols <= 0 {- cols = 80- }- rows := int32(req.Rows)- if rows <= 0 {- rows = 24- }-- sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)- if err != nil {- return nil, fmt.Errorf("create PTY in VM: %w", err)- }-- conn, err := agent.ConnectPTYData(vsockPath, dataPort)- if err != nil {- _ = agent.PTYKill(context.Background(), sessionID)- return nil, fmt.Errorf("connect PTY data: %w", err)- }-- done := make(chan struct{})- return &sandbox.PTYSessionHandle{- ID: sessionID,- SandboxID: sandboxID,- PTY: conn,- Done: done,- }, nil- }-+// createPTYSessionQEMU creates a PTY session using AF_VSOCK (QEMU backend).+func createPTYSessionQEMU(agent *qm.AgentClient, guestCID uint32, sandboxID string, req types.PTYCreateRequest) (*sandbox.PTYSessionHandle, error) {+ cols := int32(req.Cols)+ if cols <= 0 {+ cols = 80+ }+ rows := int32(req.Rows)+ if rows <= 0 {+ rows = 24+ }++ sessionID, dataPort, err := agent.PTYCreate(context.Background(), cols, rows, req.Shell)+ if err != nil {+ return nil, fmt.Errorf("create PTY in VM: %w", err)+ }++ conn, err := agent.ConnectPTYData(guestCID, dataPort)+ if err != nil {+ _ = agent.PTYKill(context.Background(), sessionID)+ return nil, fmt.Errorf("connect PTY data: %w", err)+ }++ done := make(chan struct{})+ return &sandbox.PTYSessionHandle{+ ID: sessionID,+ SandboxID: sandboxID,+ PTY: conn,+ Done: done,+ }, nil+}++// processHibernateResults handles results from HibernateAll for both backends.+func processHibernateResults(results interface{}, store *db.Store, extract func(interface{}) (string, string, error)) {- // This is intentionally generic — each backend calls it with its own result type+ switch rs := results.(type) {- case []fc.HibernateAllResult:- for _, r := range rs {- if r.Err != nil {- log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)- if store != nil {- errMsg := "hibernate failed on shutdown: " + r.Err.Error()- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)- }- continue- }- log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)- if store != nil {- session, err := store.GetSandboxSession(context.Background(), r.SandboxID)- if err == nil {- _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,- r.HibernationKey, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)- }- }- }+ case []qm.HibernateAllResult:+ for _, r := range rs {+ if r.Err != nil {+ log.Printf("opensandbox-worker: hibernate failed for %s: %v", r.SandboxID, r.Err)if store != nil {- session, err := store.GetSandboxSession(context.Background(), r.SandboxID)- if err == nil {- _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,- r.HibernationKey, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)- }+ errMsg := "hibernate failed on shutdown: " + r.Err.Error()+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "stopped", &errMsg)}+ continue}+ log.Printf("opensandbox-worker: hibernated %s (key=%s)", r.SandboxID, r.HibernationKey)+ if store != nil {+ session, err := store.GetSandboxSession(context.Background(), r.SandboxID)+ if err == nil {+ _, _ = store.CreateHibernation(context.Background(), r.SandboxID, session.OrgID,+ r.HibernationKey, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(context.Background(), r.SandboxID, "hibernated", nil)+ }+ }+ }+ }+}- // recoverLocalFC handles local NVMe recovery for Firecracker backend.- func recoverLocalFC(ctx context.Context, fcMgr *fc.Manager, store *db.Store, cfg *config.Config) {- recoveries := fcMgr.RecoverLocalSandboxes()- if len(recoveries) == 0 {- return- }- snapshotCount, workspaceCount := 0, 0- for _, r := range recoveries {- session, err := store.GetSandboxSession(ctx, r.SandboxID)- if err != nil {- log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)- continue- }- _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,- "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)- _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)- if r.HasSnapshot {- snapshotCount++- } else {- workspaceCount++- }- }- if snapshotCount+workspaceCount > 0 {- log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)- }- }-- // 3. Wait for async S3 uploads to complete- log.Println("opensandbox-worker: waiting for S3 uploads...")- fcMgr.WaitUploads(3 * time.Minute)- log.Println("opensandbox-worker: graceful shutdown complete")+// recoverLocalQEMU handles local disk recovery for QEMU backend.+func recoverLocalQEMU(ctx context.Context, qmMgr *qm.Manager, store *db.Store, cfg *config.Config) {+ recoveries := qmMgr.RecoverLocalSandboxes()+ if len(recoveries) == 0 {+ return+ }+ snapshotCount, workspaceCount := 0, 0+ for _, r := range recoveries {+ session, err := store.GetSandboxSession(ctx, r.SandboxID)+ if err != nil {+ log.Printf("opensandbox-worker: no DB session for %s, skipping recovery", r.SandboxID)+ continue+ }+ _, _ = store.CreateHibernation(ctx, r.SandboxID, session.OrgID,+ "local://"+r.SandboxID, 0, session.Region, session.Template, session.Config)+ _ = store.UpdateSandboxSessionStatus(ctx, r.SandboxID, "hibernated", nil)+ if r.HasSnapshot {+ snapshotCount+++ } else {+ workspaceCount++}}+ if snapshotCount+workspaceCount > 0 {+ log.Printf("opensandbox-worker: local recovery: %d with snapshot, %d workspace-only", snapshotCount, workspaceCount)+ }}+diff --cc internal/api/router.goindex 285e6a56,42ebb0ed..1bfbc1e4--- a/internal/api/router.go+++ b/internal/api/router.go@@@ -99,8 -103,27 +100,26 @@@ func NewServer(mgr sandbox.Manager, ptys.workerRegistry = opts.WorkerRegistrys.checkpointStore = opts.CheckpointStores.sandboxDomain = opts.SandboxDomain- s.ecrConfig = opts.ECRConfigs.cfClient = opts.CFClients.sandboxAPIProxy = opts.SandboxAPIProxy++ // Wire up readiness waiting so the proxy blocks until async creates finish+ if s.sandboxAPIProxy != nil {+ s.sandboxAPIProxy.SetWaitForReady(func(ctx context.Context, sandboxID string) error {+ val, ok := s.pendingCreates.Load(sandboxID)+ if !ok {+ return nil // not a pending create — proceed normally+ }+ pending := val.(*pendingCreate)+ select {+ case <-pending.ready:+ s.pendingCreates.Delete(sandboxID)+ return pending.err+ case <-ctx.Done():+ return ctx.Err()+ }+ })+ }}// Global middlewarediff --cc internal/worker/grpc_server.goindex d1aea9d8,3d3abedf..c75570bf--- a/internal/worker/grpc_server.go+++ b/internal/worker/grpc_server.go@@@ -37,7 -42,29 +41,29 @@@ type GRPCServer struct}// NewGRPCServer creates a new gRPC server wrapping the sandbox manager.- func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, store *db.Store) *GRPCServer {+ // If OPENSANDBOX_GRPC_TLS_* env vars are set, the server uses mTLS.-func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder *template.Builder, store *db.Store) *GRPCServer {++func NewGRPCServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, sandboxDBs *sandbox.SandboxDBManager, checkpointStore *storage.CheckpointStore, router *sandbox.SandboxRouter, builder interface{}, store *db.Store) *GRPCServer {+ serverOpts := []grpc.ServerOption{+ grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{+ MinTime: 5 * time.Second,+ PermitWithoutStream: true,+ }),+ grpc.KeepaliveParams(keepalive.ServerParameters{+ Time: 30 * time.Second,+ Timeout: 10 * time.Second,+ }),+ }++ // Enable mTLS if configured+ if grpctls.Enabled() {+ creds, err := grpctls.ServerCredentials()+ if err != nil {+ log.Fatalf("grpc: failed to load TLS credentials: %v", err)+ }+ serverOpts = append(serverOpts, grpc.Creds(creds))+ log.Println("grpc: mTLS enabled for worker gRPC server")+ }+s := &GRPCServer{manager: mgr,router: router,diff --cc proto/worker/worker.pb.goindex 97ff3d74,fc302ae0..c2796429--- a/proto/worker/worker.pb.go+++ b/proto/worker/worker.pb.go@@@ -83,9 -83,17 +83,13 @@@ type CreateSandboxRequest struct// If set, attempt warm fork from local checkpoint snapshot (LoadSnapshot instead of cold boot).CheckpointId string `protobuf:"bytes,11,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"`// Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.- SandboxId string `protobuf:"bytes,12,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`- unknownFields protoimpl.UnknownFields- sizeCache protoimpl.SizeCache+ SandboxId string `protobuf:"bytes,12,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`- // Egress allowlist: restrict outbound HTTPS to these hosts.- // Supports exact ("api.anthropic.com") and wildcard ("*.openai.com") patterns.- // Empty = all hosts allowed.++ // Egress allowlist: if non-empty, only these hosts can be reached.+ EgressAllowlist []string `protobuf:"bytes,13,rep,name=egress_allowlist,json=egressAllowlist,proto3" json:"egress_allowlist,omitempty"`- // Per-secret host restrictions: env var name → comma-separated allowed hosts.- // Secrets are only substituted in requests to matching hosts.- // Empty value or missing key = substitute on all allowed hosts.++ // Per-secret host restrictions for secrets proxy.+ SecretAllowedHosts map[string]string `protobuf:"bytes,14,rep,name=secret_allowed_hosts,json=secretAllowedHosts,proto3" json:"secret_allowed_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache}func (x *CreateSandboxRequest) Reset() {@@@ -2375,7 -2397,8 +2393,8 @@@ func (x *GetSandboxStatsResponse) GetPitype CreateCheckpointRequest struct {state protoimpl.MessageState `protogen:"open.v1"`SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`- CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // UUID assigned by control plane+ CheckpointId string `protobuf:"bytes,2,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // UUID assigned by control plane- PrepareGolden bool `protobuf:"varint,3,opt,name=prepare_golden,json=prepareGolden,proto3" json:"prepare_golden,omitempty"` // If true, also create a per-template golden snapshot for fast future creates++ PrepareGolden bool `protobuf:"varint,3,opt,name=prepare_golden,json=prepareGolden,proto3" json:"prepare_golden,omitempty"` // If true, prepare a golden snapshot from this checkpointunknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@@ -2942,7 -2856,7 +2974,7 @@@ func file_proto_worker_worker_proto_raw}var file_proto_worker_worker_proto_enumTypes = make([]protoimpl.EnumInfo, 1)- var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 49)-var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 48)++var file_proto_worker_worker_proto_msgTypes = make([]protoimpl.MessageInfo, 50)var file_proto_worker_worker_proto_goTypes = []any{(ExecOutputChunk_Stream)(0), // 0: worker.ExecOutputChunk.Stream(*CreateSandboxRequest)(nil), // 1: worker.CreateSandboxRequest@@@ -2989,70 -2903,68 +3021,72 @@@(*CreateCheckpointResponse)(nil), // 42: worker.CreateCheckpointResponse(*RestoreCheckpointRequest)(nil), // 43: worker.RestoreCheckpointRequest(*RestoreCheckpointResponse)(nil), // 44: worker.RestoreCheckpointResponse- nil, // 45: worker.CreateSandboxRequest.EnvsEntry- nil, // 46: worker.CreateSandboxRequest.SecretAllowedHostsEntry- nil, // 47: worker.ExecCommandRequest.EnvsEntry- nil, // 48: worker.ExecSessionCreateRequest.EnvsEntry+ (*SetSandboxLimitsRequest)(nil), // 45: worker.SetSandboxLimitsRequest+ (*SetSandboxLimitsResponse)(nil), // 46: worker.SetSandboxLimitsResponse+ nil, // 47: worker.CreateSandboxRequest.EnvsEntry- nil, // 48: worker.ExecCommandRequest.EnvsEntry- nil, // 49: worker.ExecSessionCreateRequest.EnvsEntry++ nil, // 48: worker.CreateSandboxRequest.SecretAllowedHostsEntry++ nil, // 49: worker.ExecCommandRequest.EnvsEntry++ nil, // 50: worker.ExecSessionCreateRequest.EnvsEntry}var file_proto_worker_worker_proto_depIdxs = []int32{- 45, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry- 46, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry+ 47, // 0: worker.CreateSandboxRequest.envs:type_name -> worker.CreateSandboxRequest.EnvsEntry- 6, // 1: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 48, // 2: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry- 0, // 3: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream- 17, // 4: worker.ListDirResponse.entries:type_name -> worker.DirEntry- 22, // 5: worker.PTYInput.resize:type_name -> worker.PTYResize- 49, // 6: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry- 36, // 7: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry- 1, // 8: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest- 3, // 9: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest- 5, // 10: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest- 7, // 11: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest- 9, // 12: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest- 9, // 13: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest- 12, // 14: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest- 14, // 15: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest- 16, // 16: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest- 19, // 17: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest- 21, // 18: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput- 32, // 19: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest- 34, // 20: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest- 37, // 21: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest- 24, // 22: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest- 26, // 23: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest- 28, // 24: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest- 41, // 25: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest- 43, // 26: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest- 30, // 27: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest- 39, // 28: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 45, // 29: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest- 2, // 30: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 31: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 32: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 33: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 34: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 35: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 36: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 37: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 38: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 39: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 40: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 33, // 41: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse- 35, // 42: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse- 38, // 43: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse- 25, // 44: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 45: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 46: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse- 42, // 47: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse- 44, // 48: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse- 31, // 49: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 40, // 50: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 46, // 51: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse- 30, // [30:52] is the sub-list for method output_type- 8, // [8:30] is the sub-list for method input_type- 8, // [8:8] is the sub-list for extension type_name- 8, // [8:8] is the sub-list for extension extendee- 0, // [0:8] is the sub-list for field type_name++ 48, // 1: worker.CreateSandboxRequest.secret_allowed_hosts:type_name -> worker.CreateSandboxRequest.SecretAllowedHostsEntry+ 6, // 2: worker.ListSandboxesResponse.sandboxes:type_name -> worker.GetSandboxResponse- 47, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry++ 49, // 3: worker.ExecCommandRequest.envs:type_name -> worker.ExecCommandRequest.EnvsEntry+ 0, // 4: worker.ExecOutputChunk.stream:type_name -> worker.ExecOutputChunk.Stream+ 17, // 5: worker.ListDirResponse.entries:type_name -> worker.DirEntry+ 22, // 6: worker.PTYInput.resize:type_name -> worker.PTYResize- 48, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry++ 50, // 7: worker.ExecSessionCreateRequest.envs:type_name -> worker.ExecSessionCreateRequest.EnvsEntry+ 36, // 8: worker.ExecSessionListResponse.sessions:type_name -> worker.ExecSessionInfoEntry+ 1, // 9: worker.SandboxWorker.CreateSandbox:input_type -> worker.CreateSandboxRequest+ 3, // 10: worker.SandboxWorker.DestroySandbox:input_type -> worker.DestroySandboxRequest+ 5, // 11: worker.SandboxWorker.GetSandbox:input_type -> worker.GetSandboxRequest+ 7, // 12: worker.SandboxWorker.ListSandboxes:input_type -> worker.ListSandboxesRequest+ 9, // 13: worker.SandboxWorker.ExecCommand:input_type -> worker.ExecCommandRequest+ 9, // 14: worker.SandboxWorker.ExecCommandStream:input_type -> worker.ExecCommandRequest+ 12, // 15: worker.SandboxWorker.ReadFile:input_type -> worker.ReadFileRequest+ 14, // 16: worker.SandboxWorker.WriteFile:input_type -> worker.WriteFileRequest+ 16, // 17: worker.SandboxWorker.ListDir:input_type -> worker.ListDirRequest+ 19, // 18: worker.SandboxWorker.CreatePTY:input_type -> worker.CreatePTYRequest+ 21, // 19: worker.SandboxWorker.PTYStream:input_type -> worker.PTYInput+ 32, // 20: worker.SandboxWorker.ExecSessionCreate:input_type -> worker.ExecSessionCreateRequest+ 34, // 21: worker.SandboxWorker.ExecSessionList:input_type -> worker.ExecSessionListRequest+ 37, // 22: worker.SandboxWorker.ExecSessionKill:input_type -> worker.ExecSessionKillRequest+ 24, // 23: worker.SandboxWorker.HibernateSandbox:input_type -> worker.HibernateSandboxRequest+ 26, // 24: worker.SandboxWorker.WakeSandbox:input_type -> worker.WakeSandboxRequest+ 28, // 25: worker.SandboxWorker.SaveAsTemplate:input_type -> worker.SaveAsTemplateRequest+ 41, // 26: worker.SandboxWorker.CreateCheckpoint:input_type -> worker.CreateCheckpointRequest+ 43, // 27: worker.SandboxWorker.RestoreCheckpoint:input_type -> worker.RestoreCheckpointRequest+ 30, // 28: worker.SandboxWorker.BuildTemplate:input_type -> worker.BuildTemplateRequest+ 39, // 29: worker.SandboxWorker.GetSandboxStats:input_type -> worker.GetSandboxStatsRequest- 2, // 30: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse- 4, // 31: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse- 6, // 32: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse- 8, // 33: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse- 10, // 34: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse- 11, // 35: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk- 13, // 36: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse- 15, // 37: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse- 18, // 38: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse- 20, // 39: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse- 23, // 40: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput- 33, // 41: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse- 35, // 42: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse- 38, // 43: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse- 25, // 44: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse- 27, // 45: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse- 29, // 46: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse- 42, // 47: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse- 44, // 48: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse- 31, // 49: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse- 40, // 50: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse- 30, // [30:51] is the sub-list for method output_type- 9, // [9:30] is the sub-list for method input_type++ 45, // 30: worker.SandboxWorker.SetSandboxLimits:input_type -> worker.SetSandboxLimitsRequest++ 2, // 31: worker.SandboxWorker.CreateSandbox:output_type -> worker.CreateSandboxResponse++ 4, // 32: worker.SandboxWorker.DestroySandbox:output_type -> worker.DestroySandboxResponse++ 6, // 33: worker.SandboxWorker.GetSandbox:output_type -> worker.GetSandboxResponse++ 8, // 34: worker.SandboxWorker.ListSandboxes:output_type -> worker.ListSandboxesResponse++ 10, // 35: worker.SandboxWorker.ExecCommand:output_type -> worker.ExecCommandResponse++ 11, // 36: worker.SandboxWorker.ExecCommandStream:output_type -> worker.ExecOutputChunk++ 13, // 37: worker.SandboxWorker.ReadFile:output_type -> worker.ReadFileResponse++ 15, // 38: worker.SandboxWorker.WriteFile:output_type -> worker.WriteFileResponse++ 18, // 39: worker.SandboxWorker.ListDir:output_type -> worker.ListDirResponse++ 20, // 40: worker.SandboxWorker.CreatePTY:output_type -> worker.CreatePTYResponse++ 23, // 41: worker.SandboxWorker.PTYStream:output_type -> worker.PTYOutput++ 33, // 42: worker.SandboxWorker.ExecSessionCreate:output_type -> worker.ExecSessionCreateResponse++ 35, // 43: worker.SandboxWorker.ExecSessionList:output_type -> worker.ExecSessionListResponse++ 38, // 44: worker.SandboxWorker.ExecSessionKill:output_type -> worker.ExecSessionKillResponse++ 25, // 45: worker.SandboxWorker.HibernateSandbox:output_type -> worker.HibernateSandboxResponse++ 27, // 46: worker.SandboxWorker.WakeSandbox:output_type -> worker.WakeSandboxResponse++ 29, // 47: worker.SandboxWorker.SaveAsTemplate:output_type -> worker.SaveAsTemplateResponse++ 42, // 48: worker.SandboxWorker.CreateCheckpoint:output_type -> worker.CreateCheckpointResponse++ 44, // 49: worker.SandboxWorker.RestoreCheckpoint:output_type -> worker.RestoreCheckpointResponse++ 31, // 50: worker.SandboxWorker.BuildTemplate:output_type -> worker.BuildTemplateResponse++ 40, // 51: worker.SandboxWorker.GetSandboxStats:output_type -> worker.GetSandboxStatsResponse++ 46, // 52: worker.SandboxWorker.SetSandboxLimits:output_type -> worker.SetSandboxLimitsResponse++ 31, // [31:53] is the sub-list for method output_type++ 9, // [9:31] is the sub-list for method input_type+ 9, // [9:9] is the sub-list for extension type_name+ 9, // [9:9] is the sub-list for extension extendee+ 0, // [0:9] is the sub-list for field type_name}func init() { file_proto_worker_worker_proto_init() }@@@ -3070,7 -2982,7 +3104,7 @@@ func file_proto_worker_worker_proto_iniGoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_worker_worker_proto_rawDesc), len(file_proto_worker_worker_proto_rawDesc)),NumEnums: 1,- NumMessages: 49,- NumMessages: 48,++ NumMessages: 50,NumExtensions: 0,NumServices: 1,},diff --cc proto/worker/worker.protoindex 665464fe,1eb79a6d..6acec57c--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@@ -55,6 -53,14 +55,10 @@@ message CreateSandboxRequeststring checkpoint_id = 11;// Server-assigned sandbox ID. If non-empty, worker uses this instead of generating one.string sandbox_id = 12;- // Egress allowlist: restrict outbound HTTPS to these hosts.- // Supports exact ("api.anthropic.com") and wildcard ("*.openai.com") patterns.- // Empty = all hosts allowed.++ // Egress allowlist: if non-empty, only these hosts can be reached.+ repeated string egress_allowlist = 13;- // Per-secret host restrictions: env var name → comma-separated allowed hosts.- // Secrets are only substituted in requests to matching hosts.- // Empty value or missing key = substitute on all allowed hosts.++ // Per-secret host restrictions for secrets proxy.+ map<string, string> secret_allowed_hosts = 14;}message CreateSandboxResponse {@@@ -275,6 -281,7 +279,7 @@@ message GetSandboxStatsResponsemessage CreateCheckpointRequest {string sandbox_id = 1;string checkpoint_id = 2; // UUID assigned by control plane- bool prepare_golden = 3; // If true, also create a per-template golden snapshot for fast future creates++ bool prepare_golden = 3; // If true, prepare a golden snapshot from this checkpoint}message CreateCheckpointResponse {diff --cc scripts/qemu-tests/01-lifecycle.shindex 00000000,00000000..6259da53new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/01-lifecycle.sh@@@ -1,0 -1,0 +1,39 @@@++#!/usr/bin/env bash++# 01-lifecycle.sh — Sandbox create, list, get, destroy, auto-timeout++source "$(dirname "$0")/common.sh"++++h "Sandbox Lifecycle"++++# Create++SB=$(create_sandbox 3600)++[ -n "$SB" ] && pass "Create sandbox: $SB" || fail "Create sandbox"++++# List++LIST=$(api "$API_URL/api/sandboxes")++echo "$LIST" | grep -q "$SB" && pass "List shows sandbox" || fail "List shows sandbox"++++# Get++STATUS=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; print(json.load(sys.stdin)['status'])")++[ "$STATUS" = "running" ] && pass "Get status: running" || fail "Get status: $STATUS"++++# Destroy++api -X DELETE "$API_URL/api/sandboxes/$SB" >/dev/null++sleep 1++STATUS=$(api "$API_URL/api/sandboxes/$SB" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','gone'))" 2>/dev/null)++[ "$STATUS" != "running" ] && pass "Destroy: sandbox gone" || fail "Destroy: still running"++++# Timeout auto-destroy++h "Auto-timeout (10s)"++SB2=$(create_sandbox 10)++[ -n "$SB2" ] && pass "Create with timeout=10: $SB2" || fail "Create with timeout=10"++echo " Waiting 15s for auto-destroy..."++sleep 15++STATUS=$(api "$API_URL/api/sandboxes/$SB2" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','gone'))" 2>/dev/null)++if [ "$STATUS" != "running" ]; then++ pass "Auto-timeout: sandbox destroyed after 10s"++else++ fail "Auto-timeout: sandbox still running"++ destroy_sandbox "$SB2"++fi++++summarydiff --cc scripts/qemu-tests/02-exec-files.shindex 00000000,00000000..20411bdbnew file mode 100755--- /dev/null+++ b/scripts/qemu-tests/02-exec-files.sh@@@ -1,0 -1,0 +1,64 @@@++#!/usr/bin/env bash++# 02-exec-files.sh — Exec commands, file read/write/list++source "$(dirname "$0")/common.sh"++++h "Exec & File I/O"++++SB=$(create_sandbox)++trap "destroy_sandbox $SB" EXIT++++# Basic exec++OUT=$(exec_stdout "$SB" "echo" "hello world")++[ "$OUT" = "hello world" ] && pass "exec echo" || fail "exec echo: '$OUT'"++++# Python exec++OUT=$(exec_stdout "$SB" "python3" "-c" "print(1+1)")++[ "$OUT" = "2" ] && pass "exec python3" || fail "exec python3: '$OUT'"++++# Exec with env++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" \++ -d '{"cmd":"bash","args":["-c","echo $FOO"],"envs":{"FOO":"bar123"},"timeout":5}')++OUT=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['stdout'].strip())")++[ "$OUT" = "bar123" ] && pass "exec with envs" || fail "exec with envs: '$OUT'"++++# Exec with cwd++OUT=$(exec_stdout "$SB" "pwd")++# default cwd++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" \++ -d '{"cmd":"pwd","args":[],"cwd":"/workspace","timeout":5}')++OUT=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['stdout'].strip())")++[ "$OUT" = "/workspace" ] && pass "exec with cwd" || fail "exec with cwd: '$OUT'"++++# Exec timeout++START=$(date +%s)++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/exec/run" \++ -d '{"cmd":"sleep","args":["30"],"timeout":3}')++END=$(date +%s)++ELAPSED=$((END - START))++[ "$ELAPSED" -lt 10 ] && pass "exec timeout (${ELAPSED}s)" || fail "exec timeout took ${ELAPSED}s"++++# Write file++api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt" \++ -H "Content-Type: application/octet-stream" \++ --data-binary "hello world" >/dev/null++pass "write file"++++# Read file++CONTENT=$(api "$API_URL/api/sandboxes/$SB/files?path=/workspace/test.txt")++[ "$CONTENT" = "hello world" ] && pass "read file" || fail "read file: '$CONTENT'"++++# List dir++LIST=$(api "$API_URL/api/sandboxes/$SB/files/list?path=/workspace")++echo "$LIST" | grep -q "test.txt" && pass "list dir" || fail "list dir"++++# Large file (10MB)++dd if=/dev/urandom bs=1M count=10 2>/dev/null | base64 > /tmp/qemu-test-large.txt++api -X PUT "$API_URL/api/sandboxes/$SB/files?path=/workspace/large.bin" \++ -H "Content-Type: application/octet-stream" \++ --data-binary @/tmp/qemu-test-large.txt >/dev/null++SIZE=$(exec_stdout "$SB" "stat" "-c" "%s" "/workspace/large.bin")++EXPECTED=$(wc -c < /tmp/qemu-test-large.txt | tr -d ' ')++[ "$SIZE" = "$EXPECTED" ] && pass "large file (${SIZE} bytes)" || fail "large file: got $SIZE expected $EXPECTED"++rm -f /tmp/qemu-test-large.txt++++summarydiff --cc scripts/qemu-tests/03-scaling.shindex 00000000,00000000..1acb228enew file mode 100755--- /dev/null+++ b/scripts/qemu-tests/03-scaling.sh@@@ -1,0 -1,0 +1,52 @@@++#!/usr/bin/env bash++# 03-scaling.sh — Memory scaling via virtio-mem (external + internal API)++source "$(dirname "$0")/common.sh"++++h "Memory Scaling (virtio-mem)"++++SB=$(create_sandbox)++trap "destroy_sandbox $SB" EXIT++++# Baseline++MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM" -gt 800 ] && [ "$MEM" -lt 1000 ] && pass "Baseline: ${MEM}MB (~1GB)" || fail "Baseline: ${MEM}MB"++++# Scale to 2GB via external API++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null++sleep 1++MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM" -gt 1800 ] && [ "$MEM" -lt 2100 ] && pass "Scale 2GB (external): ${MEM}MB" || fail "Scale 2GB: ${MEM}MB"++++# Scale to 4GB via external API++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null++sleep 1++MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM" -gt 3800 ] && [ "$MEM" -lt 4200 ] && pass "Scale 4GB: ${MEM}MB" || fail "Scale 4GB: ${MEM}MB"++++# Scale to 8GB and allocate 7GB++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":8192,"cpuPercent":800,"maxPids":256}' >/dev/null++sleep 1++OUT=$(exec_stdout "$SB" "python3" "-c" "x=bytearray(7*1024*1024*1024); print(len(x))")++[ "$OUT" = "7516192768" ] && pass "8GB: 7GB allocation OK" || fail "8GB allocation: '$OUT'"++++# Scale down to 1GB (cgroup enforced, physical stays)++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":1024,"cpuPercent":100,"maxPids":128}' >/dev/null++sleep 1++CGROUP_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/memory.max")++# Should be ~1GB in bytes++CGROUP_MB=$((CGROUP_MAX / 1024 / 1024))++[ "$CGROUP_MB" -gt 900 ] && [ "$CGROUP_MB" -lt 1200 ] && pass "Scale down cgroup: ${CGROUP_MB}MB" || fail "Scale down cgroup: ${CGROUP_MB}MB"++++# Internal scale API++h "Internal Scale API (169.254.169.254)"++RESULT=$(exec_stdout "$SB" "curl" "-s" "-X" "POST" "http://169.254.169.254/v1/scale" "-d" '{"memoryMB":2048}')++echo "$RESULT" | grep -q '"ok":true' && pass "Internal scale API" || fail "Internal scale: $RESULT"++sleep 1++MEM=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM" -gt 1800 ] && pass "Internal scale verified: ${MEM}MB" || fail "Internal scale verify: ${MEM}MB"++++summarydiff --cc scripts/qemu-tests/04-metadata.shindex 00000000,00000000..387bee1bnew file mode 100755--- /dev/null+++ b/scripts/qemu-tests/04-metadata.sh@@@ -1,0 -1,0 +1,31 @@@++#!/usr/bin/env bash++# 04-metadata.sh — Internal metadata API (169.254.169.254)++source "$(dirname "$0")/common.sh"++++h "Metadata API (169.254.169.254)"++++SB=$(create_sandbox)++trap "destroy_sandbox $SB" EXIT++++# Status++STATUS=$(exec_stdout "$SB" "curl" "-s" "http://169.254.169.254/v1/status")++echo "$STATUS" | grep -q "\"sandboxId\":\"$SB\"" && pass "Status: sandboxId matches" || fail "Status sandboxId: $STATUS"++echo "$STATUS" | grep -q '"uptime"' && pass "Status: has uptime" || fail "Status uptime: $STATUS"++++# Limits++LIMITS=$(exec_stdout "$SB" "curl" "-s" "http://169.254.169.254/v1/limits")++echo "$LIMITS" | grep -q '"memLimit"' && pass "Limits: has memLimit" || fail "Limits: $LIMITS"++echo "$LIMITS" | grep -q '"pids"' && pass "Limits: has pids" || fail "Limits pids: $LIMITS"++++# Metadata++META=$(exec_stdout "$SB" "curl" "-s" "http://169.254.169.254/v1/metadata")++echo "$META" | grep -q '"region"' && pass "Metadata: has region" || fail "Metadata region: $META"++echo "$META" | grep -q '"template"' && pass "Metadata: has template" || fail "Metadata template: $META"++++# Clock sync++GUEST_TIME=$(exec_stdout "$SB" "date" "+%s")++HOST_TIME=$(date +%s)++DRIFT=$((GUEST_TIME - HOST_TIME))++[ "$DRIFT" -ge -2 ] && [ "$DRIFT" -le 2 ] && pass "Clock sync: drift=${DRIFT}s" || fail "Clock drift: ${DRIFT}s"++++summarydiff --cc scripts/qemu-tests/05-hibernate-wake.shindex 00000000,00000000..7dcb068dnew file mode 100755--- /dev/null+++ b/scripts/qemu-tests/05-hibernate-wake.sh@@@ -1,0 -1,0 +1,81 @@@++#!/usr/bin/env bash++# 05-hibernate-wake.sh — Hibernate/wake with data persistence++source "$(dirname "$0")/common.sh"++++TIMEOUT=120++++h "Hibernate / Wake"++++SB=$(create_sandbox)++# No trap — we manage cleanup manually++++# Write marker file++exec_run "$SB" "bash" "-c" "echo persist-test-42 > /workspace/marker.txt" >/dev/null++pass "Write marker file"++++# Hibernate++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/hibernate")++echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernate" || { fail "Hibernate: $RESULT"; destroy_sandbox "$SB"; exit 1; }++++# Wake++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')++echo "$RESULT" | grep -q '"running"' && pass "Wake" || { fail "Wake: $RESULT"; destroy_sandbox "$SB"; exit 1; }++++# Verify workspace file++OUT=$(exec_stdout "$SB" "cat" "/workspace/marker.txt")++[ "$OUT" = "persist-test-42" ] && pass "Workspace file survived" || fail "Workspace file: '$OUT'"++++# Rootfs persistence (apt install)++h "Rootfs Persistence"++exec_run "$SB" "bash" "-c" "apt-get update -qq && apt-get install -y -qq cowsay 2>/dev/null" >/dev/null++OUT=$(exec_stdout "$SB" "bash" "-c" "/usr/games/cowsay test 2>/dev/null | head -1")++[ -n "$OUT" ] && pass "cowsay installed" || fail "cowsay install"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/hibernate")++echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernate (with cowsay)" || fail "Hibernate 2"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')++echo "$RESULT" | grep -q '"running"' && pass "Wake (2nd)" || fail "Wake 2"++++OUT=$(exec_stdout "$SB" "bash" "-c" "/usr/games/cowsay survived 2>/dev/null | head -1")++[ -n "$OUT" ] && pass "cowsay survived hibernate" || fail "cowsay after wake"++++# Workspace large file with hash++h "Large File Integrity"++HASH_BEFORE=$(exec_stdout "$SB" "bash" "-c" "dd if=/dev/urandom of=/workspace/big.bin bs=1M count=100 2>/dev/null && sha256sum /workspace/big.bin | cut -d' ' -f1")++[ -n "$HASH_BEFORE" ] && pass "Write 100MB (hash: ${HASH_BEFORE:0:16}...)" || fail "Write 100MB"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/hibernate")++echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernate (100MB)" || fail "Hibernate 3"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')++echo "$RESULT" | grep -q '"running"' && pass "Wake (3rd)" || fail "Wake 3"++++HASH_AFTER=$(exec_stdout "$SB" "bash" "-c" "sha256sum /workspace/big.bin | cut -d' ' -f1")++[ "$HASH_BEFORE" = "$HASH_AFTER" ] && pass "100MB hash matches after wake" || fail "Hash mismatch: $HASH_BEFORE vs $HASH_AFTER"++++# Scaled memory persists++h "Memory Persists Across Hibernate"++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null++sleep 1++MEM_BEFORE=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++pass "Scaled to 2GB: ${MEM_BEFORE}MB"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/hibernate")++echo "$RESULT" | grep -q '"hibernated"' && pass "Hibernate (2GB)" || fail "Hibernate 4"++++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/wake" -d '{"timeout":3600}')++echo "$RESULT" | grep -q '"running"' && pass "Wake (4th)" || fail "Wake 4"++++MEM_AFTER=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM_AFTER" -gt 1800 ] && pass "Memory persisted: ${MEM_AFTER}MB" || fail "Memory after wake: ${MEM_AFTER}MB"++++# Clock sync after wake++GUEST=$(exec_stdout "$SB" "date" "+%s")++HOST=$(date +%s)++DRIFT=$((GUEST - HOST))++[ "$DRIFT" -ge -2 ] && [ "$DRIFT" -le 2 ] && pass "Clock sync after wake: drift=${DRIFT}s" || fail "Clock drift: ${DRIFT}s"++++destroy_sandbox "$SB"++summarydiff --cc scripts/qemu-tests/06-checkpoint-fork.shindex 00000000,00000000..9c0f1e53new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/06-checkpoint-fork.sh@@@ -1,0 -1,0 +1,83 @@@++#!/usr/bin/env bash++# 06-checkpoint-fork.sh — Checkpoint creation, forking, state isolation++source "$(dirname "$0")/common.sh"++++TIMEOUT=60++SANDBOXES=()++cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done; }++trap cleanup EXIT++++h "Checkpoint / Fork"++++SB=$(create_sandbox)++SANDBOXES+=("$SB")++++# Install numpy + write workspace file before checkpoint++exec_run "$SB" "bash" "-c" "pip3 install --quiet numpy 2>/dev/null" >/dev/null++exec_run "$SB" "bash" "-c" "echo checkpoint-data > /workspace/check.txt" >/dev/null++pass "Setup: numpy + workspace file"++++# Create checkpoint++CP_RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB/checkpoints" -d '{"name":"test-cp"}')++CP_ID=$(echo "$CP_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")++[ -n "$CP_ID" ] && pass "Create checkpoint: $CP_ID" || { fail "Create checkpoint"; summary; }++++sleep 5 # wait for savevm++++# Fork from checkpoint++FORK_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":3600}')++FORK_ID=$(echo "$FORK_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")++SANDBOXES+=("$FORK_ID")++[ -n "$FORK_ID" ] && pass "Fork: $FORK_ID" || { fail "Fork failed"; summary; }++++# Wait for fork to be ready++sleep 8++wait_for_sandbox "$FORK_ID" 15 && pass "Fork running" || { fail "Fork not ready"; summary; }++++# Verify numpy on fork++OUT=$(exec_stdout "$FORK_ID" "python3" "-c" "import numpy; print(numpy.__version__)")++[ -n "$OUT" ] && pass "Fork has numpy: $OUT" || fail "Fork numpy missing"++++# Verify workspace file on fork++OUT=$(exec_stdout "$FORK_ID" "cat" "/workspace/check.txt")++[ "$OUT" = "checkpoint-data" ] && pass "Fork has workspace file" || fail "Fork workspace: '$OUT'"++++# Pre-scale checkpoint test++h "Pre-Scale Checkpoint"++api -X PUT "$API_URL/api/sandboxes/$SB/limits" \++ -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null++sleep 1++MEM_ORIG=$(exec_stdout "$SB" "free" "-m" | awk '/Mem:/{print $2}')++pass "Original scaled to 4GB: ${MEM_ORIG}MB"++++# Fork from the PRE-SCALE checkpoint++FORK2_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":3600}')++FORK2_ID=$(echo "$FORK2_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")++SANDBOXES+=("$FORK2_ID")++sleep 8++wait_for_sandbox "$FORK2_ID" 15++++MEM_FORK=$(exec_stdout "$FORK2_ID" "free" "-m" | awk '/Mem:/{print $2}')++[ "$MEM_FORK" -lt 1100 ] && pass "Fork has original 1GB: ${MEM_FORK}MB (not 4GB)" || fail "Fork memory: ${MEM_FORK}MB (expected ~896)"++++# Isolation: write to fork, verify original unaffected++h "Fork Isolation"++exec_run "$FORK_ID" "bash" "-c" "echo fork-only > /workspace/fork-file.txt" >/dev/null++OUT=$(exec_stdout "$SB" "bash" "-c" "cat /workspace/fork-file.txt 2>/dev/null || echo not-found")++[ "$OUT" = "not-found" ] && pass "Fork isolated from original" || fail "Fork leak: '$OUT'"++++# Multiple forks++h "Multiple Forks"++for i in 1 2 3; do++ F_RESULT=$(api -X POST "$API_URL/api/sandboxes/from-checkpoint/$CP_ID" -d '{"timeout":3600}')++ F_ID=$(echo "$F_RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])")++ SANDBOXES+=("$F_ID")++ sleep 5++ if wait_for_sandbox "$F_ID" 15; then++ pass "Fork $i: $F_ID"++ else++ fail "Fork $i failed"++ fi++done++++summarydiff --cc scripts/qemu-tests/07-isolation.shindex 00000000,00000000..69cb0733new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/07-isolation.sh@@@ -1,0 -1,0 +1,53 @@@++#!/usr/bin/env bash++# 07-isolation.sh — Resource isolation, cgroups, process list, cross-sandbox isolation++source "$(dirname "$0")/common.sh"++++SANDBOXES=()++cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done; }++trap cleanup EXIT++++h "Resource Isolation & Cgroups"++++SB=$(create_sandbox)++SANDBOXES+=("$SB")++++# PID 1 is agent++PIDS=$(exec_stdout "$SB" "ps" "aux")++echo "$PIDS" | grep -q 'osb-agent' && pass "PID 1 is osb-agent" || fail "PID 1 not osb-agent"++++# Count user processes (exclude kernel threads [bracketed], ps itself, header)++USER_PROCS=$(echo "$PIDS" | grep -v '\[.*\]' | grep -v 'ps aux' | grep -v 'USER' | grep -cv '^\s*$' || true)++[ "$USER_PROCS" -le 2 ] && pass "Minimal user processes: $USER_PROCS" || fail "Too many user processes: $USER_PROCS"++++# Cgroup pids.max++PIDS_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/pids.max")++[ "$PIDS_MAX" = "128" ] && pass "pids.max = 128" || fail "pids.max = $PIDS_MAX"++++# Cgroup memory.max (~90% of 1GB)++MEM_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/memory.max")++MEM_MAX_MB=$((MEM_MAX / 1024 / 1024))++[ "$MEM_MAX_MB" -gt 700 ] && [ "$MEM_MAX_MB" -lt 950 ] && pass "memory.max = ${MEM_MAX_MB}MB (90% of 1GB)" || fail "memory.max = ${MEM_MAX_MB}MB"++++# Cgroup cpu.max++CPU_MAX=$(exec_stdout "$SB" "cat" "/sys/fs/cgroup/sandbox/cpu.max")++echo "$CPU_MAX" | grep -qE '^[0-9]+ 100000$' && pass "cpu.max = $CPU_MAX" || fail "cpu.max = $CPU_MAX"++++# Cross-sandbox isolation++h "Cross-Sandbox Isolation"++SB_A=$(create_sandbox)++SB_B=$(create_sandbox)++SANDBOXES+=("$SB_A" "$SB_B")++++exec_run "$SB_A" "bash" "-c" "echo secret-A > /workspace/secret.txt" >/dev/null++OUT=$(exec_stdout "$SB_B" "bash" "-c" "cat /workspace/secret.txt 2>/dev/null || echo not-found")++[ "$OUT" = "not-found" ] && pass "Cross-sandbox isolated (A's file not in B)" || fail "Cross-sandbox leak: '$OUT'"++++# Network works++h "Network"++OUT=$(exec_stdout "$SB" "bash" "-c" "ping -c1 -W3 8.8.8.8 2>&1 | grep -c 'bytes from' || echo 0")++[ "$OUT" = "1" ] && pass "Network: ping 8.8.8.8" || fail "Ping failed"++++OUT=$(exec_stdout "$SB" "bash" "-c" "nslookup google.com 2>&1 | grep -c 'Address' || echo 0")++[ "$OUT" -ge 1 ] && pass "DNS resolution" || fail "DNS failed"++++summarydiff --cc scripts/qemu-tests/08-fork-bomb.shindex 00000000,00000000..dfb94ff1new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/08-fork-bomb.sh@@@ -1,0 -1,0 +1,40 @@@++#!/usr/bin/env bash++# 08-fork-bomb.sh — Fork bomb containment (sandbox wedges but host survives)++source "$(dirname "$0")/common.sh"++++TIMEOUT=60++SANDBOXES=()++cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done; }++trap cleanup EXIT++++h "Fork Bomb Containment"++++# Create two sandboxes — one for the bomb, one to verify host isn't affected++SB_BOMB=$(create_sandbox)++SB_CTRL=$(create_sandbox)++SANDBOXES+=("$SB_BOMB" "$SB_CTRL")++++# Verify control sandbox works++OUT=$(exec_stdout "$SB_CTRL" "echo" "control-ok")++[ "$OUT" = "control-ok" ] && pass "Control sandbox: responsive" || fail "Control sandbox"++++# Launch fork bomb (will timeout)++echo " Launching fork bomb on $SB_BOMB (5s timeout)..."++RESULT=$(api --max-time 15 -X POST "$API_URL/api/sandboxes/$SB_BOMB/exec/run" \++ -d '{"cmd":"bash","args":["-c",":(){ :|:& };:"],"timeout":5}' 2>/dev/null || echo '{"error":"timeout"}')++pass "Fork bomb launched (returned or timed out)"++++# Verify control sandbox still works++sleep 2++OUT=$(exec_stdout "$SB_CTRL" "echo" "still-alive")++[ "$OUT" = "still-alive" ] && pass "Control sandbox: still responsive after bomb" || fail "Control sandbox affected by bomb"++++# Destroy the bombed sandbox++api -X DELETE "$API_URL/api/sandboxes/$SB_BOMB" >/dev/null 2>&1++pass "Bombed sandbox destroyed"++++# Verify control sandbox still works after destroy++OUT=$(exec_stdout "$SB_CTRL" "echo" "final-check")++[ "$OUT" = "final-check" ] && pass "Control sandbox: works after bomb cleanup" || fail "Control sandbox post-cleanup"++++summarydiff --cc scripts/qemu-tests/09-concurrent.shindex 00000000,00000000..f6dbfba9new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/09-concurrent.sh@@@ -1,0 -1,0 +1,75 @@@++#!/usr/bin/env bash++# 09-concurrent.sh — Concurrent sandbox creation + exec under load++source "$(dirname "$0")/common.sh"++++SANDBOXES=()++cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done; }++trap cleanup EXIT++++h "Concurrent Load"++++# 3 sandboxes at different tiers++SB1=$(create_sandbox); SANDBOXES+=("$SB1")++SB2=$(create_sandbox); SANDBOXES+=("$SB2")++SB3=$(create_sandbox); SANDBOXES+=("$SB3")++pass "Created 3 sandboxes"++++api -X PUT "$API_URL/api/sandboxes/$SB2/limits" -d '{"maxMemoryMB":2048,"cpuPercent":200,"maxPids":256}' >/dev/null++api -X PUT "$API_URL/api/sandboxes/$SB3/limits" -d '{"maxMemoryMB":4096,"cpuPercent":400,"maxPids":256}' >/dev/null++sleep 1++++MEM1=$(exec_stdout "$SB1" "free" "-m" | awk '/Mem:/{print $2}')++MEM2=$(exec_stdout "$SB2" "free" "-m" | awk '/Mem:/{print $2}')++MEM3=$(exec_stdout "$SB3" "free" "-m" | awk '/Mem:/{print $2}')++++[ "$MEM1" -lt 1000 ] && pass "SB1 (1GB): ${MEM1}MB" || fail "SB1: ${MEM1}MB"++[ "$MEM2" -gt 1800 ] && pass "SB2 (2GB): ${MEM2}MB" || fail "SB2: ${MEM2}MB"++[ "$MEM3" -gt 3800 ] && pass "SB3 (4GB): ${MEM3}MB" || fail "SB3: ${MEM3}MB"++++# Destroy tier sandboxes++for sb in "$SB1" "$SB2" "$SB3"; do destroy_sandbox "$sb"; done++SANDBOXES=()++++# 10 concurrent creates++h "10 Concurrent Creates"++PIDS=()++TMPDIR=$(mktemp -d)++for i in $(seq 1 10); do++ (++ RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":300}')++ SB_ID=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID','FAIL'))" 2>/dev/null)++ echo "$SB_ID" > "$TMPDIR/sb-$i"++ ) &++ PIDS+=($!)++done++++# Wait for all++CREATED=0++FAILED=0++for pid in "${PIDS[@]}"; do++ wait "$pid" 2>/dev/null || true++done++++for i in $(seq 1 10); do++ SB_ID=$(cat "$TMPDIR/sb-$i" 2>/dev/null)++ if [ -n "$SB_ID" ] && [ "$SB_ID" != "FAIL" ]; then++ SANDBOXES+=("$SB_ID")++ CREATED=$((CREATED+1))++ else++ FAILED=$((FAILED+1))++ fi++done++rm -rf "$TMPDIR"++++[ "$CREATED" -ge 8 ] && pass "Concurrent creates: $CREATED/10 succeeded" || fail "Concurrent creates: only $CREATED/10"++++# Exec on all created sandboxes in parallel++h "Exec Under Load ($CREATED sandboxes)"++OK=0++for sb in "${SANDBOXES[@]}"; do++ OUT=$(exec_stdout "$sb" "echo" "load-test" 2>/dev/null)++ [ "$OUT" = "load-test" ] && OK=$((OK+1))++done++[ "$OK" -eq "${#SANDBOXES[@]}" ] && pass "All $OK sandboxes responsive" || fail "Only $OK/${#SANDBOXES[@]} responsive"++++summarydiff --cc scripts/qemu-tests/10-edge-cases.shindex 00000000,00000000..73edfd58new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/10-edge-cases.sh@@@ -1,0 -1,0 +1,74 @@@++#!/usr/bin/env bash++# 10-edge-cases.sh — Edge cases and error handling++source "$(dirname "$0")/common.sh"++++SANDBOXES=()++cleanup() { for sb in "${SANDBOXES[@]}"; do destroy_sandbox "$sb"; done; }++trap cleanup EXIT++++h "Edge Cases"++++# Exec on hibernated sandbox (wake-on-request: auto-wakes and executes)++SB=$(create_sandbox)++SANDBOXES+=("$SB")++api -X POST "$API_URL/api/sandboxes/$SB/hibernate" >/dev/null++sleep 1++RESULT=$(api --max-time 60 -X POST "$API_URL/api/sandboxes/$SB/exec/run" -d '{"cmd":"echo","args":["test"],"timeout":5}')++OUT=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null)++[ "$OUT" = "test" ] && pass "Exec on hibernated: auto-woke and executed" || fail "Exec on hibernated: $RESULT"++++# Double hibernate++h "Double Hibernate"++SB2=$(create_sandbox)++SANDBOXES+=("$SB2")++api -X POST "$API_URL/api/sandboxes/$SB2/hibernate" >/dev/null++sleep 1++RESULT=$(api -X POST "$API_URL/api/sandboxes/$SB2/hibernate")++echo "$RESULT" | grep -qi 'error\|already\|not running' && pass "Double hibernate: returns error" || fail "Double hibernate: $RESULT"++++# Destroy hibernated sandbox++api -X DELETE "$API_URL/api/sandboxes/$SB2" >/dev/null++sleep 1++STATUS=$(api "$API_URL/api/sandboxes/$SB2" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','gone'))" 2>/dev/null)++[ "$STATUS" != "running" ] && pass "Destroy hibernated sandbox (status=$STATUS)" || fail "Destroy hibernated: still running"++++# Create with zero timeout (should default)++h "Default Timeout"++SB3=$(create_sandbox 0)++SANDBOXES+=("$SB3")++OUT=$(exec_stdout "$SB3" "echo" "default-timeout-ok")++[ "$OUT" = "default-timeout-ok" ] && pass "Create with timeout=0 works" || fail "Default timeout: '$OUT'"++++# Binary file round-trip++h "Binary File Round-Trip"++SB4=$(create_sandbox)++SANDBOXES+=("$SB4")++++# Generate random binary data, write via API, read back, compare++dd if=/dev/urandom bs=4096 count=1 2>/dev/null > /tmp/qemu-test-binary.bin++HASH_LOCAL=$(shasum -a 256 /tmp/qemu-test-binary.bin | cut -d' ' -f1)++++api -X PUT "$API_URL/api/sandboxes/$SB4/files?path=/workspace/binary.bin" \++ -H "Content-Type: application/octet-stream" \++ --data-binary @/tmp/qemu-test-binary.bin >/dev/null++++HASH_REMOTE=$(exec_stdout "$SB4" "sha256sum" "/workspace/binary.bin" | awk '{print $1}')++[ "$HASH_LOCAL" = "$HASH_REMOTE" ] && pass "Binary file round-trip (hash match)" || fail "Binary mismatch: $HASH_LOCAL vs $HASH_REMOTE"++rm -f /tmp/qemu-test-binary.bin++++# Auth tests++h "Authentication"++RESULT=$(curl -s --max-time 5 -X POST "$API_URL/api/sandboxes" \++ -H "Content-Type: application/json" -d '{"timeout":300}')++echo "$RESULT" | grep -qi 'unauthorized\|missing.*key\|api key' && pass "No API key: 401" || fail "No key: $RESULT"++++RESULT=$(curl -s --max-time 5 -X POST "$API_URL/api/sandboxes" \++ -H "Content-Type: application/json" -H "X-API-Key: wrong-key" -d '{"timeout":300}')++echo "$RESULT" | grep -qi 'invalid\|forbidden\|unauthorized' && pass "Wrong API key: rejected" || fail "Wrong key: $RESULT"++++RESULT=$(api -X POST "$API_URL/api/sandboxes" -d '{"timeout":300}')++echo "$RESULT" | grep -q 'sandboxID' && pass "Correct API key: 200" || fail "Correct key: $RESULT"++NEW_SB=$(echo "$RESULT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('sandboxID',''))" 2>/dev/null)++[ -n "$NEW_SB" ] && SANDBOXES+=("$NEW_SB")++++summarydiff --cc scripts/qemu-tests/common.shindex 00000000,00000000..01611390new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/common.sh@@@ -1,0 -1,0 +1,78 @@@++#!/usr/bin/env bash++# common.sh — Shared helpers for QEMU backend test scripts++set -euo pipefail++++API_URL="${API_URL:-http://3.148.184.81:8080}"++API_KEY="${API_KEY:-test-dev-key}"++SSH_KEY="${SSH_KEY:-$HOME/.ssh/opensandbox-digger.pem}"++WORKER_HOST="${WORKER_HOST:-3.148.184.81}"++++PASS=0++FAIL=0++SKIP=0++++h() { printf '\n\033[1;34m=== %s ===\033[0m\n' "$*"; }++pass() { PASS=$((PASS+1)); printf ' \033[32m✓ %s\033[0m\n' "$*"; }++fail() { FAIL=$((FAIL+1)); printf ' \033[31m✗ %s\033[0m\n' "$*"; }++skip() { SKIP=$((SKIP+1)); printf ' \033[33m⊘ %s\033[0m\n' "$*"; }++summary() {++ echo ""++ printf '\033[1m%d passed, %d failed, %d skipped\033[0m\n' "$PASS" "$FAIL" "$SKIP"++ [ "$FAIL" -eq 0 ] && exit 0 || exit 1++}++++api() {++ curl -s --max-time "${TIMEOUT:-30}" \++ -H "Content-Type: application/json" \++ -H "X-API-Key: $API_KEY" \++ "$@"++}++++create_sandbox() {++ local timeout="${1:-3600}"++ api -X POST "$API_URL/api/sandboxes" -d "{\"timeout\":$timeout}" | python3 -c "import sys,json; print(json.load(sys.stdin)['sandboxID'])"++}++++destroy_sandbox() {++ api -X DELETE "$API_URL/api/sandboxes/$1" >/dev/null 2>&1 || true++}++++exec_run() {++ local sb="$1"; shift++ local cmd="$1"; shift++ local args=""++ if [ $# -gt 0 ]; then++ args=$(printf '%s\n' "$@" | python3 -c "import sys,json; print(json.dumps([l.strip() for l in sys.stdin]))")++ else++ args="[]"++ fi++ api -X POST "$API_URL/api/sandboxes/$sb/exec/run" \++ -d "{\"cmd\":\"$cmd\",\"args\":$args,\"timeout\":30}"++}++++exec_stdout() {++ local result++ result=$(exec_run "$@")++ echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('stdout','').strip())" 2>/dev/null++}++++exec_exit_code() {++ local result++ result=$(exec_run "$@")++ echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('exitCode',-999))" 2>/dev/null++}++++wait_for_sandbox() {++ local sb="$1" max="${2:-30}"++ for i in $(seq 1 "$max"); do++ local status++ status=$(api "$API_URL/api/sandboxes/$sb" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status',''))" 2>/dev/null)++ [ "$status" = "running" ] && return 0++ sleep 1++ done++ return 1++}++++ssh_worker() {++ ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 -i "$SSH_KEY" "ubuntu@$WORKER_HOST" "$@"++}diff --cc scripts/qemu-tests/run-all.shindex 00000000,00000000..f66ef2a9new file mode 100755--- /dev/null+++ b/scripts/qemu-tests/run-all.sh@@@ -1,0 -1,0 +1,89 @@@++#!/usr/bin/env bash++# run-all.sh — Run all QEMU backend tests in sequence++#++# Usage:++# ./scripts/qemu-tests/run-all.sh # run all tests++# ./scripts/qemu-tests/run-all.sh 01 03 05 # run specific tests++# ./scripts/qemu-tests/run-all.sh 05 # run just hibernate tests++#++# Environment:++# API_URL=http://3.148.184.81:8080 (default)++# API_KEY=test-dev-key (default)++++set -uo pipefail++++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"++++ALL_TESTS=(++ "01-lifecycle"++ "02-exec-files"++ "03-scaling"++ "04-metadata"++ "05-hibernate-wake"++ "06-checkpoint-fork"++ "07-isolation"++ "08-fork-bomb"++ "09-concurrent"++ "10-edge-cases"++)++++# Filter tests if args provided++if [ $# -gt 0 ]; then++ TESTS=()++ for arg in "$@"; do++ for t in "${ALL_TESTS[@]}"; do++ if [[ "$t" == "$arg"* ]]; then++ TESTS+=("$t")++ fi++ done++ done++else++ TESTS=("${ALL_TESTS[@]}")++fi++++TOTAL_PASS=0++TOTAL_FAIL=0++FAILED_SUITES=()++++echo ""++echo "╔══════════════════════════════════════════════╗"++echo "║ OpenSandbox QEMU Backend Test Suite ║"++echo "║ ${#TESTS[@]} test suites ║"++echo "╚══════════════════════════════════════════════╝"++echo ""++++for test in "${TESTS[@]}"; do++ SCRIPT="$SCRIPT_DIR/${test}.sh"++ if [ ! -f "$SCRIPT" ]; then++ echo " ⊘ $test: script not found"++ continue++ fi++++ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++ echo " Running: $test"++ echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"++++ if bash "$SCRIPT"; then++ echo ""++ else++ FAILED_SUITES+=("$test")++ echo ""++ fi++done++++echo ""++echo "╔══════════════════════════════════════════════╗"++echo "║ Results ║"++echo "╚══════════════════════════════════════════════╝"++echo ""++++if [ ${#FAILED_SUITES[@]} -eq 0 ]; then++ echo " ✓ All ${#TESTS[@]} test suites passed"++ exit 0++else++ echo " ${#FAILED_SUITES[@]} suite(s) had failures:"++ for suite in "${FAILED_SUITES[@]}"; do++ echo " ✗ $suite"++ done++ exit 1++fidiff --cc serverindex 00000000,00000000..d0adede0new file mode 100755Binary files differ