Skip to content

An open-source, faster Devin alternative

TypeScript

feat(guest): add the /oc/* front door to microvm-hooks — envs, exec, workspace export/import, PTY and exec-session streaming, and sealed-secret application, so the control plane reaches the guest over plain JSON instead of a brokered tunnel

Brian Reardon4dc004ceecc0
diff --git a/cmd/microvm-hooks/main.go b/cmd/microvm-hooks/main.go
index 411c8e13..5ba0396b 100644
--- a/cmd/microvm-hooks/main.go
+++ b/cmd/microvm-hooks/main.go
@@ -93,9 +93,13 @@ const (
// written, a box answering /healthz in 90ms with agentUp=true was simultaneously
// logged by the control plane as tunnel-less with re-dial timing out at 30s.
//
-// The cost is deliberate and total: no streaming, no PTY, no sessions, no file
-// transfer. One command, buffered output, one reply. Anything richer belongs on
-// the agent path.
+// One command, buffered output, one reply — and deliberately nothing more, so
+// that the path a customer's exec takes stays this short.
+//
+// The richer operations do NOT need the tunnel either, which was not obvious
+// when this was written: see oc.go, where files and stats reach the agent over
+// loopback gRPC and cross the proxy as plain JSON. What still belongs on the
+// agent path is only what needs a bidirectional stream — PTY and exec sessions.
// The field names mirror types.ProcessConfig so the control plane forwards a
// customer's exec request without reshaping it.
type runCmdRequest struct {
@@ -268,6 +272,13 @@ func main() {
mux.HandleFunc(claimPath, s.handleClaim)
mux.HandleFunc(claimAndRunPath, s.handleClaimAndRun)
+ // The /oc front door: the four paths above under their new prefix, plus
+ // files, stats, reboot and customer-port proxying. See oc.go — all of it
+ // reaches the agent over LOOPBACK gRPC, which is why it can offer the full
+ // agent API on a path that deliberately cannot carry gRPC through the
+ // proxy. Registered before the catch-all for the same longest-match reason.
+ s.registerOC(mux)
+
// Everything that is not a hook is forwarded to osb-agent.
//
// This exists because Lambda's proxy forwards guest traffic ONLY to the port
@@ -462,17 +473,51 @@ func runCmd(reqCtx context.Context, req runCmdRequest) (runCmdResponse, error) {
name, args = req.Cmd, req.Args
}
cmd := exec.CommandContext(ctx, name, args...)
+
+ // RUN AS THE SANDBOX USER, NOT AS US.
+ //
+ // This process is PID 1 and therefore root. Without this the customer's
+ // commands inherited that — measured on dev before this existed:
+ //
+ // uid=0(root) gid=0(root) HOME=/root pwd=/
+ //
+ // against uid=1000 in /home/sandbox on the QEMU fleet and on the agent
+ // path, which sets the same credential (internal/agent/exec.go).
+ //
+ // Three things broke because of it, and none of them announced itself:
+ //
+ // the sandbox was root a privilege boundary the QEMU fleet has and
+ // this runtime silently did not
+ // secrets were readable the in-guest proxy keeps plaintext in THIS
+ // process's memory, which is safe only because
+ // the customer is unprivileged (oc_secrets.go)
+ // checkpoints missed work cwd was /, and the workspace archive covers
+ // /home/sandbox — so anything written to a
+ // relative path was outside every checkpoint
+ // Only root can hand a child a different uid. In the guest this process IS
+ // root (PID 1), so this always applies there; the check exists because the
+ // unit tests run it as an ordinary user, where the setuid would fail the
+ // fork outright and turn every test into "operation not permitted".
+ if os.Geteuid() == 0 {
+ cmd.SysProcAttr = &syscall.SysProcAttr{
+ Credential: &syscall.Credential{Uid: sandboxUID, Gid: sandboxGID},
+ }
+ }
cmd.Dir = req.Cwd
- if len(req.Env) > 0 {
- // Appended to the guest's environment, not substituted for it: replacing
- // it would drop PATH and HOME, so every command that named a binary
- // rather than a path would stop resolving.
- env := os.Environ()
- for k, v := range req.Env {
- env = append(env, k+"="+v)
+ if cmd.Dir == "" {
+ // Not "" (which inherits /): a relative path from a customer has to
+ // land in the workspace, both because that is where they expect it and
+ // because that is what a checkpoint captures. Guarded on existence so
+ // the tests, which have no /home/sandbox, still run.
+ if st, err := os.Stat(sandboxHomeDir); err == nil && st.IsDir() {
+ cmd.Dir = sandboxHomeDir
}
- cmd.Env = env
}
+ // The guest's environment, then the sandbox's, then this request's — see
+ // buildEnv. Never nil now: the user identity below always has to be stated,
+ // because os.Environ() is ROOT's and would otherwise tell the customer's
+ // shell that HOME is /root.
+ cmd.Env = buildEnv(req.Env)
var stdout, stderr cappedBuffer
stdout.limit, stderr.limit = runCmdMaxOutput, runCmdMaxOutput
cmd.Stdout, cmd.Stderr = &stdout, &stderr
diff --git a/cmd/microvm-hooks/oc.go b/cmd/microvm-hooks/oc.go
new file mode 100644
index 00000000..5b37c0c8
--- /dev/null
+++ b/cmd/microvm-hooks/oc.go
@@ -0,0 +1,644 @@
+package main
+
+// oc.go — the guest's front door.
+//
+// Lambda's proxy forwards guest traffic ONLY to the port declared in the
+// image's hook configuration (8080). A second listener is unreachable: the
+// agent listens on 8081 and requests to it come back 502 while the identical
+// request to 8080 arrives (see the note on agentAddr). So everything a customer
+// can reach — exec, files, stats, reboot, and their own HTTP servers — has to
+// enter here and be fanned out inside the guest.
+//
+// WHY THIS CAN EXIST AT ALL. The direct path deliberately gave up files, stats
+// and everything else because gRPC reports status in HTTP/2 trailers and the
+// proxy strips them. But that is a property of the PROXY HOP, not of the agent:
+// inside the guest, loopback gRPC to 127.0.0.1:8081 works perfectly, and
+// handleValidate has been driving real Exec RPCs over it since the image was
+// first built. So the trailer problem is bypassed by never carrying gRPC across
+// the proxy — the caller speaks plain JSON to this process, and this process
+// speaks gRPC to the agent over loopback.
+//
+// The result is that the direct path keeps its one-request exec and still
+// reaches the agent's full API, with no tunnel, no WebSocket, no persistent
+// channel and no keepalive. None of these handlers is on the create or exec hot
+// path: exec is still runCmdPath, answered without touching any of this.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httputil"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/credentials/insecure"
+ "google.golang.org/grpc/status"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+// The /oc prefix. The older /osb paths stay registered as aliases (see
+// registerOC) because the running fleet and the deployed control plane both
+// speak them, and a rename that requires a lockstep image + control-plane
+// deploy buys nothing. New work goes here; /osb is retired once no deployed
+// control plane sends it.
+const (
+ ocPrefix = "/oc/"
+
+ ocRunPath = ocPrefix + "run"
+ ocClaimPath = ocPrefix + "claim"
+ ocClaimRunPath = ocPrefix + "claim-and-run"
+ ocAgentGRPCPath = ocPrefix + "agent-grpc"
+
+ ocFSPrefix = ocPrefix + "fs/"
+ ocStatsPath = ocPrefix + "stats"
+ ocRebootPath = ocPrefix + "reboot"
+
+ // ocPortPrefix proxies to a port the customer is listening on inside the
+ // guest: /oc/port/3000/some/path reaches 127.0.0.1:3000/some/path.
+ ocPortPrefix = ocPrefix + "port/"
+)
+
+// fsMaxInline bounds a buffered read or write. Anything larger belongs on the
+// streaming endpoints, which never hold the whole file in memory — on a box
+// this small, one careless 2 GB read would OOM the guest and take the agent
+// with it.
+const fsMaxInline = 32 << 20 // 32 MiB
+
+// registerOC wires the front door onto the hook mux.
+//
+// Registered on BOTH prefixes for the four paths that already exist, so an
+// image carrying this code serves a control plane that speaks either. ServeMux
+// picks the longest matching pattern, so every one of these wins over the
+// catch-all bridge to the agent — without an explicit entry a JSON POST would
+// be forwarded to the agent's gRPC listener, which answers 415 and no
+// explanation.
+func (s *server) registerOC(mux *http.ServeMux) {
+ // Aliases for the existing surface.
+ mux.HandleFunc(ocRunPath, s.handleRunCmd)
+ mux.HandleFunc(ocClaimPath, s.handleClaim)
+ mux.HandleFunc(ocClaimRunPath, s.handleClaimAndRun)
+ mux.HandleFunc(ocAgentGRPCPath, s.handleAgentTunnel)
+
+ // Filesystem, bridged to the agent over loopback gRPC.
+ mux.HandleFunc(ocFSPrefix+"read", s.ocFSRead)
+ mux.HandleFunc(ocFSPrefix+"write", s.ocFSWrite)
+ mux.HandleFunc(ocFSPrefix+"list", s.ocFSList)
+ mux.HandleFunc(ocFSPrefix+"mkdir", s.ocFSMkdir)
+ mux.HandleFunc(ocFSPrefix+"rm", s.ocFSRemove)
+ mux.HandleFunc(ocFSPrefix+"exists", s.ocFSExists)
+ mux.HandleFunc(ocFSPrefix+"stat", s.ocFSStat)
+ mux.HandleFunc(ocFSPrefix+"download", s.ocFSDownload)
+ mux.HandleFunc(ocFSPrefix+"upload", s.ocFSUpload)
+
+ mux.HandleFunc(ocStatsPath, s.ocStats)
+ mux.HandleFunc(ocEnvsPath, s.ocSetEnvs)
+ mux.HandleFunc(ocSecretsPath, s.ocSetSecrets)
+ mux.HandleFunc(ocSecretsUpdatePath, s.ocUpdateSecret)
+ // PTY, streaming exec and the workspace archive. Separated only because
+ // they are streams rather than request/reply — see oc_stream.go.
+ s.registerOCStream(mux)
+ mux.HandleFunc(ocRebootPath, s.ocReboot)
+ mux.HandleFunc(ocPortPrefix, s.ocPort)
+}
+
+// ── agent client ────────────────────────────────────────────────────────────
+
+// agentConn is one lazily-dialled loopback gRPC connection, shared by every
+// handler here.
+//
+// Lazy, not created at startup, because this process starts during the image
+// BUILD and every box resumes from a snapshot taken then: a connection
+// established before the snapshot would be restored into every box that ever
+// runs, having been idle across a snapshot boundary. Dialling on first use puts
+// it safely after /resume.
+//
+// Shared, not per-request, because a file op should not pay a handshake — and
+// reset on failure, because the agent can be restarted underneath us by
+// /oc/reboot, which invalidates whatever we were holding.
+var agentConn struct {
+ mu sync.Mutex
+ conn *grpc.ClientConn
+}
+
+func agentClient() (pb.SandboxAgentClient, error) {
+ agentConn.mu.Lock()
+ defer agentConn.mu.Unlock()
+ if agentConn.conn == nil {
+ c, err := grpc.NewClient(agentDialAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return nil, fmt.Errorf("dial agent: %w", err)
+ }
+ agentConn.conn = c
+ }
+ return pb.NewSandboxAgentClient(agentConn.conn), nil
+}
+
+// resetAgentClient drops the shared connection so the next caller redials.
+// Called when the agent is deliberately restarted.
+func resetAgentClient() {
+ agentConn.mu.Lock()
+ defer agentConn.mu.Unlock()
+ if agentConn.conn != nil {
+ _ = agentConn.conn.Close()
+ agentConn.conn = nil
+ }
+}
+
+// ── plumbing ────────────────────────────────────────────────────────────────
+
+// ocRequest is the request body every buffered filesystem endpoint accepts.
+// One shape for all of them: the control plane sends the same JSON regardless
+// of the operation, and the fields it does not need are simply absent.
+type ocRequest struct {
+ Path string `json:"path"`
+ Content []byte `json:"content,omitempty"`
+ Mode uint32 `json:"mode,omitempty"`
+}
+
+// decode reads a JSON body, bounded. Returns false having already answered.
+func decode(w http.ResponseWriter, r *http.Request, dst any) bool {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return false
+ }
+ if err := json.NewDecoder(io.LimitReader(r.Body, fsMaxInline)).Decode(dst); err != nil {
+ http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
+ return false
+ }
+ return true
+}
+
+// fail turns an agent error into an HTTP status.
+//
+// The mapping is the point: the control plane cannot see gRPC codes from out
+// here, so a missing file and a broken agent would otherwise be the same 500
+// and the SDK would retry the one that will never succeed. NotFound in
+// particular has to survive — "file does not exist" is a normal answer to a
+// read, not a fault.
+func fail(w http.ResponseWriter, op string, err error) {
+ code := http.StatusInternalServerError
+ switch status.Code(err) {
+ case codes.NotFound:
+ code = http.StatusNotFound
+ case codes.InvalidArgument:
+ code = http.StatusBadRequest
+ case codes.PermissionDenied:
+ code = http.StatusForbidden
+ case codes.AlreadyExists:
+ code = http.StatusConflict
+ case codes.Unavailable:
+ // The agent is not answering. Retryable, and distinct from a bad
+ // request — this is the code that says "ask again", so a transient
+ // agent restart does not surface to a customer as a failed write.
+ code = http.StatusServiceUnavailable
+ case codes.ResourceExhausted:
+ code = http.StatusInsufficientStorage
+ }
+ log.Printf("microvm-hooks: %s: %v", op, err)
+ http.Error(w, err.Error(), code)
+}
+
+// withAgent runs fn against the agent, answering the request on any failure to
+// obtain a client. Every filesystem handler is this plus one RPC.
+func withAgent(w http.ResponseWriter, op string, fn func(pb.SandboxAgentClient) error) {
+ c, err := agentClient()
+ if err != nil {
+ fail(w, op, status.Error(codes.Unavailable, err.Error()))
+ return
+ }
+ if err := fn(c); err != nil {
+ fail(w, op, err)
+ }
+}
+
+// fsTimeout bounds a buffered filesystem call. Generous relative to a local
+// file operation, so only a genuinely wedged agent trips it.
+const fsTimeout = 60 * time.Second
+
+// ── filesystem ──────────────────────────────────────────────────────────────
+
+func (s *server) ocFSRead(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/read", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ resp, err := c.ReadFile(ctx, &pb.ReadFileRequest{Path: req.Path})
+ if err != nil {
+ return err
+ }
+ // Bytes, not a string: the control plane's ReadFile returns a string,
+ // but encoding/json handles []byte as base64, which round-trips binary
+ // content that a string field would corrupt.
+ writeJSON(w, http.StatusOK, map[string]any{"content": resp.Content})
+ return nil
+ })
+}
+
+func (s *server) ocFSWrite(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/write", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ _, err := c.WriteFile(ctx, &pb.WriteFileRequest{
+ Path: req.Path, Content: req.Content, Mode: req.Mode,
+ })
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+func (s *server) ocFSList(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/list", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ resp, err := c.ListDir(ctx, &pb.ListDirRequest{Path: req.Path})
+ if err != nil {
+ return err
+ }
+ // Shaped as types.EntryInfo so the control plane can unmarshal it
+ // directly rather than translating a second wire format.
+ out := make([]map[string]any, 0, len(resp.Entries))
+ for _, e := range resp.Entries {
+ out = append(out, map[string]any{
+ "name": e.Name, "isDir": e.IsDir, "size": e.Size, "path": e.Path,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"entries": out})
+ return nil
+ })
+}
+
+func (s *server) ocFSMkdir(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/mkdir", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ if _, err := c.MakeDir(ctx, &pb.MakeDirRequest{Path: req.Path}); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+func (s *server) ocFSRemove(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/rm", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ if _, err := c.Remove(ctx, &pb.RemoveRequest{Path: req.Path}); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+func (s *server) ocFSExists(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/exists", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ resp, err := c.Exists(ctx, &pb.ExistsRequest{Path: req.Path})
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"exists": resp.Exists})
+ return nil
+ })
+}
+
+func (s *server) ocFSStat(w http.ResponseWriter, r *http.Request) {
+ var req ocRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "fs/stat", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), fsTimeout)
+ defer cancel()
+ resp, err := c.Stat(ctx, &pb.StatRequest{Path: req.Path})
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{
+ "name": resp.Name, "isDir": resp.IsDir, "size": resp.Size,
+ "mode": resp.Mode, "modTime": resp.ModTime, "path": resp.Path,
+ })
+ return nil
+ })
+}
+
+// ── streaming filesystem ────────────────────────────────────────────────────
+//
+// Streamed as ordinary HTTP bodies. Only TRAILERS die on the proxy hop; a body
+// passes through untouched, which is what makes a large file transfer possible
+// on this path at all. Neither of these buffers the file.
+
+// ocFSDownload streams a file out. GET /oc/fs/download?path=...
+func (s *server) ocFSDownload(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ path := r.URL.Query().Get("path")
+ if path == "" {
+ http.Error(w, "path is required", http.StatusBadRequest)
+ return
+ }
+ withAgent(w, "fs/download", func(c pb.SandboxAgentClient) error {
+ stream, err := c.ReadFileStream(r.Context(), &pb.ReadFileStreamRequest{Path: path})
+ if err != nil {
+ return err
+ }
+ // Headers are committed on the FIRST chunk, not before: an error on the
+ // opening read is a real status code (404 for a missing file), whereas
+ // writing the header first would force every failure to look like a
+ // truncated 200.
+ wrote := false
+ for {
+ chunk, err := stream.Recv()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ if !wrote {
+ return err
+ }
+ // Mid-stream failure. The status is already 200 and the body is
+ // short; nothing can be signalled except to stop and log, which
+ // is why the length header below matters to the caller.
+ log.Printf("microvm-hooks: fs/download %s: truncated: %v", path, err)
+ return nil
+ }
+ if !wrote {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ if chunk.TotalSize > 0 {
+ w.Header().Set("Content-Length", strconv.FormatInt(chunk.TotalSize, 10))
+ }
+ w.WriteHeader(http.StatusOK)
+ wrote = true
+ }
+ if _, err := w.Write(chunk.Data); err != nil {
+ return nil // client hung up
+ }
+ }
+ if !wrote {
+ // A zero-byte file still needs a response.
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Length", "0")
+ w.WriteHeader(http.StatusOK)
+ }
+ return nil
+ })
+}
+
+// ocFSUpload streams a file in. PUT /oc/fs/upload?path=...&mode=...
+func (s *server) ocFSUpload(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut && r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ path := r.URL.Query().Get("path")
+ if path == "" {
+ http.Error(w, "path is required", http.StatusBadRequest)
+ return
+ }
+ mode := uint32(0)
+ if m := r.URL.Query().Get("mode"); m != "" {
+ if parsed, err := strconv.ParseUint(m, 8, 32); err == nil {
+ mode = uint32(parsed)
+ }
+ }
+ withAgent(w, "fs/upload", func(c pb.SandboxAgentClient) error {
+ stream, err := c.WriteFileStream(r.Context())
+ if err != nil {
+ return err
+ }
+ // path and mode ride on the first message only, per the proto.
+ buf := make([]byte, 256<<10)
+ first := true
+ for {
+ n, rerr := r.Body.Read(buf)
+ if n > 0 {
+ msg := &pb.WriteFileStreamRequest{Data: buf[:n]}
+ if first {
+ msg.Path, msg.Mode, first = path, mode, false
+ }
+ if err := stream.Send(msg); err != nil {
+ return err
+ }
+ }
+ if errors.Is(rerr, io.EOF) {
+ break
+ }
+ if rerr != nil {
+ _, _ = stream.CloseAndRecv()
+ return status.Error(codes.Canceled, "upload body: "+rerr.Error())
+ }
+ }
+ if first {
+ // Empty body: the agent has still not been told the path, so send
+ // one empty message carrying it or the file is never created.
+ if err := stream.Send(&pb.WriteFileStreamRequest{Path: path, Mode: mode}); err != nil {
+ return err
+ }
+ }
+ resp, err := stream.CloseAndRecv()
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"bytesWritten": resp.BytesWritten})
+ return nil
+ })
+}
+
+// ── stats ───────────────────────────────────────────────────────────────────
+
+func (s *server) ocStats(w http.ResponseWriter, r *http.Request) {
+ withAgent(w, "stats", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
+ defer cancel()
+ resp, err := c.Stats(ctx, &pb.StatsRequest{})
+ if err != nil {
+ return err
+ }
+ // Field names match sandbox.SandboxStats so the control plane
+ // unmarshals straight into it.
+ writeJSON(w, http.StatusOK, map[string]any{
+ "cpuPercent": resp.CpuPercent,
+ "memUsage": resp.MemUsage,
+ "memLimit": resp.MemLimit,
+ "netInput": resp.NetInput,
+ "netOutput": resp.NetOutput,
+ "pids": resp.Pids,
+ })
+ return nil
+ })
+}
+
+// ── reboot ──────────────────────────────────────────────────────────────────
+
+// ocReboot restarts the sandbox's workload in place.
+//
+// NOT A KERNEL RESTART, and the difference is worth stating because it is the
+// one place this runtime cannot match QEMU. There is no way to restart a
+// MicroVM's guest kernel: the box is a snapshot restored by the service, and
+// the only "restart" the service offers is launching a different box. The old
+// agent-tunnel path implemented reboot as exactly that — export the workspace,
+// launch a replacement, import, terminate the original — which costs a ~3.3s
+// floor plus the size of the workspace, and silently loses anything the
+// customer installed outside /home/sandbox.
+//
+// This does the thing customers actually want from a reboot — nothing of mine
+// is running any more, and the tools are back to a known state — without moving
+// any data: kill everything the sandbox user owns, then restart the agent, so
+// no process, no shell state and no listening port survives. The disk is
+// untouched, so /home/sandbox and anything installed at runtime both persist,
+// which is MORE than the old path preserved rather than less.
+func (s *server) ocReboot(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ // The customer's processes, killed by walking /proc rather than shelling
+ // out to pkill.
+ //
+ // pkill IS NOT IN THIS IMAGE. The base is al2023-minimal and the Dockerfile
+ // installs nodejs, python3, tar, gzip, ca-certificates and shadow-utils —
+ // procps-ng is not among them, so `pkill` (and `ps`, and `pgrep`) exit with
+ // "executable file not found". The earlier version of this handler swallowed
+ // that as a non-fatal error and went on to report a successful reboot that
+ // had killed nothing at all. Found on dev by asking a rebooted sandbox
+ // whether its processes were still running.
+ //
+ // Reading /proc has no such dependency, and is what pkill would have done.
+ if n := killSandboxProcesses(); n > 0 {
+ log.Printf("microvm-hooks: reboot: killed %d sandbox process(es)", n)
+ }
+
+ // Then the agent, so its own state — env set via SetEnvs, open PTYs, exec
+ // sessions — goes too. Restarting it is what makes this a reboot rather
+ // than a kill.
+ s.mu.Lock()
+ cmd := s.agentCmd
+ s.mu.Unlock()
+ if cmd != nil && cmd.Process != nil {
+ _ = cmd.Process.Kill()
+ }
+ // Drop the pooled connection before the new agent comes up; it points at a
+ // listener that no longer exists.
+ resetAgentClient()
+
+ // cmd.Wait is already owned by the goroutine in startAgent, so the exit is
+ // reaped there. Give the listener a moment to actually go away before
+ // rebinding, or the new agent races the old one for the port.
+ deadline := time.Now().Add(10 * time.Second)
+ for agentUp() && time.Now().Before(deadline) {
+ time.Sleep(50 * time.Millisecond)
+ }
+
+ if err := s.startAgent(); err != nil {
+ log.Printf("microvm-hooks: reboot: restart agent: %v", err)
+ http.Error(w, "reboot: agent did not restart: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ for !agentUp() && time.Now().Before(deadline) {
+ time.Sleep(50 * time.Millisecond)
+ }
+ if !agentUp() {
+ // Say so rather than reporting a reboot that left the box unusable.
+ http.Error(w, "reboot: agent did not come back", http.StatusInternalServerError)
+ return
+ }
+ // The agent is new and its env map is empty. Without this, PTY and exec
+ // sessions after a reboot see none of the sandbox's variables while
+ // /oc/run commands still do — see reapplyEnvsToAgent.
+ reapplyEnvsToAgent(r.Context())
+
+ log.Printf("microvm-hooks: reboot ok")
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+// ── customer ports ──────────────────────────────────────────────────────────
+
+// ocPort proxies to a port the customer is listening on inside the guest.
+//
+// /oc/port/3000/api/users -> 127.0.0.1:3000/api/users
+//
+// This is the only way a customer's own server is reachable. Lambda's proxy
+// forwards solely to the hook port, so a preview URL cannot simply name the
+// customer's port the way it does on QEMU, where the host publishes one — the
+// fan-out has to happen in here.
+//
+// WebSocket and SSE both work: the reverse proxy passes an upgrade through, and
+// FlushInterval -1 stops it buffering an event stream into silence.
+func (s *server) ocPort(w http.ResponseWriter, r *http.Request) {
+ rest := strings.TrimPrefix(r.URL.Path, ocPortPrefix)
+ portStr, tail, _ := strings.Cut(rest, "/")
+ port, err := strconv.Atoi(portStr)
+ if err != nil || port < 1 || port > 65535 {
+ http.Error(w, "bad port in path: expected /oc/port/<port>/...", http.StatusBadRequest)
+ return
+ }
+ // Refuse our own ports. Proxying to the hook port is an infinite loop that
+ // takes the box's only listener down with it, and the agent's port is not
+ // the customer's to reach — it is the whole trust boundary of this design.
+ if port == 8080 || port == 8081 {
+ http.Error(w, "port is reserved", http.StatusForbidden)
+ return
+ }
+
+ target := &url.URL{Scheme: "http", Host: "127.0.0.1:" + portStr}
+ proxy := &httputil.ReverseProxy{
+ Rewrite: func(pr *httputil.ProxyRequest) {
+ pr.Out.URL.Scheme = target.Scheme
+ pr.Out.URL.Host = target.Host
+ pr.Out.URL.Path = "/" + tail
+ pr.Out.URL.RawQuery = r.URL.RawQuery
+ pr.Out.Host = target.Host
+ pr.SetXForwarded()
+ },
+ FlushInterval: -1,
+ ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
+ // A connection refused here almost always means the customer's
+ // server is not listening yet, which is a normal state during
+ // startup and worth distinguishing from a broken sandbox.
+ log.Printf("microvm-hooks: port %d: %v", port, err)
+ http.Error(w, fmt.Sprintf("nothing is listening on port %d", port), http.StatusBadGateway)
+ },
+ }
+ proxy.ServeHTTP(w, r)
+}
diff --git a/cmd/microvm-hooks/oc_envs.go b/cmd/microvm-hooks/oc_envs.go
new file mode 100644
index 00000000..81442de7
--- /dev/null
+++ b/cmd/microvm-hooks/oc_envs.go
@@ -0,0 +1,171 @@
+package main
+
+// oc_envs.go — sandbox-level environment variables.
+//
+// A create can carry `envs`, and on the QEMU fleet those are set once and seen
+// by everything the sandbox subsequently runs. On this runtime they were
+// silently DROPPED: the backend's Claim passed only template and size to the
+// manager, so `create({envs})` returned 200 and did nothing. No error, no log —
+// the customer's program just saw an unset variable.
+//
+// SET IN TWO PLACES, and it has to be both, which is the part that is easy to
+// get wrong. Commands reach the guest by two different routes:
+//
+// /oc/run runCmd builds the process HERE, in this process. The
+// agent's own env map is invisible to it.
+// PTY, sessions go through the agent, which applies its sandboxEnvs.
+//
+// Setting only the agent's would leave plain exec — the overwhelmingly common
+// case — without them. Setting only ours would leave terminals without them.
+// Both, or the sandbox's environment depends on how you happen to run a
+// command, which is the kind of inconsistency that costs an afternoon to
+// diagnose.
+
+import (
+ "context"
+ "log"
+ "net/http"
+ "os"
+ "sync"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+const (
+ ocEnvsPath = ocPrefix + "envs"
+
+ // The identity customer commands run as. Matches internal/agent/exec.go —
+ // the two run commands in the same sandbox and must agree about who owns
+ // the files they create.
+ sandboxUID = 1000
+ sandboxGID = 1000
+ sandboxUserName = "sandbox"
+ sandboxHomeDir = "/home/sandbox"
+)
+
+// sandboxEnvs is the environment applied to everything this process runs.
+//
+// Guarded because it is written by a create and read by every exec, and those
+// race by construction — a create returns as soon as the sandbox is usable, and
+// nothing stops the customer's first command arriving while the write is still
+// in flight.
+var sandboxEnvs struct {
+ mu sync.RWMutex
+ m map[string]string
+}
+
+// envsSnapshot returns a copy for merging into one command.
+func envsSnapshot() map[string]string {
+ sandboxEnvs.mu.RLock()
+ defer sandboxEnvs.mu.RUnlock()
+ if len(sandboxEnvs.m) == 0 {
+ return nil
+ }
+ out := make(map[string]string, len(sandboxEnvs.m))
+ for k, v := range sandboxEnvs.m {
+ out[k] = v
+ }
+ return out
+}
+
+// buildEnv resolves the environment for one command.
+//
+// Three layers, and the order is the contract: the guest's own environment
+// first (PATH, HOME — replacing rather than extending it would stop every
+// command that names a binary instead of a path from resolving), then the
+// sandbox's, then the request's. Per-exec envs win, so a caller can override a
+// sandbox-level value for one command without changing it for the sandbox.
+//
+// Never returns nil: even with no envs set at all, the sandbox user's identity
+// has to be stamped over root's.
+func buildEnv(reqEnv map[string]string) []string {
+ sandbox := envsSnapshot()
+ env := os.Environ()
+ // os.Environ() is ROOT's — this process is PID 1. Commands run as the
+ // sandbox user (see runCmd), so the identity has to be restated or the
+ // customer's shell is told HOME=/root, which it cannot write, and `cd ~`
+ // lands somewhere they have no access to. The agent does the same thing
+ // for the same reason (internal/agent/exec.go).
+ env = append(env,
+ "HOME="+sandboxHomeDir,
+ "USER="+sandboxUserName,
+ "LOGNAME="+sandboxUserName,
+ )
+ for k, v := range sandbox {
+ env = append(env, k+"="+v)
+ }
+ // Appended after the sandbox's, and later entries win in execve, so a
+ // per-request value overrides a sandbox-level one of the same name.
+ for k, v := range reqEnv {
+ env = append(env, k+"="+v)
+ }
+ return env
+}
+
+// applySandboxEnvs records the environment this process applies to /oc/run.
+//
+// Idempotent and total: it REPLACES whatever was there rather than merging, so
+// a caller can clear a variable by omitting it.
+func applySandboxEnvs(m map[string]string) {
+ sandboxEnvs.mu.Lock()
+ sandboxEnvs.m = m
+ sandboxEnvs.mu.Unlock()
+}
+
+// pushEnvsToAgent gives the agent the same environment, for the paths that run
+// commands through it rather than through runCmd.
+func pushEnvsToAgent(ctx context.Context, m map[string]string) error {
+ c, err := agentClient()
+ if err != nil {
+ return err
+ }
+ _, err = c.SetEnvs(ctx, &pb.SetEnvsRequest{Envs: m})
+ return err
+}
+
+// reapplyEnvsToAgent re-pushes the current environment after the agent has been
+// restarted.
+//
+// /oc/reboot kills the agent and starts a new one, and a new agent has an EMPTY
+// env map. This process keeps its own copy, so /oc/run commands were unaffected
+// — but PTY and exec sessions go through the agent and would silently lose
+// every sandbox variable. The environment would then depend on HOW a command
+// was run, which is the kind of inconsistency that costs an afternoon.
+func reapplyEnvsToAgent(ctx context.Context) {
+ m := envsSnapshot()
+ if len(m) == 0 {
+ return
+ }
+ if err := pushEnvsToAgent(ctx, m); err != nil {
+ log.Printf("microvm-hooks: WARNING re-applying %d env(s) to the restarted agent failed: %v — "+
+ "terminals and exec sessions will not see them", len(m), err)
+ return
+ }
+ log.Printf("microvm-hooks: re-applied %d env(s) to the restarted agent", len(m))
+}
+
+// ocSetEnvs records the sandbox's environment.
+//
+// A create sets this once. A sandbox WITH secrets goes through /oc/secrets
+// instead, which produces its environment by sealing — see oc_secrets.go.
+func (s *server) ocSetEnvs(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Envs map[string]string `json:"envs"`
+ }
+ if !decode(w, r, &req) {
+ return
+ }
+
+ applySandboxEnvs(req.Envs)
+
+ // Failure is reported rather than swallowed: a sandbox whose terminals see
+ // a different environment from its execs is worse than one that failed to
+ // start, because it works until it doesn't.
+ withAgent(w, "envs", func(c pb.SandboxAgentClient) error {
+ if _, err := c.SetEnvs(r.Context(), &pb.SetEnvsRequest{Envs: req.Envs}); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true, "count": len(req.Envs)})
+ return nil
+ })
+}
diff --git a/cmd/microvm-hooks/oc_envs_test.go b/cmd/microvm-hooks/oc_envs_test.go
new file mode 100644
index 00000000..eacee5f5
--- /dev/null
+++ b/cmd/microvm-hooks/oc_envs_test.go
@@ -0,0 +1,133 @@
+package main
+
+import (
+ "os"
+ "strings"
+ "testing"
+)
+
+// oc_envs_test.go — the layering, which is where this goes wrong silently.
+//
+// A sandbox env that never reaches a command is the bug this closed. An env
+// that REPLACES the guest's own environment is the bug introduced by fixing it
+// carelessly: drop PATH and every command naming a binary rather than a path
+// stops resolving, which looks like a broken image rather than a broken env.
+
+func setSandboxEnvs(m map[string]string) {
+ sandboxEnvs.mu.Lock()
+ sandboxEnvs.m = m
+ sandboxEnvs.mu.Unlock()
+}
+
+func envValue(env []string, key string) (string, bool) {
+ // Later entries win in execve, so the LAST match is the effective one —
+ // which is the whole mechanism the precedence below relies on.
+ val, found := "", false
+ for _, e := range env {
+ if strings.HasPrefix(e, key+"=") {
+ val, found = strings.TrimPrefix(e, key+"="), true
+ }
+ }
+ return val, found
+}
+
+// Even with nothing set, the environment must state the sandbox user's
+// identity. os.Environ() belongs to ROOT — this process is PID 1 — and commands
+// run as uid 1000, so inheriting it verbatim tells the customer's shell that
+// HOME is /root: a directory they cannot write, and one `cd ~` lands in.
+func TestBuildEnvAlwaysStampsTheSandboxIdentity(t *testing.T) {
+ setSandboxEnvs(nil)
+ env := buildEnv(nil)
+ if env == nil {
+ t.Fatal("buildEnv returned nil — the command would inherit root's HOME=/root")
+ }
+ if v, _ := envValue(env, "HOME"); v != sandboxHomeDir {
+ t.Errorf("HOME = %q, want %q", v, sandboxHomeDir)
+ }
+ for _, k := range []string{"USER", "LOGNAME"} {
+ if v, _ := envValue(env, k); v != sandboxUserName {
+ t.Errorf("%s = %q, want %q", k, v, sandboxUserName)
+ }
+ }
+}
+
+// The identity must survive both other layers, or a customer setting an
+// unrelated variable would silently get root's home back.
+func TestSandboxIdentitySurvivesOtherEnvLayers(t *testing.T) {
+ setSandboxEnvs(map[string]string{"APP": "x"})
+ env := buildEnv(map[string]string{"REQ": "y"})
+ if v, _ := envValue(env, "HOME"); v != sandboxHomeDir {
+ t.Errorf("HOME = %q, want %q", v, sandboxHomeDir)
+ }
+}
+
+// The guest's own environment survives. Without this, PATH is gone.
+func TestBuildEnvKeepsTheGuestEnvironment(t *testing.T) {
+ t.Setenv("OC_TEST_GUEST_VAR", "from-guest")
+ setSandboxEnvs(map[string]string{"SANDBOX_VAR": "from-sandbox"})
+
+ env := buildEnv(nil)
+ if v, ok := envValue(env, "OC_TEST_GUEST_VAR"); !ok || v != "from-guest" {
+ t.Error("the guest's environment was replaced — PATH and HOME would be gone and every bare command name would stop resolving")
+ }
+ if v, ok := envValue(env, "SANDBOX_VAR"); !ok || v != "from-sandbox" {
+ t.Errorf("SANDBOX_VAR = %q, want it applied to every command", v)
+ }
+}
+
+// A create's envs reach a command that specifies none of its own. This is the
+// case that silently did nothing before.
+func TestSandboxEnvsReachACommandWithNoOwnEnv(t *testing.T) {
+ setSandboxEnvs(map[string]string{"API_KEY": "sk-123"})
+ if v, ok := envValue(buildEnv(nil), "API_KEY"); !ok || v != "sk-123" {
+ t.Fatalf("API_KEY = %q, ok=%v — create({envs}) would return 200 and the program would see an unset variable", v, ok)
+ }
+}
+
+// Per-exec wins, so one command can override without changing the sandbox.
+func TestPerExecEnvOverridesTheSandboxEnv(t *testing.T) {
+ setSandboxEnvs(map[string]string{"MODE": "production"})
+ env := buildEnv(map[string]string{"MODE": "debug"})
+ if v, _ := envValue(env, "MODE"); v != "debug" {
+ t.Errorf("MODE = %q, want the per-exec value to win", v)
+ }
+}
+
+// And a per-exec env still works with no sandbox env set — the pre-existing
+// behaviour, which must not regress.
+func TestPerExecEnvAloneStillWorks(t *testing.T) {
+ setSandboxEnvs(nil)
+ env := buildEnv(map[string]string{"ONLY": "here"})
+ if v, ok := envValue(env, "ONLY"); !ok || v != "here" {
+ t.Errorf("ONLY = %q", v)
+ }
+ if _, ok := envValue(env, "PATH"); !ok && os.Getenv("PATH") != "" {
+ t.Error("PATH missing from a per-exec-only environment")
+ }
+}
+
+// Replacing rather than merging: omitting a key clears it, so a caller can
+// unset a variable.
+func TestSetEnvsReplacesRatherThanMerges(t *testing.T) {
+ setSandboxEnvs(map[string]string{"OLD": "1"})
+ setSandboxEnvs(map[string]string{"NEW": "2"})
+ env := buildEnv(nil)
+ if _, ok := envValue(env, "OLD"); ok {
+ t.Error("a replaced environment kept a key the caller omitted — there would be no way to unset one")
+ }
+ if v, _ := envValue(env, "NEW"); v != "2" {
+ t.Errorf("NEW = %q", v)
+ }
+}
+
+// The snapshot is a copy: a command building its environment must not be able
+// to mutate the sandbox's.
+func TestSnapshotIsACopy(t *testing.T) {
+ setSandboxEnvs(map[string]string{"K": "v"})
+ snap := envsSnapshot()
+ snap["K"] = "mutated"
+ if v, _ := envValue(buildEnv(nil), "K"); v != "v" {
+ t.Errorf("K = %q — the snapshot aliased the shared map", v)
+ }
+ setSandboxEnvs(nil)
+}
diff --git a/cmd/microvm-hooks/oc_exec.go b/cmd/microvm-hooks/oc_exec.go
new file mode 100644
index 00000000..9eee5d60
--- /dev/null
+++ b/cmd/microvm-hooks/oc_exec.go
@@ -0,0 +1,322 @@
+package main
+
+// oc_exec.go — long-running exec sessions with a live output stream.
+//
+// The difference from /oc/run is duration. A run is one command, buffered, one
+// reply — fine for the overwhelming majority of what a sandbox is asked to do,
+// and useless for `npm run dev`, a training job, or anything a customer wants
+// to watch. A session starts a process, keeps it alive across disconnects, and
+// streams its output to whoever is attached.
+//
+// Same shape as the PTY bridge next door, and for the same reason: the gRPC
+// stream stays inside the guest, and the customer's side speaks a small JSON
+// frame format the proxy can carry. Opened on attach, closed on detach.
+//
+// The scrollback is the agent's, not ours. It replays what a process has
+// already printed when a client attaches, then sends SCROLLBACK_END to mark the
+// boundary between history and live output — which is also what makes /result
+// below possible without a worker holding a buffer.
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/gorilla/websocket"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+const (
+ ocExecCreate = ocPrefix + "exec/create"
+ ocExecAttach = ocPrefix + "exec/attach"
+ ocExecList = ocPrefix + "exec/list"
+ ocExecKill = ocPrefix + "exec/kill"
+ ocExecResult = ocPrefix + "exec/result"
+)
+
+// execSessionRequest is the body of the unary exec-session endpoints.
+type execSessionRequest struct {
+ SessionID string `json:"sessionId,omitempty"`
+ Command string `json:"cmd,omitempty"`
+ Args []string `json:"args,omitempty"`
+ Env map[string]string `json:"envs,omitempty"`
+ Cwd string `json:"cwd,omitempty"`
+ TimeoutSec int32 `json:"timeoutSec,omitempty"`
+ MaxRunAfterDisconnect int32 `json:"maxRunAfterDisconnect,omitempty"`
+ Signal int32 `json:"signal,omitempty"`
+}
+
+// execFrame is one message from the session's output stream.
+//
+// The stream field is the whole reason this is framed rather than raw: stdout
+// and stderr arrive interleaved on one connection and a customer redirecting
+// one but not the other needs them told apart. `scrollbackEnd` marks where
+// replayed history stops and live output starts, which is what lets a client
+// render "catching up" distinctly from "watching".
+type execFrame struct {
+ Stream string `json:"stream,omitempty"` // stdout | stderr | exit | scrollbackEnd
+ Data string `json:"data,omitempty"` // base64
+ ExitCode int32 `json:"exitCode,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func streamName(t pb.ExecSessionOutput_Type) string {
+ switch t {
+ case pb.ExecSessionOutput_STDOUT:
+ return "stdout"
+ case pb.ExecSessionOutput_STDERR:
+ return "stderr"
+ case pb.ExecSessionOutput_EXIT:
+ return "exit"
+ case pb.ExecSessionOutput_SCROLLBACK_END:
+ return "scrollbackEnd"
+ }
+ return "stdout"
+}
+
+func (s *server) registerOCExec(mux *http.ServeMux) {
+ mux.HandleFunc(ocExecCreate, s.ocExecCreate)
+ mux.HandleFunc(ocExecAttach, s.ocExecAttach)
+ mux.HandleFunc(ocExecList, s.ocExecList)
+ mux.HandleFunc(ocExecKill, s.ocExecKill)
+ mux.HandleFunc(ocExecResult, s.ocExecResult)
+}
+
+func (s *server) ocExecCreate(w http.ResponseWriter, r *http.Request) {
+ var req execSessionRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ if strings.TrimSpace(req.Command) == "" {
+ http.Error(w, "cmd is required", http.StatusBadRequest)
+ return
+ }
+ withAgent(w, "exec/create", func(c pb.SandboxAgentClient) error {
+ resp, err := c.ExecSessionCreate(r.Context(), &pb.ExecSessionCreateRequest{
+ Command: req.Command,
+ Args: req.Args,
+ Envs: req.Env,
+ Cwd: req.Cwd,
+ TimeoutSeconds: req.TimeoutSec,
+ MaxRunAfterDisconnect: req.MaxRunAfterDisconnect,
+ })
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"sessionId": resp.SessionId})
+ return nil
+ })
+}
+
+func (s *server) ocExecList(w http.ResponseWriter, r *http.Request) {
+ withAgent(w, "exec/list", func(c pb.SandboxAgentClient) error {
+ resp, err := c.ExecSessionList(r.Context(), &pb.ExecSessionListRequest{})
+ if err != nil {
+ return err
+ }
+ out := make([]map[string]any, 0, len(resp.Sessions))
+ for _, sess := range resp.Sessions {
+ out = append(out, map[string]any{
+ "sessionId": sess.SessionId,
+ "command": sess.Command,
+ "args": sess.Args,
+ "running": sess.Running,
+ "exitCode": sess.ExitCode,
+ "startedAt": sess.StartedAt,
+ "attachedClients": sess.AttachedClients,
+ })
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"sessions": out})
+ return nil
+ })
+}
+
+func (s *server) ocExecKill(w http.ResponseWriter, r *http.Request) {
+ var req execSessionRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "exec/kill", func(c pb.SandboxAgentClient) error {
+ if _, err := c.ExecSessionKill(r.Context(), &pb.ExecSessionKillRequest{
+ SessionId: req.SessionID, Signal: req.Signal,
+ }); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+// ocExecResult reports a session's output so far WITHOUT holding a stream open.
+//
+// This is the async-poll path: start something, come back later, ask what
+// happened. The worker-backed fleet answers it from a buffer the worker keeps;
+// there is no worker here, so it is synthesised from the agent's own scrollback
+// — attach, read the replay, stop at SCROLLBACK_END. That marker is what makes
+// this terminate: without it there is no way to tell "this is history" from
+// "the process is quiet right now", and the poll would hang until timeout.
+func (s *server) ocExecResult(w http.ResponseWriter, r *http.Request) {
+ sessionID := r.URL.Query().Get("sessionId")
+ if sessionID == "" {
+ http.Error(w, "sessionId is required", http.StatusBadRequest)
+ return
+ }
+ withAgent(w, "exec/result", func(c pb.SandboxAgentClient) error {
+ ctx, cancel := contextWithTimeout(r, 30*time.Second)
+ defer cancel()
+ stream, err := c.ExecSessionAttach(ctx)
+ if err != nil {
+ return err
+ }
+ if err := stream.Send(&pb.ExecSessionInput{SessionId: sessionID}); err != nil {
+ return err
+ }
+ // Half-close immediately: this is a read-only look at the session, and
+ // leaving the send side open would keep it counted as an attached
+ // client, which changes when the agent tears a finished session down.
+ _ = stream.CloseSend()
+
+ var stdout, stderr []byte
+ running := true
+ var exitCode *int32
+ for {
+ out, rerr := stream.Recv()
+ if rerr != nil {
+ if rerr == io.EOF {
+ break
+ }
+ return rerr
+ }
+ switch out.Type {
+ case pb.ExecSessionOutput_STDOUT:
+ stdout = append(stdout, out.Data...)
+ case pb.ExecSessionOutput_STDERR:
+ stderr = append(stderr, out.Data...)
+ case pb.ExecSessionOutput_EXIT:
+ running = false
+ code := out.ExitCode
+ exitCode = &code
+ case pb.ExecSessionOutput_SCROLLBACK_END:
+ // Everything before this is history; everything after is live
+ // output we are not here to wait for.
+ goto done
+ }
+ }
+ done:
+ body := map[string]any{"running": running, "stdout": stdout, "stderr": stderr}
+ if exitCode != nil {
+ body["exitCode"] = *exitCode
+ }
+ writeJSON(w, http.StatusOK, body)
+ return nil
+ })
+}
+
+// ocExecAttach bridges a customer WebSocket to a session's output stream.
+//
+// /oc/exec/attach?sessionId=…
+func (s *server) ocExecAttach(w http.ResponseWriter, r *http.Request) {
+ sessionID := r.URL.Query().Get("sessionId")
+ if sessionID == "" {
+ http.Error(w, "sessionId is required", http.StatusBadRequest)
+ return
+ }
+ client, err := agentClient()
+ if err != nil {
+ http.Error(w, "agent unavailable: "+err.Error(), http.StatusServiceUnavailable)
+ return
+ }
+
+ ws, err := (&websocket.Upgrader{
+ ReadBufferSize: 32 * 1024,
+ WriteBufferSize: 32 * 1024,
+ CheckOrigin: func(*http.Request) bool { return true },
+ }).Upgrade(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer ws.Close()
+
+ stream, err := client.ExecSessionAttach(r.Context())
+ if err != nil {
+ _ = ws.WriteJSON(execFrame{Stream: "exit", Error: "attach: " + err.Error()})
+ return
+ }
+ // Session id on the first message, per the proto.
+ if err := stream.Send(&pb.ExecSessionInput{SessionId: sessionID}); err != nil {
+ _ = ws.WriteJSON(execFrame{Stream: "exit", Error: "attach: " + err.Error()})
+ return
+ }
+
+ // One writer. gorilla allows exactly one concurrent writer and both halves
+ // below can produce one.
+ var writeMu sync.Mutex
+ send := func(f execFrame) error {
+ writeMu.Lock()
+ defer writeMu.Unlock()
+ return ws.WriteJSON(f)
+ }
+
+ done := make(chan struct{})
+
+ // agent -> customer
+ go func() {
+ defer close(done)
+ for {
+ out, rerr := stream.Recv()
+ if rerr != nil {
+ if rerr != io.EOF && !strings.Contains(rerr.Error(), "context canceled") {
+ _ = send(execFrame{Stream: "exit", Error: rerr.Error()})
+ }
+ return
+ }
+ f := execFrame{Stream: streamName(out.Type), ExitCode: out.ExitCode}
+ if len(out.Data) > 0 {
+ f.Data = b64(out.Data)
+ }
+ if err := send(f); err != nil {
+ return
+ }
+ if out.Type == pb.ExecSessionOutput_EXIT {
+ return
+ }
+ }
+ }()
+
+ // customer -> agent (stdin)
+ for {
+ select {
+ case <-done:
+ return
+ default:
+ }
+ _, msg, rerr := ws.ReadMessage()
+ if rerr != nil {
+ // Detach, do NOT kill: a session outlives its clients by design —
+ // that is what maxRunAfterDisconnect is for. Closing the send side
+ // tells the agent this client is gone without touching the process.
+ _ = stream.CloseSend()
+ <-done
+ return
+ }
+ var f clientFrame
+ if err := json.Unmarshal(msg, &f); err != nil {
+ continue
+ }
+ if f.Data == "" {
+ continue
+ }
+ data, derr := unb64(f.Data)
+ if derr != nil {
+ continue
+ }
+ if err := stream.Send(&pb.ExecSessionInput{SessionId: sessionID, Stdin: data}); err != nil {
+ <-done
+ return
+ }
+ }
+}
diff --git a/cmd/microvm-hooks/oc_secrets.go b/cmd/microvm-hooks/oc_secrets.go
new file mode 100644
index 00000000..06a11024
--- /dev/null
+++ b/cmd/microvm-hooks/oc_secrets.go
@@ -0,0 +1,214 @@
+package main
+
+// oc_secrets.go — the secret store, running inside the guest.
+//
+// On the QEMU fleet the secrets proxy runs on the WORKER. The sandbox is given
+// placeholder tokens (`osb_sealed_…`), its egress is MITM'd through a CONNECT
+// proxy with its own CA, and the real value is substituted into the request
+// only for hosts that particular secret is allowed to reach. The plaintext
+// never enters the VM.
+//
+// There is no worker here, so the proxy moves into the guest — as root, in this
+// process, while the customer's code runs as the unprivileged `sandbox` user.
+// The alternative considered and rejected was a shared in-region service: it
+// would be a single high-value target holding every customer's secrets and a
+// SPOF on everyone's egress, and we would be building it precisely because we
+// removed the worker that made it unnecessary.
+//
+// TWO PROPERTIES CARRY THIS DESIGN.
+//
+// Bypass is fail-closed. The guest only ever holds placeholders. A customer
+// who ignores HTTPS_PROXY and dials the upstream
+// directly sends a worthless osb_sealed_… string. So
+// egress does not have to be FORCED through the proxy
+// — no iptables, no fighting the customer's network.
+//
+// Substitution is Session.TokenHosts means a token is substituted only
+// host-scoped. for the hosts that secret is for. Sending it to a
+// server the customer controls yields the placeholder.
+//
+// WHERE THIS IS WEAKER THAN QEMU, stated plainly because it is a real
+// reduction: the secret lives in this process's memory rather than on a
+// separate machine. `sandbox` cannot read root's memory, but a privilege
+// escalation inside the guest reaches the secrets, where on QEMU it would not.
+
+import (
+ "log"
+ "net/http"
+ "os"
+ "sync"
+
+ "github.com/opensandbox/opensandbox/internal/secretsproxy"
+)
+
+const (
+ ocSecretsPath = ocPrefix + "secrets"
+ ocSecretsUpdatePath = ocPrefix + "secrets/update"
+
+ // secretsProxyAddr is loopback-only. Nothing outside the box could reach it
+ // anyway — Lambda's proxy forwards solely to the hook port — but binding
+ // narrowly is what makes that a property of this process rather than an
+ // accident of the platform.
+ secretsProxyAddr = "127.0.0.1:3128"
+
+ // secretsProxyEndpoint is what the sandbox is told to use. The worker fleet
+ // uses an anycast link-local address; that address is nobody in here.
+ secretsProxyEndpoint = "http://" + secretsProxyAddr
+
+ // caDir holds the generated CA.
+ //
+ // DELIBERATELY NOT UNDER /home/sandbox. That directory is what
+ // /oc/workspace/export archives, so a CA key kept there would be uploaded
+ // to blob storage inside every checkpoint the customer takes — and restored
+ // into every fork of it.
+ caDir = "/var/lib/opencomputer/ca"
+
+ // guestCACertPath is where the sandbox's TLS libraries look. The env vars
+ // CreateSealedEnvs returns name this exact path.
+ guestCACertPath = "/usr/local/share/ca-certificates/opensandbox-proxy.crt"
+)
+
+// secrets holds the lazily-started proxy.
+//
+// LAZY, NOT STARTED AT BOOT, and the reason is the snapshot: this process
+// starts during the image BUILD and every box resumes from that moment, so a CA
+// generated at startup would be the SAME KEY in every box we ever run.
+// Generating on first use puts it after /resume, which makes it per-box.
+//
+// It also means a sandbox with no secrets never generates a key, never listens,
+// and never pays for any of this.
+var secrets struct {
+ mu sync.Mutex
+ proxy *secretsproxy.SecretsProxy
+}
+
+// secretsProxy returns the running proxy, starting it if this is the first use.
+func secretsProxy() (*secretsproxy.SecretsProxy, error) {
+ secrets.mu.Lock()
+ defer secrets.mu.Unlock()
+ if secrets.proxy != nil {
+ return secrets.proxy, nil
+ }
+
+ ca, err := secretsproxy.LoadOrCreateCA(caDir)
+ if err != nil {
+ return nil, err
+ }
+ p, err := secretsproxy.NewSecretsProxy(ca, secretsProxyAddr)
+ if err != nil {
+ return nil, err
+ }
+ // Point the sandbox at loopback rather than the workers' anycast address.
+ p.SetEndpoint(secretsProxyEndpoint)
+ p.Start()
+
+ // The CA the sandbox has to trust. Written as a plain file: the env vars
+ // below name this path directly and the consuming libraries read it, so no
+ // update-ca-certificates run is needed (same as the QEMU path).
+ if err := os.MkdirAll("/usr/local/share/ca-certificates", 0o755); err != nil {
+ log.Printf("microvm-hooks: secrets: mkdir ca dir: %v", err)
+ }
+ if err := os.WriteFile(guestCACertPath, ca.CertPEM(), 0o644); err != nil {
+ _ = p.Stop()
+ return nil, err
+ }
+
+ secrets.proxy = p
+ log.Printf("microvm-hooks: secrets proxy listening on %s", secretsProxyAddr)
+ return p, nil
+}
+
+// secretsRequest mirrors CreateSealedEnvs' arguments.
+//
+// The REAL values arrive here — that is the whole point, and it is safe because
+// this request crosses only the platform's authenticated channel into a root
+// process. What leaves this function toward the customer is sealed.
+type secretsRequest struct {
+ SandboxID string `json:"sandboxId"`
+ // PlaintextEnvs are forwarded unsealed. They came from the caller directly
+ // rather than a secret store, and sealing them would break `echo $VAR`,
+ // file writes and subprocess env without adding protection.
+ PlaintextEnvs map[string]string `json:"envs,omitempty"`
+ // SecretEnvs are sealed: the sandbox sees a token, never these values.
+ SecretEnvs map[string]string `json:"secretEnvs,omitempty"`
+ // Allowlist gates egress entirely. Empty means unrestricted.
+ Allowlist []string `json:"allowlist,omitempty"`
+ // SecretAllowedHosts scopes each secret to the hosts it may be sent to.
+ SecretAllowedHosts map[string][]string `json:"secretAllowedHosts,omitempty"`
+}
+
+// ocSetSecrets seals the sandbox's secrets and applies the resulting
+// environment.
+//
+// Replaces /oc/envs for a sandbox that has any, rather than running alongside
+// it: the env map returned below ALREADY contains the plaintext envs merged in,
+// so a subsequent /oc/envs call would overwrite the sealed values with nothing
+// and quietly disable the whole mechanism.
+func (s *server) ocSetSecrets(w http.ResponseWriter, r *http.Request) {
+ var req secretsRequest
+ if !decode(w, r, &req) {
+ return
+ }
+
+ p, err := secretsProxy()
+ if err != nil {
+ log.Printf("microvm-hooks: secrets: start proxy: %v", err)
+ http.Error(w, "secrets: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ // guestIP is the key the proxy looks a session up by, and in here the
+ // client is always loopback — there is exactly one sandbox per box, so the
+ // per-VM IP keying the worker fleet needs collapses to a constant.
+ env := p.CreateSealedEnvs(req.SandboxID, "127.0.0.1", "",
+ req.PlaintextEnvs, req.SecretEnvs, req.Allowlist, req.SecretAllowedHosts)
+ if env == nil {
+ // Nothing to seal and nothing to enforce.
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sealed": 0})
+ return
+ }
+
+ applySandboxEnvs(env)
+
+ // The agent runs PTY and exec-session commands, so it needs the same
+ // environment or a terminal would see different variables from an exec.
+ if err := pushEnvsToAgent(r.Context(), env); err != nil {
+ log.Printf("microvm-hooks: secrets: push envs to agent: %v", err)
+ http.Error(w, "secrets: agent: "+err.Error(), http.StatusServiceUnavailable)
+ return
+ }
+
+ log.Printf("microvm-hooks: secrets applied for %s (%d sealed, %d allowlisted hosts)",
+ req.SandboxID, len(req.SecretEnvs), len(req.Allowlist))
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sealed": len(req.SecretEnvs)})
+}
+
+// ocUpdateSecret refreshes one secret's value in place.
+//
+// By NAME, not by token: the sandbox is holding a token it was given at create
+// and must keep working, so re-sealing would mean pushing a new environment
+// into a process that already read the old one. Session.Names exists for
+// exactly this.
+func (s *server) ocUpdateSecret(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ SandboxID string `json:"sandboxId"`
+ Name string `json:"name"`
+ Value string `json:"value"`
+ }
+ if !decode(w, r, &req) {
+ return
+ }
+
+ secrets.mu.Lock()
+ p := secrets.proxy
+ secrets.mu.Unlock()
+ if p == nil {
+ // No proxy means no session, which is a miss rather than an error —
+ // the same answer the worker path gives for a sandbox with no secrets.
+ writeJSON(w, http.StatusOK, map[string]any{"updated": false})
+ return
+ }
+
+ updated := p.UpdateSecretValue(req.SandboxID, req.Name, req.Value)
+ writeJSON(w, http.StatusOK, map[string]any{"updated": updated})
+}
diff --git a/cmd/microvm-hooks/oc_secrets_test.go b/cmd/microvm-hooks/oc_secrets_test.go
new file mode 100644
index 00000000..24c423c9
--- /dev/null
+++ b/cmd/microvm-hooks/oc_secrets_test.go
@@ -0,0 +1,124 @@
+package main
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/internal/secretsproxy"
+)
+
+// oc_secrets_test.go — the sealing boundary.
+//
+// One thing must be true and is not visible from any log or response: the
+// environment handed to the sandbox contains NO real secret. If sealing
+// silently degrades to passthrough, everything keeps working — the customer's
+// code reads the variable, the request succeeds — and the entire protection is
+// gone with nothing to notice.
+
+// newGuestProxy builds a proxy configured the way the guest configures one.
+func newGuestProxy(t *testing.T) *secretsproxy.SecretsProxy {
+ t.Helper()
+ ca, err := secretsproxy.LoadOrCreateCA(t.TempDir())
+ if err != nil {
+ t.Fatalf("ca: %v", err)
+ }
+ // Port 0: a real listener, but no fight over 3128 in a test run.
+ p, err := secretsproxy.NewSecretsProxy(ca, "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("proxy: %v", err)
+ }
+ t.Cleanup(func() { _ = p.Stop() })
+ p.SetEndpoint(secretsProxyEndpoint)
+ return p
+}
+
+// The environment the sandbox boots with must not contain the secret.
+func TestSealedEnvNeverCarriesTheRealValue(t *testing.T) {
+ p := newGuestProxy(t)
+ const real = "sk-live-do-not-leak-me"
+
+ env := p.CreateSealedEnvs("sbx-1", "127.0.0.1", "",
+ map[string]string{"PUBLIC": "fine"},
+ map[string]string{"API_KEY": real},
+ nil, nil)
+ if env == nil {
+ t.Fatal("no environment produced")
+ }
+
+ for k, v := range env {
+ if strings.Contains(v, real) {
+ t.Fatalf("%s carries the real secret — the sandbox would hold the plaintext and the whole mechanism would be off", k)
+ }
+ }
+ if got := env["API_KEY"]; !strings.HasPrefix(got, "osb_sealed_") {
+ t.Errorf("API_KEY = %q, want a sealed placeholder", got)
+ }
+ // Plaintext envs are deliberately NOT sealed — they never came from a
+ // secret store, and sealing them would break echo/file/subprocess use.
+ if got := env["PUBLIC"]; got != "fine" {
+ t.Errorf("PUBLIC = %q, want it passed through unsealed", got)
+ }
+}
+
+// The sandbox has to be pointed at the in-guest proxy. The workers' anycast
+// address is nobody in here, and getting this wrong means every outbound
+// request times out rather than failing loudly.
+func TestGuestEnvPointsAtLoopbackNotAnycast(t *testing.T) {
+ p := newGuestProxy(t)
+ env := p.CreateSealedEnvs("sbx-1", "127.0.0.1", "", nil,
+ map[string]string{"K": "v"}, nil, nil)
+
+ for _, key := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"} {
+ if env[key] != secretsProxyEndpoint {
+ t.Errorf("%s = %q, want %q", key, env[key], secretsProxyEndpoint)
+ }
+ }
+ if strings.Contains(env["HTTPS_PROXY"], "169.254") {
+ t.Error("the guest was pointed at the workers' anycast address, which nothing answers in here")
+ }
+ // All three, because node, python and OpenSSL each read a different one.
+ for _, key := range []string{"NODE_EXTRA_CA_CERTS", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE"} {
+ if env[key] != guestCACertPath {
+ t.Errorf("%s = %q, want %q", key, env[key], guestCACertPath)
+ }
+ }
+}
+
+// A store with only an allowlist still has to register a session, or the proxy
+// rejects every CONNECT with 407 and the sandbox has no egress at all.
+func TestAllowlistOnlyStoreStillProducesAnEnvironment(t *testing.T) {
+ p := newGuestProxy(t)
+ env := p.CreateSealedEnvs("sbx-1", "127.0.0.1", "", nil, nil,
+ []string{"api.stripe.com"}, nil)
+ if env == nil {
+ t.Fatal("an allowlist-only store produced no environment — the sandbox would never be pointed at the proxy and the allowlist would not be enforced")
+ }
+ if env["HTTPS_PROXY"] != secretsProxyEndpoint {
+ t.Errorf("HTTPS_PROXY = %q", env["HTTPS_PROXY"])
+ }
+}
+
+// A sandbox with nothing to seal and nothing to enforce gets no environment,
+// and therefore never starts the proxy.
+func TestNoSecretsProducesNoEnvironment(t *testing.T) {
+ p := newGuestProxy(t)
+ if env := p.CreateSealedEnvs("sbx-1", "127.0.0.1", "", nil, nil, nil, nil); env != nil {
+ t.Errorf("got an environment for a sandbox with no secrets: %v", env)
+ }
+}
+
+// The CA key must not live under the workspace: /oc/workspace/export archives
+// that directory, so the key would be uploaded to blob storage inside every
+// checkpoint and restored into every fork.
+func TestCADirIsOutsideTheArchivedWorkspace(t *testing.T) {
+ if strings.HasPrefix(caDir, workspaceDir) {
+ t.Fatalf("caDir %q is inside %q — the CA private key would be shipped in every checkpoint", caDir, workspaceDir)
+ }
+}
+
+// The proxy binds loopback only.
+func TestProxyBindsLoopbackOnly(t *testing.T) {
+ if !strings.HasPrefix(secretsProxyAddr, "127.0.0.1:") {
+ t.Errorf("secretsProxyAddr = %q, want a loopback bind", secretsProxyAddr)
+ }
+}
diff --git a/cmd/microvm-hooks/oc_stream.go b/cmd/microvm-hooks/oc_stream.go
new file mode 100644
index 00000000..c8601445
--- /dev/null
+++ b/cmd/microvm-hooks/oc_stream.go
@@ -0,0 +1,241 @@
+package main
+
+// oc_stream.go — PTY and streaming exec, over one WebSocket per session.
+//
+// These are the two things the direct path could not do, because both are
+// bidirectional streams and the whole design is one request in, one reply out.
+//
+// The tunnel that carries them ALREADY EXISTS in this image: handleAgentTunnel
+// splices a WebSocket to the agent's gRPC listener, and it works through the
+// proxy. What made it a liability on the agent path was not the tunnel — it was
+// that the tunnel was ALWAYS ON: one pre-dialed channel per box, keepalives, a
+// re-dial ladder, and a Durable Object holding sockets open, all of it decaying
+// whether or not anyone was using it. Measured consequence: a box answering
+// /healthz in 90ms while the control plane logged it as tunnel-less.
+//
+// So these endpoints translate instead. The customer's side is a plain
+// WebSocket carrying our own small frame format; the gRPC stream to the agent
+// lives entirely inside the guest, for exactly as long as the session does, and
+// nothing survives it. Create and exec never touch any of this.
+
+import (
+ "encoding/json"
+ "io"
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+
+ "github.com/gorilla/websocket"
+
+ pb "github.com/opensandbox/opensandbox/proto/agent"
+)
+
+const (
+ ocPTYCreate = ocPrefix + "pty/create"
+ ocPTYAttach = ocPrefix + "pty/attach"
+ ocPTYResize = ocPrefix + "pty/resize"
+ ocPTYKill = ocPrefix + "pty/kill"
+)
+
+// ptyRequest is the JSON body of the unary PTY endpoints. One shape for all
+// three, matching the agent's proto fields.
+type ptyRequest struct {
+ SessionID string `json:"sessionId,omitempty"`
+ Cols int32 `json:"cols,omitempty"`
+ Rows int32 `json:"rows,omitempty"`
+ Shell string `json:"shell,omitempty"`
+}
+
+// clientFrame is what the customer's side sends over the attach socket.
+//
+// A framed protocol rather than raw bytes because a PTY needs an out-of-band
+// resize: a terminal that cannot be resized renders every full-screen program
+// wrong the moment the window changes. Raw bytes would have no room to say so.
+type clientFrame struct {
+ Data string `json:"data,omitempty"` // base64 stdin
+ Cols int32 `json:"cols,omitempty"`
+ Rows int32 `json:"rows,omitempty"`
+}
+
+// serverFrame is what goes back.
+type serverFrame struct {
+ Data string `json:"data,omitempty"` // base64 stdout
+ Exited bool `json:"exited,omitempty"`
+ ExitCode int32 `json:"exitCode,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (s *server) registerOCStream(mux *http.ServeMux) {
+ mux.HandleFunc(ocPTYCreate, s.ocPTYCreate)
+ mux.HandleFunc(ocPTYAttach, s.ocPTYAttach)
+ mux.HandleFunc(ocPTYResize, s.ocPTYResize)
+ mux.HandleFunc(ocPTYKill, s.ocPTYKill)
+ s.registerOCExec(mux)
+ mux.HandleFunc(ocWorkspaceExport, s.ocWorkspaceExport)
+ mux.HandleFunc(ocWorkspaceImport, s.ocWorkspaceImport)
+}
+
+func (s *server) ocPTYCreate(w http.ResponseWriter, r *http.Request) {
+ var req ptyRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "pty/create", func(c pb.SandboxAgentClient) error {
+ resp, err := c.PTYCreate(r.Context(), &pb.PTYCreateRequest{
+ Cols: req.Cols, Rows: req.Rows, Shell: req.Shell,
+ })
+ if err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"sessionId": resp.SessionId})
+ return nil
+ })
+}
+
+func (s *server) ocPTYResize(w http.ResponseWriter, r *http.Request) {
+ var req ptyRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "pty/resize", func(c pb.SandboxAgentClient) error {
+ if _, err := c.PTYResize(r.Context(), &pb.PTYResizeRequest{
+ SessionId: req.SessionID, Cols: req.Cols, Rows: req.Rows,
+ }); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+func (s *server) ocPTYKill(w http.ResponseWriter, r *http.Request) {
+ var req ptyRequest
+ if !decode(w, r, &req) {
+ return
+ }
+ withAgent(w, "pty/kill", func(c pb.SandboxAgentClient) error {
+ if _, err := c.PTYKill(r.Context(), &pb.PTYKillRequest{SessionId: req.SessionID}); err != nil {
+ return err
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+ return nil
+ })
+}
+
+// ocPTYAttach bridges a customer WebSocket to the agent's PTYAttach stream.
+//
+// /oc/pty/attach?sessionId=…
+//
+// The gRPC stream is opened here, inside the guest, and closed when the socket
+// closes. Nothing outside the box ever speaks gRPC, so the proxy's trailer
+// stripping is irrelevant — the status of this stream is the WebSocket's own
+// close, which the proxy does forward.
+func (s *server) ocPTYAttach(w http.ResponseWriter, r *http.Request) {
+ sessionID := r.URL.Query().Get("sessionId")
+ if sessionID == "" {
+ http.Error(w, "sessionId is required", http.StatusBadRequest)
+ return
+ }
+ client, err := agentClient()
+ if err != nil {
+ http.Error(w, "agent unavailable: "+err.Error(), http.StatusServiceUnavailable)
+ return
+ }
+
+ ws, err := (&websocket.Upgrader{
+ ReadBufferSize: 32 * 1024,
+ WriteBufferSize: 32 * 1024,
+ // The proxy is the only route in and it has already authenticated the
+ // caller's token, so there is no origin to check against.
+ CheckOrigin: func(*http.Request) bool { return true },
+ }).Upgrade(w, r, nil)
+ if err != nil {
+ log.Printf("microvm-hooks: pty attach upgrade: %v", err)
+ return
+ }
+ defer ws.Close()
+
+ // Bound to the request context so the stream dies with the socket rather
+ // than leaking a goroutine and a PTY per disconnect.
+ stream, err := client.PTYAttach(r.Context())
+ if err != nil {
+ _ = ws.WriteJSON(serverFrame{Error: "pty attach: " + err.Error()})
+ return
+ }
+
+ // The session id rides on the first message, per the proto. Sent before any
+ // customer input so the agent knows which PTY this is even if the customer
+ // types nothing.
+ if err := stream.Send(&pb.PTYInput{SessionId: sessionID}); err != nil {
+ _ = ws.WriteJSON(serverFrame{Error: "pty attach: " + err.Error()})
+ return
+ }
+
+ // One writer goroutine. gorilla/websocket permits exactly one concurrent
+ // writer, and both directions below can produce a write — a mutex is the
+ // difference between a working terminal and a corrupted frame under load.
+ var writeMu sync.Mutex
+ send := func(f serverFrame) error {
+ writeMu.Lock()
+ defer writeMu.Unlock()
+ return ws.WriteJSON(f)
+ }
+
+ done := make(chan struct{})
+
+ // agent -> customer
+ go func() {
+ defer close(done)
+ for {
+ out, err := stream.Recv()
+ if err != nil {
+ if err != io.EOF && !strings.Contains(err.Error(), "context canceled") {
+ _ = send(serverFrame{Error: err.Error()})
+ }
+ return
+ }
+ f := serverFrame{Exited: out.Exited, ExitCode: out.ExitCode}
+ if len(out.Data) > 0 {
+ f.Data = b64(out.Data)
+ }
+ if err := send(f); err != nil {
+ return
+ }
+ if out.Exited {
+ return
+ }
+ }
+ }()
+
+ // customer -> agent
+ for {
+ select {
+ case <-done:
+ return
+ default:
+ }
+ _, msg, err := ws.ReadMessage()
+ if err != nil {
+ _ = stream.CloseSend()
+ <-done
+ return
+ }
+ var f clientFrame
+ if err := json.Unmarshal(msg, &f); err != nil {
+ continue // a malformed frame is not worth killing a terminal over
+ }
+ in := &pb.PTYInput{SessionId: sessionID, Cols: f.Cols, Rows: f.Rows}
+ if f.Data != "" {
+ data, derr := unb64(f.Data)
+ if derr != nil {
+ continue
+ }
+ in.Stdin = data
+ }
+ if err := stream.Send(in); err != nil {
+ <-done
+ return
+ }
+ }
+}
diff --git a/cmd/microvm-hooks/oc_test.go b/cmd/microvm-hooks/oc_test.go
new file mode 100644
index 00000000..fe84a4fa
--- /dev/null
+++ b/cmd/microvm-hooks/oc_test.go
@@ -0,0 +1,173 @@
+package main
+
+import (
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+// oc_test.go — the parts of the front door that do not need a live agent.
+//
+// The filesystem handlers are a thin translation over loopback gRPC and are
+// exercised end to end on dev against a real box; what is worth pinning here is
+// the routing and the error mapping, because both fail silently. A port proxy
+// that mis-parses its path reaches the wrong service, and a status mapping that
+// collapses everything to 500 makes "file not found" indistinguishable from
+// "the agent is wedged" — the SDK then retries the one that can never succeed.
+
+// The customer's own server is reachable, path and query intact.
+func TestPortProxyReachesCustomerServer(t *testing.T) {
+ var gotPath, gotQuery string
+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotQuery = r.URL.Path, r.URL.RawQuery
+ _, _ = io.WriteString(w, "hello from the sandbox")
+ }))
+ defer backend.Close()
+
+ _, port, err := net.SplitHostPort(strings.TrimPrefix(backend.URL, "http://"))
+ if err != nil {
+ t.Fatalf("split backend addr: %v", err)
+ }
+
+ s := &server{}
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, ocPortPrefix+port+"/api/users?limit=5", nil)
+ s.ocPort(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
+ }
+ if body := rec.Body.String(); body != "hello from the sandbox" {
+ t.Errorf("body = %q, want the customer server's response", body)
+ }
+ // The /oc/port/<port> prefix must be stripped: forwarding it would make
+ // every customer route 404 against their own server.
+ if gotPath != "/api/users" {
+ t.Errorf("forwarded path = %q, want /api/users — the port prefix leaked through", gotPath)
+ }
+ if gotQuery != "limit=5" {
+ t.Errorf("forwarded query = %q, want limit=5", gotQuery)
+ }
+}
+
+// Our own ports are refused. Proxying to the hook port is an infinite loop that
+// takes down the box's only listener; the agent port is not the customer's to
+// reach.
+func TestPortProxyRefusesReservedPorts(t *testing.T) {
+ s := &server{}
+ for _, port := range []string{"8080", "8081"} {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, ocPortPrefix+port+"/", nil)
+ s.ocPort(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Errorf("port %s: status = %d, want 403", port, rec.Code)
+ }
+ }
+}
+
+func TestPortProxyRejectsBadPort(t *testing.T) {
+ s := &server{}
+ for _, path := range []string{"notaport/", "0/", "99999/", ""} {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, ocPortPrefix+path, nil)
+ s.ocPort(rec, req)
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("path %q: status = %d, want 400", path, rec.Code)
+ }
+ }
+}
+
+// Nothing listening is a 502 with an explanation, not a hang or a 500. This is
+// the ordinary state while a customer's server is still starting up.
+func TestPortProxyReportsNothingListening(t *testing.T) {
+ // Bind and immediately release, so the port is almost certainly free.
+ l, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatalf("listen: %v", err)
+ }
+ _, port, _ := net.SplitHostPort(l.Addr().String())
+ _ = l.Close()
+
+ s := &server{}
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, ocPortPrefix+port+"/", nil)
+ s.ocPort(rec, req)
+
+ if rec.Code != http.StatusBadGateway {
+ t.Errorf("status = %d, want 502", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "nothing is listening") {
+ t.Errorf("body = %q, want an explanation naming the port", rec.Body.String())
+ }
+}
+
+// A missing file must not look like a broken agent. The control plane cannot
+// see gRPC codes from outside the guest, so this mapping is the only thing that
+// distinguishes a normal answer from a fault.
+func TestErrorMappingDistinguishesFaultFromAnswer(t *testing.T) {
+ cases := []struct {
+ code codes.Code
+ want int
+ }{
+ {codes.NotFound, http.StatusNotFound},
+ {codes.InvalidArgument, http.StatusBadRequest},
+ {codes.PermissionDenied, http.StatusForbidden},
+ {codes.AlreadyExists, http.StatusConflict},
+ {codes.Unavailable, http.StatusServiceUnavailable},
+ {codes.ResourceExhausted, http.StatusInsufficientStorage},
+ {codes.Internal, http.StatusInternalServerError},
+ {codes.Unknown, http.StatusInternalServerError},
+ }
+ for _, c := range cases {
+ rec := httptest.NewRecorder()
+ fail(rec, "test", status.Error(c.code, "boom"))
+ if rec.Code != c.want {
+ t.Errorf("gRPC %v -> HTTP %d, want %d", c.code, rec.Code, c.want)
+ }
+ }
+}
+
+// The front door must win over the catch-all bridge to the agent. Without an
+// explicit registration a JSON POST to /oc/fs/read is forwarded to the agent's
+// gRPC listener, which answers 415 with no explanation.
+func TestOCRoutesBeatTheAgentCatchAll(t *testing.T) {
+ mux := http.NewServeMux()
+ catchAll := false
+ mux.HandleFunc("/", func(http.ResponseWriter, *http.Request) { catchAll = true })
+ (&server{}).registerOC(mux)
+
+ for _, path := range []string{
+ ocFSPrefix + "read", ocFSPrefix + "write", ocFSPrefix + "list",
+ ocFSPrefix + "mkdir", ocFSPrefix + "rm", ocFSPrefix + "exists",
+ ocFSPrefix + "stat", ocFSPrefix + "download", ocFSPrefix + "upload",
+ ocStatsPath, ocRebootPath, ocPortPrefix + "3000/",
+ ocRunPath, ocClaimPath, ocClaimRunPath,
+ } {
+ _, pattern := mux.Handler(httptest.NewRequest(http.MethodPost, path, nil))
+ if pattern == "/" {
+ t.Errorf("%s fell through to the agent catch-all", path)
+ }
+ }
+ if catchAll {
+ t.Error("catch-all ran during registration")
+ }
+}
+
+// The old prefix keeps working. The deployed control plane speaks /osb, and an
+// image that served only /oc would break every box the moment it rolled.
+func TestLegacyOSBPathsStillRegistered(t *testing.T) {
+ mux := http.NewServeMux()
+ mux.HandleFunc(runCmdPath, (&server{}).handleRunCmd)
+ (&server{}).registerOC(mux)
+
+ _, pattern := mux.Handler(httptest.NewRequest(http.MethodPost, runCmdPath, nil))
+ if pattern != runCmdPath {
+ t.Errorf("legacy %s resolved to %q — a rolling image would break the deployed control plane", runCmdPath, pattern)
+ }
+}
diff --git a/cmd/microvm-hooks/oc_util.go b/cmd/microvm-hooks/oc_util.go
new file mode 100644
index 00000000..8127af0a
--- /dev/null
+++ b/cmd/microvm-hooks/oc_util.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "context"
+ "encoding/base64"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "strconv"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// capBuffer collects a bounded amount of a subprocess's stderr.
+//
+// Bounded because tar can be extremely chatty about files that changed while it
+// read them, and an unbounded buffer on a box this small is a memory leak with
+// a customer's workspace as the input.
+type capBuffer struct {
+ mu sync.Mutex
+ b []byte
+ max int
+}
+
+func (c *capBuffer) Write(p []byte) (int, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.max == 0 {
+ c.max = 8 << 10
+ }
+ if room := c.max - len(c.b); room > 0 {
+ if len(p) < room {
+ room = len(p)
+ }
+ c.b = append(c.b, p[:room]...)
+ }
+ // Always report the full write: a short write makes exec.Cmd treat a
+ // truncated log as a broken pipe and kill the process.
+ return len(p), nil
+}
+
+func (c *capBuffer) String() string {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return string(c.b)
+}
+
+// copyFlush streams src to dst, flushing after every chunk.
+//
+// Without the flush a large archive sits in the response buffer and the caller
+// sees nothing until it completes — which for a slow transfer is
+// indistinguishable from a hang, and for a proxy with an idle timeout is a
+// failure.
+func copyFlush(dst io.Writer, src io.Reader) (int64, error) {
+ flusher, _ := dst.(http.Flusher)
+ buf := make([]byte, 256<<10)
+ var total int64
+ for {
+ n, rerr := src.Read(buf)
+ if n > 0 {
+ w, werr := dst.Write(buf[:n])
+ total += int64(w)
+ if werr != nil {
+ return total, werr
+ }
+ if flusher != nil {
+ flusher.Flush()
+ }
+ }
+ if rerr == io.EOF {
+ return total, nil
+ }
+ if rerr != nil {
+ return total, rerr
+ }
+ }
+}
+
+func b64(b []byte) string { return base64.StdEncoding.EncodeToString(b) }
+
+func unb64(s string) ([]byte, error) { return base64.StdEncoding.DecodeString(s) }
+
+// contextWithTimeout bounds a request-scoped operation without letting the
+// caller's disconnect be the only thing that stops it.
+func contextWithTimeout(r *http.Request, d time.Duration) (context.Context, context.CancelFunc) {
+ return context.WithTimeout(r.Context(), d)
+}
+
+// killSandboxProcesses SIGKILLs everything owned by the sandbox user, and
+// reports how many it signalled.
+//
+// Walks /proc directly because procps-ng is not installed in this image — see
+// the call site. A directory's owner IS the process's real uid, which is the
+// same test `pkill -u` applies.
+//
+// PID 1 is skipped defensively: it is this process, it is root, and killing it
+// would take the box down. The uid check already excludes it; the explicit skip
+// is there because the cost of being wrong is the whole sandbox.
+func killSandboxProcesses() int {
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ log.Printf("microvm-hooks: read /proc: %v", err)
+ return 0
+ }
+ killed := 0
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil || pid <= 1 {
+ continue
+ }
+ info, err := os.Stat("/proc/" + e.Name())
+ if err != nil {
+ continue // exited between the listing and the stat
+ }
+ st, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || st.Uid != sandboxUID {
+ continue
+ }
+ if err := syscall.Kill(pid, syscall.SIGKILL); err == nil {
+ killed++
+ }
+ }
+ return killed
+}
diff --git a/cmd/microvm-hooks/oc_workspace.go b/cmd/microvm-hooks/oc_workspace.go
new file mode 100644
index 00000000..c287053a
--- /dev/null
+++ b/cmd/microvm-hooks/oc_workspace.go
@@ -0,0 +1,169 @@
+package main
+
+// oc_workspace.go — archiving the customer's work out of the guest, and back in.
+//
+// This is the primitive behind checkpoints on this runtime, and it is the only
+// kind of checkpoint the service can support: there is no way to snapshot a
+// running MicroVM into an image we control (an image is BUILT through an API,
+// not captured), so a checkpoint here is the workspace, not the machine.
+//
+// Streamed both ways, deliberately. The agent path's equivalent execs `tar czf`
+// to a file in /tmp and then reads the file back out — which needs the archive
+// to fit on the guest's disk ALONGSIDE the data it just archived, and doubles
+// the time. Piping tar's stdout straight into the HTTP response costs neither.
+//
+// What survives: everything under /home/sandbox. What does not: anything the
+// customer installed elsewhere at runtime, and all process/memory state. That
+// is a real difference from a QEMU checkpoint and belongs in the docs, not in a
+// comment nobody reads — but it is also the part customers actually fork.
+
+import (
+ "log"
+ "net/http"
+ "os"
+ "os/exec"
+)
+
+const (
+ ocWorkspaceExport = ocPrefix + "workspace/export"
+ ocWorkspaceImport = ocPrefix + "workspace/import"
+
+ // workspaceDir is the customer's working directory — where commands run and
+ // where relative paths land.
+ workspaceDir = sandboxHomeDir
+)
+
+// archiveRoots are the paths a checkpoint captures, relative to /.
+//
+// JUST THE WORKSPACE, and the reason is worth recording because the obvious
+// improvement is wrong here.
+//
+// Widening this to /usr/local and /opt looks compelling — that is where things
+// built from source and dropped-in binaries land, and capturing them would make
+// a template carry a customer's whole environment rather than just their files.
+// It was tried, on dev, and measured:
+//
+// - The customer CANNOT WRITE to either path. Both are root-owned, commands
+// run as the unprivileged sandbox user, and sudo cannot elevate because the
+// MicroVM runs with no_new_privs set. So there is nothing of theirs there
+// to capture — the same platform constraint that makes FUSE mounts
+// impossible.
+// - It captured OUR files instead. /usr/local/bin holds rclone, so every
+// customer checkpoint grew from 603 bytes to 48 MB of base image, and a
+// restore would have overwritten our own binaries with a stale copy.
+//
+// The way to let a customer keep an installed toolchain is therefore to put the
+// toolchain INSIDE the workspace — see the user-space install defaults in the
+// image (PATH, npm prefix, PIP_USER), which land everything under
+// /home/sandbox/.local and are captured by this archive for free.
+var archiveRoots = []string{"home/sandbox"}
+
+// existingRoots filters archiveRoots to what is actually present. tar fails the
+// whole archive on a missing member, and /opt is legitimately absent on a fresh
+// box.
+func existingRoots() []string {
+ out := make([]string, 0, len(archiveRoots))
+ for _, r := range archiveRoots {
+ if _, err := os.Stat("/" + r); err == nil {
+ out = append(out, r)
+ }
+ }
+ return out
+}
+
+// ocWorkspaceExport streams a gzipped tar of the archived roots.
+//
+// Rooted at / with explicit members, so the archive carries paths like
+// `home/sandbox/...` and `usr/local/...` and a restore puts each one back where
+// it came from. The previous format was `-C /home/sandbox .`, which produced
+// bare `./...` entries — those two are NOT interchangeable, which is why the
+// storage key changed with the format (see WorkspaceKey): extracting an old
+// archive under the new importer would scatter a customer's home directory
+// across /.
+func (s *server) ocWorkspaceExport(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ roots := existingRoots()
+ if len(roots) == 0 {
+ http.Error(w, "export: nothing to archive", http.StatusInternalServerError)
+ return
+ }
+ args := append([]string{"czf", "-", "-C", "/"}, roots...)
+ cmd := exec.CommandContext(r.Context(), "tar", args...)
+ stdout, err := cmd.StdoutPipe()
+ if err != nil {
+ http.Error(w, "export: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ // Captured rather than inherited: tar writes "file changed as we read it" to
+ // stderr for anything the customer touches mid-archive, and that is a
+ // warning, not a failure. Letting it reach the response would corrupt the
+ // archive; letting it reach the container log unread would hide real errors.
+ var stderr capBuffer
+ cmd.Stderr = &stderr
+
+ if err := cmd.Start(); err != nil {
+ http.Error(w, "export: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ // Headers before the first byte, and no Content-Length: the size is not
+ // known until tar finishes, and a chunked body is exactly what the proxy
+ // forwards unchanged.
+ w.Header().Set("Content-Type", "application/gzip")
+ w.WriteHeader(http.StatusOK)
+
+ n, copyErr := copyFlush(w, stdout)
+ waitErr := cmd.Wait()
+ if copyErr != nil || waitErr != nil {
+ // The status is already 200 and bytes are on the wire, so nothing can be
+ // signalled to the caller here. Logged loudly because a truncated
+ // archive that nobody notices is a checkpoint that silently loses data —
+ // the caller's own size check is what catches it.
+ log.Printf("microvm-hooks: workspace export FAILED after %d bytes: copy=%v wait=%v stderr=%s",
+ n, copyErr, waitErr, stderr.String())
+ return
+ }
+ log.Printf("microvm-hooks: workspace export ok (%d bytes)", n)
+}
+
+// ocWorkspaceImport extracts a gzipped tar into the workspace.
+//
+// Additive, not a replacement: tar overwrites what the archive contains and
+// leaves everything else alone. That is the behaviour a restore wants — a
+// checkpoint carries what existed when it was taken, and wiping the directory
+// first would delete files created since, on a box the customer is still using.
+func (s *server) ocWorkspaceImport(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut && r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ // --no-same-owner: this process is root, so tar would otherwise restore the
+ // uids recorded in the archive. They come from the same image and would
+ // normally match, but "normally" is doing too much work for something that
+ // silently hands the customer files they cannot write. Ownership is fixed up
+ // below instead.
+ cmd := exec.CommandContext(r.Context(), "tar", "xzf", "-", "-C", "/", "--no-same-owner")
+ cmd.Stdin = r.Body
+ var stderr capBuffer
+ cmd.Stderr = &stderr
+
+ if err := cmd.Run(); err != nil {
+ log.Printf("microvm-hooks: workspace import failed: %v (%s)", err, stderr.String())
+ http.Error(w, "import: "+err.Error()+": "+stderr.String(), http.StatusInternalServerError)
+ return
+ }
+ // The customer's code runs as `sandbox`; a workspace it cannot write is
+ // worse than no restore at all, because it fails later and somewhere else.
+ // Only the workspace is chowned. /usr/local and /opt stay root-owned, which
+ // is what they are on a fresh box — handing the sandbox user write access to
+ // them would let a restore quietly widen its own privileges.
+ if out, err := exec.Command("chown", "-R", "sandbox:sandbox", workspaceDir).CombinedOutput(); err != nil {
+ log.Printf("microvm-hooks: workspace import: chown: %v (%s)", err, out)
+ http.Error(w, "import: chown failed", http.StatusInternalServerError)
+ return
+ }
+ log.Printf("microvm-hooks: workspace import ok")
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
diff --git a/deploy/microvm/Dockerfile b/deploy/microvm/Dockerfile
index 94208071..9efae93a 100644
--- a/deploy/microvm/Dockerfile
+++ b/deploy/microvm/Dockerfile
@@ -17,18 +17,58 @@
# be arm64 or the build fails before this file is ever executed.
FROM public.ecr.aws/lambda/microvms:al2023-minimal
-# Runtimes the TTI benchmark and most first commands reach for. Kept small on
-# purpose — see the note above about runtime parity being a later, separate job.
+# The sandbox's toolchain.
+#
+# This list is the al2023 equivalent of what the QEMU fleet ships
+# (deploy/firecracker/rootfs/Dockerfile.default, Ubuntu 22.04). It used to be
+# six packages — nodejs, python3, tar, gzip, ca-certificates, shadow-utils —
+# which measured, from inside a live sandbox, as:
+#
+# HAVE curl node npm python3 pip3 openssl
+# MISS git wget make gcc g++ vim nano ps top unzip zip jq ssh rsync sudo sqlite3
+#
+# No git is the one that matters most: cloning a repo is the first thing most
+# agents do, and it simply was not there. No compilers meant any `pip install`
+# needing a native extension failed. That is not a runtime a QEMU customer can
+# be moved onto, whatever the API surface says.
#
# shadow-utils is not optional: it provides useradd. The minimal base does not
# ship it, and without it the sandbox user below is never created — which shows
# up much later as every exec failing with "fork/exec /bin/sh: no such file or
# directory", because the agent runs commands in /home/sandbox and Go reports a
# missing working directory as if the binary were missing.
-RUN dnf install -y nodejs python3 tar gzip ca-certificates shadow-utils \
+#
+# fuse/fuse3 and rclone are here for the mounts feature: internal/mounts drives
+# it entirely through manager.WriteFile + manager.Exec (it writes an rclone
+# config into the guest and runs `rclone mount`), so mounts are not host-side
+# and need nothing but these binaries and a working /dev/fuse.
+# curl-minimal ships in the base and conflicts with the full curl that git
+# pulls in, so swap it first. NOTE the install below has no --allowerasing:
+# this base runs dnf5, which does not have that flag ("error: Unknown option
+# --allowerasing"). The swap is what resolves the conflict.
+RUN dnf -y swap curl-minimal curl
+RUN dnf install -y \
+ bash ca-certificates shadow-utils sudo findutils which procps-ng \
+ nano vim-minimal less \
+ wget openssh-clients iproute iputils bind-utils \
+ git \
+ tar gzip bzip2 xz zip unzip \
+ gcc gcc-c++ make automake cmake pkgconf-pkg-config \
+ openssl openssl-devel libffi-devel zlib-devel \
+ jq sqlite sqlite-devel \
+ nodejs python3 python3-pip python3-devel \
+ fuse fuse3 rsync \
&& dnf clean all \
&& rm -rf /var/cache/dnf
+# rclone is not in the al2023 repositories, and mounts need it. Fetched by
+# architecture rather than pinned to x86: this image is ARM_64 only.
+RUN set -eux; \
+ arch="$(uname -m)"; case "$arch" in aarch64) rc=arm64 ;; x86_64) rc=amd64 ;; *) rc=arm64 ;; esac; \
+ curl -fsSL -o /tmp/rclone.zip "https://downloads.rclone.org/rclone-current-linux-${rc}.zip"; \
+ cd /tmp && unzip -q rclone.zip && cp rclone-*-linux-${rc}/rclone /usr/local/bin/rclone; \
+ chmod +x /usr/local/bin/rclone; rm -rf /tmp/rclone.zip /tmp/rclone-*-linux-${rc}
+
# osb-agent is the same binary the QEMU backend runs in-guest; only its
# listener differs (TCP here, virtio-serial there), selected by the env var the
# hook server sets when it spawns the agent.
@@ -45,6 +85,32 @@ RUN chmod +x /usr/local/bin/osb-agent /usr/local/bin/microvm-hooks
RUN useradd --create-home --shell /bin/bash sandbox \
&& test -d /home/sandbox
+# Passwordless sudo for the sandbox user, matching the QEMU rootfs (which ships
+# sudo for the same reason). internal/mounts execs `sudo chmod` on the rclone
+# config it writes, so without this the mounts feature fails at its second step.
+RUN echo 'sandbox ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/sandbox \
+ && chmod 0440 /etc/sudoers.d/sandbox
+
+# User-space install defaults.
+#
+# The customer runs unprivileged and cannot write to /usr/local or /opt (sudo
+# cannot elevate — the MicroVM sets no_new_privs), so a toolchain they install
+# has to live under their home directory to exist at all. Pointing the package
+# managers there additionally means a checkpoint CAPTURES it, because the
+# workspace archive covers /home/sandbox — a template can then carry an
+# installed environment without any custom image.
+#
+# PIP_USER makes `pip install X` land in ~/.local without the customer having to
+# remember --user; PIP_BREAK_SYSTEM_PACKAGES is needed alongside it because pip
+# otherwise refuses to touch an externally-managed environment.
+ENV PIP_USER=1 \
+ PIP_BREAK_SYSTEM_PACKAGES=1 \
+ NPM_CONFIG_PREFIX=/home/sandbox/.npm-global \
+ PATH=/home/sandbox/.local/bin:/home/sandbox/.npm-global/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/bin:/sbin
+
+RUN mkdir -p /home/sandbox/.local/bin /home/sandbox/.npm-global/bin \
+ && chown -R sandbox:sandbox /home/sandbox/.local /home/sandbox/.npm-global
+
# Documentation only. Lambda's proxy forwards guest traffic solely to the port
# declared in the image's hook configuration (8080) — EXPOSE does not influence
# that, which was confirmed by adding 8081 here and watching it stay 502.