Skip to content

An open-source, faster Devin alternative

TypeScript

ALB tls termination, everything through control plane

Brian Reardon85913a73911a
diff --git a/cmd/server/main.go b/cmd/server/main.go
index f4c6f2cf..16910fb6 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -137,6 +137,12 @@ func main() {
defer redisRegistry.Stop()
opts.WorkerRegistry = redisRegistry
log.Println("opensandbox: Redis worker registry started")
+
+ // Create sandbox API proxy for routing data-plane requests to workers
+ if opts.Store != nil && opts.JWTIssuer != nil {
+ opts.SandboxAPIProxy = proxy.NewSandboxAPIProxy(opts.Store, redisRegistry, opts.JWTIssuer)
+ log.Println("opensandbox: sandbox API proxy enabled (data-plane requests proxied to workers)")
+ }
}
// Initialize EC2 compute pool + autoscaler (server mode with AWS configured)
diff --git a/deploy/ec2/Caddyfile b/deploy/ec2/Caddyfile
deleted file mode 100644
index 3c42d66a..00000000
--- a/deploy/ec2/Caddyfile
+++ /dev/null
@@ -1,10 +0,0 @@
-*.workers.opensandbox.ai {
- tls {
- dns route53 {
- access_key_id {env.AWS_ACCESS_KEY_ID}
- secret_access_key {env.AWS_SECRET_ACCESS_KEY}
- region us-east-2
- }
- }
- reverse_proxy localhost:8080
-}
diff --git a/deploy/ec2/caddy.service b/deploy/ec2/caddy.service
deleted file mode 100644
index ef3fc140..00000000
--- a/deploy/ec2/caddy.service
+++ /dev/null
@@ -1,15 +0,0 @@
-[Unit]
-Description=Caddy TLS Reverse Proxy
-After=network-online.target
-Wants=network-online.target
-
-[Service]
-Type=simple
-ExecStart=/usr/local/bin/caddy run --config /etc/caddy/Caddyfile
-Restart=always
-RestartSec=5
-Environment=HOME=/root
-EnvironmentFile=/etc/opensandbox/caddy.env
-
-[Install]
-WantedBy=multi-user.target
diff --git a/deploy/ec2/setup-instance.sh b/deploy/ec2/setup-instance.sh
index 789e8bc3..f32d6c60 100755
--- a/deploy/ec2/setup-instance.sh
+++ b/deploy/ec2/setup-instance.sh
@@ -11,7 +11,7 @@ set -euo pipefail
# Prerequisites:
# - Ubuntu 24.04 LTS AMI
# - r7gd.metal (ARM64) or c7i.metal (x86_64) for production
-# - Security group: 443 (HTTPS), 8080 (HTTP), 9090 (gRPC), 9091 (metrics) open inbound
+# - Security group: 8080 (HTTP), 9090 (gRPC), 9091 (metrics) open from VPC only (workers are internal)
# - SSH access
# Detect architecture
@@ -73,32 +73,6 @@ sudo apt-get install -y e2fsprogs
echo "==> Installing Redis..."
sudo apt-get install -y redis-server
-# -------------------------------------------------------------------
-# Caddy (custom build with Route53 DNS module for wildcard certs)
-# -------------------------------------------------------------------
-echo "==> Installing Go (needed for xcaddy)..."
-GO_VERSION="1.23.6"
-curl -sL "https://go.dev/dl/go${GO_VERSION}.linux-${GOARCH}.tar.gz" | sudo tar -C /usr/local -xzf -
-export PATH=$PATH:/usr/local/go/bin:$HOME/go/bin
-
-echo "==> Building Caddy with Route53 DNS module..."
-go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
-xcaddy build --with github.com/caddy-dns/route53 --output /tmp/caddy-custom
-sudo mv /tmp/caddy-custom /usr/local/bin/caddy
-sudo chmod +x /usr/local/bin/caddy
-
-echo "==> Verifying Caddy has Route53 module..."
-caddy list-modules | grep route53 || { echo "ERROR: Caddy missing route53 module"; exit 1; }
-
-echo "==> Installing Caddy config..."
-sudo mkdir -p /etc/caddy
-sudo cp /tmp/deploy-ec2/Caddyfile /etc/caddy/Caddyfile 2>/dev/null || \
- echo " NOTE: Copy deploy/ec2/Caddyfile to /etc/caddy/Caddyfile manually"
-
-echo "==> Installing Caddy systemd unit..."
-sudo cp /tmp/deploy-ec2/caddy.service /etc/systemd/system/caddy.service 2>/dev/null || \
- echo " NOTE: Copy deploy/ec2/caddy.service to /etc/systemd/system/ manually"
-
# -------------------------------------------------------------------
# NVMe instance storage (XFS with reflink for instant rootfs copies)
# -------------------------------------------------------------------
@@ -233,7 +207,7 @@ WORKER_ID="w-use2-${SHORT_ID}"
mkdir -p /etc/opensandbox
cat > /etc/opensandbox/worker-identity.env << EOF
OPENSANDBOX_WORKER_ID=${WORKER_ID}
-OPENSANDBOX_HTTP_ADDR=http://${PUBLIC_IP:-$PRIVATE_IP}:8080
+OPENSANDBOX_HTTP_ADDR=http://${PRIVATE_IP}:8080
OPENSANDBOX_GRPC_ADVERTISE=${PRIVATE_IP}:9090
EOF
echo "opensandbox-identity: ${WORKER_ID} private=${PRIVATE_IP} public=${PUBLIC_IP:-none}"
@@ -305,14 +279,12 @@ sudo systemctl daemon-reload
sudo systemctl enable opensandbox-nvme
sudo systemctl enable opensandbox-identity
sudo systemctl enable opensandbox-worker
-sudo systemctl enable caddy 2>/dev/null || true
# -------------------------------------------------------------------
# Cleanup
# -------------------------------------------------------------------
-echo "==> Cleaning up build tools..."
+echo "==> Cleaning up..."
sudo apt-get clean
-sudo rm -rf /usr/local/go $HOME/go
echo ""
echo "============================================"
diff --git a/internal/api/router.go b/internal/api/router.go
index 7dd47b99..b9e4b2f6 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -46,6 +46,7 @@ type Server struct {
ecrConfig *ecr.Config // nil if ECR not configured
cfClient *cloudflare.Client // nil if Cloudflare not configured
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
+ sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
}
// pendingCreate tracks an async sandbox creation.
@@ -73,6 +74,7 @@ type ServerOpts struct {
CheckpointStore *storage.CheckpointStore // nil if hibernation not configured
ECRConfig *ecr.Config // nil if ECR not configured
CFClient *cloudflare.Client // nil if Cloudflare not configured
+ SandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
}
// NewServer creates a new API server with all routes configured.
@@ -102,6 +104,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.sandboxDomain = opts.SandboxDomain
s.ecrConfig = opts.ECRConfig
s.cfClient = opts.CFClient
+ s.sandboxAPIProxy = opts.SandboxAPIProxy
}
// Global middleware
@@ -132,7 +135,6 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes", s.listSandboxes)
api.GET("/sandboxes/:id", s.getSandbox)
api.DELETE("/sandboxes/:id", s.killSandbox)
- api.POST("/sandboxes/:id/timeout", s.setTimeout)
// Hibernation
api.POST("/sandboxes/:id/hibernate", s.hibernateSandbox)
@@ -155,32 +157,70 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
api.GET("/sandboxes/:id/preview", s.listPreviewURLs)
api.DELETE("/sandboxes/:id/preview/:port", s.deletePreviewURL)
- // Exec sessions (replaces old /commands)
- api.POST("/sandboxes/:id/exec", s.createExecSession)
- api.GET("/sandboxes/:id/exec", s.listExecSessions)
- api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
- api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
- api.POST("/sandboxes/:id/exec/run", s.execRun)
-
- // Agent sessions (Claude Agent SDK)
- api.POST("/sandboxes/:id/agent", s.createAgentSession)
- api.GET("/sandboxes/:id/agent", s.listAgentSessions)
- api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
- api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
- api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
-
- // Filesystem
- api.GET("/sandboxes/:id/files", s.readFile)
- api.PUT("/sandboxes/:id/files", s.writeFile)
- api.GET("/sandboxes/:id/files/list", s.listDir)
- api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
- api.DELETE("/sandboxes/:id/files", s.removeFile)
-
- // PTY
- api.POST("/sandboxes/:id/pty", s.createPTY)
- api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
- api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)
- api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
+ // Data-plane routes: in server mode, proxy to workers; otherwise handle locally
+ if s.sandboxAPIProxy != nil {
+ // Server mode: proxy all data-plane requests to the worker that owns the sandbox
+ pxy := s.sandboxAPIProxy.ProxyHandler
+
+ // Exec
+ api.POST("/sandboxes/:id/exec", pxy)
+ api.GET("/sandboxes/:id/exec", pxy)
+ api.GET("/sandboxes/:id/exec/:sessionID", pxy)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", pxy)
+ api.POST("/sandboxes/:id/exec/run", pxy)
+
+ // Agent
+ api.POST("/sandboxes/:id/agent", pxy)
+ api.GET("/sandboxes/:id/agent", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", pxy)
+ api.POST("/sandboxes/:id/agent/:sid/kill", pxy)
+
+ // Filesystem
+ api.GET("/sandboxes/:id/files", pxy)
+ api.PUT("/sandboxes/:id/files", pxy)
+ api.GET("/sandboxes/:id/files/list", pxy)
+ api.POST("/sandboxes/:id/files/mkdir", pxy)
+ api.DELETE("/sandboxes/:id/files", pxy)
+
+ // PTY
+ api.POST("/sandboxes/:id/pty", pxy)
+ api.GET("/sandboxes/:id/pty/:sessionID", pxy)
+ api.POST("/sandboxes/:id/pty/:sessionID/resize", pxy)
+ api.DELETE("/sandboxes/:id/pty/:sessionID", pxy)
+
+ // Timeout
+ api.POST("/sandboxes/:id/timeout", pxy)
+
+ // Token refresh
+ api.POST("/sandboxes/:id/token/refresh", pxy)
+ } else {
+ // Combined/worker mode: handle locally
+ api.POST("/sandboxes/:id/exec", s.createExecSession)
+ api.GET("/sandboxes/:id/exec", s.listExecSessions)
+ api.GET("/sandboxes/:id/exec/:sessionID", s.execSessionWebSocket)
+ api.POST("/sandboxes/:id/exec/:sessionID/kill", s.killExecSession)
+ api.POST("/sandboxes/:id/exec/run", s.execRun)
+
+ api.POST("/sandboxes/:id/agent", s.createAgentSession)
+ api.GET("/sandboxes/:id/agent", s.listAgentSessions)
+ api.POST("/sandboxes/:id/agent/:sid/prompt", s.sendAgentPrompt)
+ api.POST("/sandboxes/:id/agent/:sid/interrupt", s.interruptAgent)
+ api.POST("/sandboxes/:id/agent/:sid/kill", s.killAgentSession)
+
+ api.GET("/sandboxes/:id/files", s.readFile)
+ api.PUT("/sandboxes/:id/files", s.writeFile)
+ api.GET("/sandboxes/:id/files/list", s.listDir)
+ api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
+ api.DELETE("/sandboxes/:id/files", s.removeFile)
+
+ api.POST("/sandboxes/:id/pty", s.createPTY)
+ api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)
+ api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)
+ api.DELETE("/sandboxes/:id/pty/:sessionID", s.killPTY)
+
+ api.POST("/sandboxes/:id/timeout", s.setTimeout)
+ }
// Templates
api.POST("/templates", s.buildTemplate)
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index c6e9b64a..fddb115d 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -219,12 +219,11 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
}
resp := map[string]interface{}{
- "sandboxID": grpcResp.SandboxId,
- "connectURL": worker.HTTPAddr,
- "token": token,
- "status": grpcResp.Status,
- "region": region,
- "workerID": worker.ID,
+ "sandboxID": grpcResp.SandboxId,
+ "token": token,
+ "status": grpcResp.Status,
+ "region": region,
+ "workerID": worker.ID,
}
return c.JSON(http.StatusCreated, resp)
@@ -293,13 +292,6 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
return c.JSON(http.StatusOK, resp)
}
- // Look up worker address
- worker := s.workerRegistry.GetWorker(session.WorkerID)
- connectURL := ""
- if worker != nil {
- connectURL = worker.HTTPAddr
- }
-
// Issue a fresh token
var token string
if s.jwtIssuer != nil {
@@ -310,14 +302,13 @@ func (s *Server) getSandboxRemote(c echo.Context, sandboxID string) error {
}
resp := map[string]interface{}{
- "sandboxID": sandboxID,
- "connectURL": connectURL,
- "token": token,
- "status": session.Status,
- "region": session.Region,
- "workerID": session.WorkerID,
- "startedAt": session.StartedAt,
- "template": session.Template,
+ "sandboxID": sandboxID,
+ "token": token,
+ "status": session.Status,
+ "region": session.Region,
+ "workerID": session.WorkerID,
+ "startedAt": session.StartedAt,
+ "template": session.Template,
}
return c.JSON(http.StatusOK, resp)
@@ -452,12 +443,6 @@ func (s *Server) listSandboxesRemote(c echo.Context) error {
"startedAt": sess.StartedAt,
}
- // Attach connectURL from registry
- worker := s.workerRegistry.GetWorker(sess.WorkerID)
- if worker != nil {
- entry["connectURL"] = worker.HTTPAddr
- }
-
// Issue fresh JWT
if s.jwtIssuer != nil {
token, err := s.jwtIssuer.IssueSandboxToken(orgID, sess.SandboxID, sess.WorkerID, 24*time.Hour)
@@ -473,13 +458,6 @@ func (s *Server) listSandboxesRemote(c echo.Context) error {
}
func (s *Server) setTimeout(c echo.Context) error {
- // In server mode, timeout must be set directly on the worker via connectURL
- if s.workerRegistry != nil {
- return c.JSON(http.StatusBadRequest, map[string]string{
- "error": "timeout must be set directly on the worker via connectURL",
- })
- }
-
if s.router == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
diff --git a/internal/proxy/sandbox_api_proxy.go b/internal/proxy/sandbox_api_proxy.go
new file mode 100644
index 00000000..bdf58d2d
--- /dev/null
+++ b/internal/proxy/sandbox_api_proxy.go
@@ -0,0 +1,322 @@
+package proxy
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/controlplane"
+ "github.com/opensandbox/opensandbox/internal/db"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+// SandboxAPIProxy proxies data-plane HTTP/WebSocket requests from the control
+// plane to the worker that owns the sandbox. This enables ALB-based TLS
+// termination: clients talk to the control plane through the ALB, and the
+// control plane forwards exec/files/pty/agent requests to workers over the
+// internal VPC network.
+type SandboxAPIProxy struct {
+ store *db.Store
+ registry *controlplane.RedisWorkerRegistry
+ jwtIssuer *auth.JWTIssuer
+}
+
+// NewSandboxAPIProxy creates a new sandbox API proxy.
+func NewSandboxAPIProxy(store *db.Store, registry *controlplane.RedisWorkerRegistry, jwtIssuer *auth.JWTIssuer) *SandboxAPIProxy {
+ return &SandboxAPIProxy{
+ store: store,
+ registry: registry,
+ jwtIssuer: jwtIssuer,
+ }
+}
+
+// ProxyHandler forwards requests for a sandbox to the worker that owns it.
+// It extracts the sandbox ID from the path param ":id", looks up the worker,
+// mints a short-lived JWT, and proxies the request.
+func (p *SandboxAPIProxy) ProxyHandler(c echo.Context) error {
+ sandboxID := c.Param("id")
+ if sandboxID == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "sandbox ID required",
+ })
+ }
+
+ ctx := c.Request().Context()
+
+ // Look up which worker owns this sandbox
+ session, err := p.store.GetSandboxSession(ctx, sandboxID)
+ if err != nil {
+ return c.JSON(http.StatusNotFound, map[string]string{
+ "error": fmt.Sprintf("sandbox %s not found", sandboxID),
+ })
+ }
+
+ // If hibernated, wake on demand
+ if session.Status == "hibernated" {
+ worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
+ if err != nil {
+ log.Printf("sandbox-api-proxy: wake-on-request failed for sandbox %s: %v", sandboxID, err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: failed to wake: %v", sandboxID, err),
+ })
+ }
+ log.Printf("sandbox-api-proxy: wake-on-request succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)
+ return p.forward(c, sandboxID, workerURL, session.WorkerID)
+ }
+
+ if session.Status == "stopped" || session.Status == "error" {
+ return c.JSON(http.StatusGone, map[string]string{
+ "error": fmt.Sprintf("sandbox %s has been stopped", sandboxID),
+ })
+ }
+
+ // Look up worker address
+ worker := p.registry.GetWorker(session.WorkerID)
+ if worker == nil {
+ // Worker gone — try to recover from hibernation checkpoint
+ return p.tryRecoverOrFail(c, ctx, sandboxID, session)
+ }
+
+ if worker.HTTPAddr == "" {
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("worker %s has no HTTP address", session.WorkerID),
+ })
+ }
+
+ return p.forward(c, sandboxID, worker.HTTPAddr, session.WorkerID)
+}
+
+// forward proxies the request to the worker, adding a sandbox JWT for auth.
+func (p *SandboxAPIProxy) forward(c echo.Context, sandboxID, workerURL, workerID string) error {
+ // Mint a short-lived JWT for the worker
+ token := ""
+ if p.jwtIssuer != nil {
+ orgID, _ := auth.GetOrgID(c)
+ t, err := p.jwtIssuer.IssueSandboxToken(orgID, sandboxID, workerID, 5*time.Minute)
+ if err == nil {
+ token = t
+ }
+ }
+
+ if isWebSocketUpgrade(c.Request()) {
+ return p.doWebSocket(c, sandboxID, workerURL, token)
+ }
+ return p.doHTTP(c, sandboxID, workerURL, token)
+}
+
+// doHTTP reverse-proxies a normal HTTP request to the worker.
+func (p *SandboxAPIProxy) doHTTP(c echo.Context, sandboxID, workerURL, token string) error {
+ target, err := url.Parse(workerURL)
+ if err != nil {
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": "invalid worker URL",
+ })
+ }
+
+ proxy := httputil.NewSingleHostReverseProxy(target)
+ proxy.Transport = &http.Transport{
+ DialContext: (&net.Dialer{
+ Timeout: 5 * time.Second,
+ }).DialContext,
+ ResponseHeaderTimeout: 120 * time.Second, // exec/run can be long
+ MaxIdleConnsPerHost: 10,
+ }
+
+ var proxyErr error
+ proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
+ proxyErr = err
+ }
+
+ // Rewrite request to target worker, preserving the original path
+ proxy.Director = func(r *http.Request) {
+ r.URL.Scheme = target.Scheme
+ r.URL.Host = target.Host
+ // Path is already correct (/sandboxes/:id/...)
+ // Remove the /api prefix — worker routes don't have it
+ r.URL.Path = strings.TrimPrefix(r.URL.Path, "/api")
+ r.URL.RawQuery = c.Request().URL.RawQuery
+ r.Host = target.Host
+
+ // Set sandbox JWT auth for the worker
+ if token != "" {
+ r.Header.Set("Authorization", "Bearer "+token)
+ }
+ }
+
+ rec := &responseRecorder{
+ header: make(http.Header),
+ }
+ proxy.ServeHTTP(rec, c.Request())
+
+ if proxyErr != nil {
+ log.Printf("sandbox-api-proxy: error proxying sandbox %s to %s: %v", sandboxID, workerURL, proxyErr)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
+ })
+ }
+
+ rec.writeTo(c.Response())
+ return nil
+}
+
+// doWebSocket hijacks the connection and pipes it to the worker.
+func (p *SandboxAPIProxy) doWebSocket(c echo.Context, sandboxID, workerURL, token string) error {
+ target, err := url.Parse(workerURL)
+ if err != nil {
+ return c.JSON(http.StatusBadGateway, map[string]string{"error": "invalid worker URL"})
+ }
+
+ // Connect to the worker
+ workerAddr := target.Host
+ if !strings.Contains(workerAddr, ":") {
+ if target.Scheme == "https" {
+ workerAddr += ":443"
+ } else {
+ workerAddr += ":80"
+ }
+ }
+
+ upstream, err := net.DialTimeout("tcp", workerAddr, 5*time.Second)
+ if err != nil {
+ log.Printf("sandbox-api-proxy: websocket dial failed for sandbox %s (%s): %v", sandboxID, workerAddr, err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: upstream unavailable", sandboxID),
+ })
+ }
+ defer upstream.Close()
+
+ // Hijack client connection
+ hijacker, ok := c.Response().Writer.(http.Hijacker)
+ if !ok {
+ return c.JSON(http.StatusInternalServerError, map[string]string{
+ "error": "websocket hijack not supported",
+ })
+ }
+
+ clientConn, clientBuf, err := hijacker.Hijack()
+ if err != nil {
+ log.Printf("sandbox-api-proxy: websocket hijack failed for sandbox %s: %v", sandboxID, err)
+ return err
+ }
+ defer clientConn.Close()
+
+ // Modify the request: strip /api prefix and inject JWT auth
+ req := c.Request()
+ req.URL.Path = strings.TrimPrefix(req.URL.Path, "/api")
+ req.Host = target.Host
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+
+ // Forward the modified request to the upstream worker
+ if err := req.Write(upstream); err != nil {
+ log.Printf("sandbox-api-proxy: websocket write request failed for sandbox %s: %v", sandboxID, err)
+ return nil
+ }
+
+ // Flush any buffered client data
+ if clientBuf.Reader.Buffered() > 0 {
+ buffered := make([]byte, clientBuf.Reader.Buffered())
+ n, _ := clientBuf.Read(buffered)
+ if n > 0 {
+ upstream.Write(buffered[:n])
+ }
+ }
+
+ // Bidirectional pipe
+ var wg sync.WaitGroup
+ wg.Add(2)
+
+ go func() {
+ defer wg.Done()
+ io.Copy(clientConn, upstream)
+ if tc, ok := clientConn.(*net.TCPConn); ok {
+ tc.CloseWrite()
+ }
+ }()
+
+ go func() {
+ defer wg.Done()
+ io.Copy(upstream, clientConn)
+ if tc, ok := upstream.(*net.TCPConn); ok {
+ tc.CloseWrite()
+ }
+ }()
+
+ wg.Wait()
+ return nil
+}
+
+// tryRecoverOrFail handles the case where a sandbox's worker is gone.
+func (p *SandboxAPIProxy) tryRecoverOrFail(c echo.Context, ctx context.Context, sandboxID string, session *db.SandboxSession) error {
+ checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)
+ if err == nil && checkpoint != nil {
+ log.Printf("sandbox-api-proxy: sandbox %s has active hibernation, attempting recovery wake", sandboxID)
+ worker, workerURL, err := p.wakeHibernatedSandbox(ctx, sandboxID)
+ if err != nil {
+ log.Printf("sandbox-api-proxy: recovery wake failed for sandbox %s: %v", sandboxID, err)
+ return c.JSON(http.StatusBadGateway, map[string]string{
+ "error": fmt.Sprintf("sandbox %s: worker unavailable", sandboxID),
+ })
+ }
+
+ log.Printf("sandbox-api-proxy: recovery wake succeeded for sandbox %s → worker %s (%s)", sandboxID, worker.ID, workerURL)
+ return p.forward(c, sandboxID, workerURL, worker.ID)
+ }
+
+ // No hibernation — sandbox is truly gone
+ log.Printf("sandbox-api-proxy: sandbox %s has no hibernation and worker is gone, marking stopped", sandboxID)
+ errMsg := "worker lost, sandbox not recoverable"
+ _ = p.store.UpdateSandboxSessionStatus(ctx, sandboxID, "stopped", &errMsg)
+
+ return c.JSON(http.StatusGone, map[string]string{
+ "error": fmt.Sprintf("sandbox %s is no longer available (worker was lost)", sandboxID),
+ })
+}
+
+// wakeHibernatedSandbox wakes a hibernated sandbox on the least loaded worker.
+func (p *SandboxAPIProxy) wakeHibernatedSandbox(ctx context.Context, sandboxID string) (*controlplane.WorkerEntry, string, error) {
+ checkpoint, err := p.store.GetActiveHibernation(ctx, sandboxID)
+ if err != nil {
+ return nil, "", fmt.Errorf("no active hibernation: %w", err)
+ }
+
+ region := checkpoint.Region
+ worker, grpcClient, err := p.registry.GetLeastLoadedWorker(region)
+ if err != nil {
+ return nil, "", fmt.Errorf("no workers available in region %s: %w", region, err)
+ }
+
+ log.Printf("sandbox-api-proxy: waking sandbox %s on worker %s (region=%s)", sandboxID, worker.ID, region)
+
+ grpcCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
+ defer cancel()
+
+ _, err = grpcClient.WakeSandbox(grpcCtx, &pb.WakeSandboxRequest{
+ SandboxId: sandboxID,
+ CheckpointKey: checkpoint.HibernationKey,
+ Timeout: 300,
+ })
+ if err != nil {
+ return nil, "", fmt.Errorf("gRPC WakeSandbox failed: %w", err)
+ }
+
+ _ = p.store.MarkHibernationRestored(ctx, sandboxID)
+ _ = p.store.UpdateSandboxSessionForWake(ctx, sandboxID, worker.ID)
+
+ if worker.HTTPAddr == "" {
+ return nil, "", fmt.Errorf("worker %s has no HTTP address", worker.ID)
+ }
+
+ return worker, worker.HTTPAddr, nil
+}
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index e4e316f0..e7e8b613 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -2,7 +2,6 @@ package worker
import (
"net/http"
- "strings"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
@@ -57,23 +56,6 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
return c.JSON(http.StatusOK, map[string]string{"status": "ok", "role": "worker"})
})
- // Caddy on-demand TLS check — validates that a domain is a valid sandbox subdomain
- e.GET("/caddy/check", func(c echo.Context) error {
- domain := c.QueryParam("domain")
- if domain == "" {
- return c.String(http.StatusForbidden, "missing domain")
- }
- suffix := "." + s.sandboxDomain
- if !strings.HasSuffix(domain, suffix) {
- return c.String(http.StatusForbidden, "invalid domain")
- }
- sub := strings.TrimSuffix(domain, suffix)
- if sub == "" || strings.Contains(sub, ".") {
- return c.String(http.StatusForbidden, "invalid subdomain")
- }
- return c.String(http.StatusOK, "ok")
- })
-
// All sandbox routes require JWT auth
api := e.Group("")
api.Use(auth.SandboxJWTMiddleware(jwtIssuer))