An open-source, faster Devin alternative
TypeScript
fuse mounts v1
Brian Reardon94150946c69d
diff --git a/cmd/oc/internal/commands/mounts.go b/cmd/oc/internal/commands/mounts.gonew file mode 100644index 00000000..ddd121ed--- /dev/null+++ b/cmd/oc/internal/commands/mounts.go@@ -0,0 +1,157 @@+package commands++import (+ "fmt"+ "net/url"+ "os"+ "strings"++ "github.com/opensandbox/opensandbox/cmd/oc/internal/client"+ "github.com/spf13/cobra"+)++// MountInfo mirrors internal/api.MountRecord — copied here to avoid an+// internal-package import from the CLI binary.+type MountInfo struct {+ Path string `json:"path"`+ Remote string `json:"remote"`+ Backend string `json:"backend,omitempty"`+ ReadOnly bool `json:"readOnly"`+}++var mountsCmd = &cobra.Command{+ Use: "mounts",+ Aliases: []string{"mount"},+ Short: "Manage FUSE-backed remote filesystem mounts inside a sandbox",+ Long: `Mount remote filesystems (S3, GCS, Azure Blob, SFTP, WebDAV, Dropbox)+inside a running sandbox via rclone+FUSE. Credentials are passed inline and+never persisted on the worker. Mounts are torn down on hibernate; v1 does NOT+auto-restore on wake — re-run "oc mounts add" after waking the sandbox.`,+}++var mountsAddCmd = &cobra.Command{+ Use: "add <sandbox-id>",+ Short: "Add a mount",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())++ path, _ := cmd.Flags().GetString("path")+ remote, _ := cmd.Flags().GetString("remote")+ backend, _ := cmd.Flags().GetString("backend")+ credsFlag, _ := cmd.Flags().GetStringArray("cred")+ configFile, _ := cmd.Flags().GetString("config-file")+ readWrite, _ := cmd.Flags().GetBool("read-write")+ extraOpts, _ := cmd.Flags().GetStringArray("opt")++ creds := map[string]string{}+ for _, kv := range credsFlag {+ i := strings.Index(kv, "=")+ if i <= 0 {+ return fmt.Errorf("--cred must be key=value (got %q)", kv)+ }+ creds[kv[:i]] = kv[i+1:]+ }++ body := map[string]any{+ "path": path,+ "remote": remote,+ "readOnly": !readWrite,+ }+ if backend != "" {+ body["backend"] = backend+ }+ if len(creds) > 0 {+ body["creds"] = creds+ }+ if configFile != "" {+ raw, err := os.ReadFile(configFile)+ if err != nil {+ return fmt.Errorf("read --config-file: %w", err)+ }+ body["rcloneConfig"] = string(raw)+ }+ if len(extraOpts) > 0 {+ body["mountOptions"] = extraOpts+ }++ var info MountInfo+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/mounts", args[0]), body, &info); err != nil {+ return err+ }++ printer.Print(info, func() {+ ro := "rw"+ if info.ReadOnly {+ ro = "ro"+ }+ fmt.Printf("Mounted %s → %s (%s)\n", info.Remote, info.Path, ro)+ })+ return nil+ },+}++var mountsListCmd = &cobra.Command{+ Use: "list <sandbox-id>",+ Short: "List mounts for a sandbox",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())++ var mounts []MountInfo+ if err := c.Get(cmd.Context(), fmt.Sprintf("/sandboxes/%s/mounts", args[0]), &mounts); err != nil {+ return err+ }++ printer.Print(mounts, func() {+ if len(mounts) == 0 {+ fmt.Println("No mounts.")+ return+ }+ headers := []string{"PATH", "REMOTE", "BACKEND", "MODE"}+ var rows [][]string+ for _, m := range mounts {+ mode := "rw"+ if m.ReadOnly {+ mode = "ro"+ }+ rows = append(rows, []string{m.Path, m.Remote, m.Backend, mode})+ }+ printer.Table(headers, rows)+ })+ return nil+ },+}++var mountsRemoveCmd = &cobra.Command{+ Use: "rm <sandbox-id> <path>",+ Aliases: []string{"remove"},+ Short: "Unmount a path in a sandbox",+ Args: cobra.ExactArgs(2),+ RunE: func(cmd *cobra.Command, args []string) error {+ c := client.FromContext(cmd.Context())+ target := args[1]+ ep := fmt.Sprintf("/sandboxes/%s/mounts?path=%s", args[0], url.QueryEscape(target))+ if err := c.DeleteIgnoreNotFound(cmd.Context(), ep); err != nil {+ return err+ }+ fmt.Printf("Unmounted %s.\n", target)+ return nil+ },+}++func init() {+ mountsAddCmd.Flags().String("path", "", "Absolute path inside the sandbox to mount at (required)")+ mountsAddCmd.Flags().String("remote", "", "rclone remote spec, e.g. s3:my-bucket (required)")+ mountsAddCmd.Flags().String("backend", "", "Backend type: s3, gcs, azureblob, sftp, webdav, dropbox")+ mountsAddCmd.Flags().StringArray("cred", nil, "Backend credential as key=value (repeatable; e.g. --cred access_key_id=AKIA...)")+ mountsAddCmd.Flags().String("config-file", "", "Path to a raw rclone config file (overrides --backend/--cred)")+ mountsAddCmd.Flags().Bool("read-write", false, "Mount read-write (default is read-only)")+ mountsAddCmd.Flags().StringArray("opt", nil, "Extra args appended to `rclone mount` (repeatable)")+ _ = mountsAddCmd.MarkFlagRequired("path")+ _ = mountsAddCmd.MarkFlagRequired("remote")++ mountsCmd.AddCommand(mountsAddCmd)+ mountsCmd.AddCommand(mountsListCmd)+ mountsCmd.AddCommand(mountsRemoveCmd)+}diff --git a/cmd/oc/internal/commands/root.go b/cmd/oc/internal/commands/root.goindex 4ad73120..b5e44e00 100644--- a/cmd/oc/internal/commands/root.go+++ b/cmd/oc/internal/commands/root.go@@ -67,6 +67,7 @@ func init() {rootCmd.AddCommand(checkpointCmd)rootCmd.AddCommand(patchCmd)rootCmd.AddCommand(previewCmd)+ rootCmd.AddCommand(mountsCmd)rootCmd.AddCommand(secretStoreCmd)rootCmd.AddCommand(secretCmd)rootCmd.AddCommand(configCmd)diff --git a/deploy/firecracker/rootfs/Dockerfile.default b/deploy/firecracker/rootfs/Dockerfile.defaultindex f811ebeb..b374d18a 100644--- a/deploy/firecracker/rootfs/Dockerfile.default+++ b/deploy/firecracker/rootfs/Dockerfile.default@@ -71,8 +71,21 @@ RUN apt-get update && apt-get install -y --no-install-recommends \# Process supervisor — for users who want declarative service management# without systemd. Started on demand by users (`sudo supervisord -c ...`).supervisor \+ # FUSE userspace bits + rclone — backs `sandbox.mounts.add(...)`. rclone is+ # one binary covering ~40 backends (S3, GCS, Azure Blob, SFTP, WebDAV, ...).+ # Mounts are torn down on hibernate (worker calls `fusermount3 -u -a`+ # before savevm) and do NOT auto-restore on wake in v1 — callers re-issue+ # mounts.add post-wake.+ fuse3 \+ libfuse3-3 \+ rclone \&& rm -rf /var/lib/apt/lists/*+# Allow non-root users to pass --allow-other to FUSE mounts so processes+# running as the `sandbox` user can read mounts created via sudo.+RUN echo "user_allow_other" > /etc/fuse.conf \+ && chmod 644 /etc/fuse.conf+# ── Python setup ─────────────────────────────────────────────────────────────RUN ln -sf /usr/bin/python3 /usr/bin/python \&& pip3 install --no-cache-dir --upgrade \diff --git a/internal/api/router.go b/internal/api/router.goindex c492d1ea..dc3bad09 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -59,6 +59,7 @@ type Server struct {sandboxDomain string // base domain for sandbox subdomainscfClient *cloudflare.Client // nil if Cloudflare not configuredpendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking+ mounts *mountRegistry // process-local FUSE mount tracker; cleared on hibernatesandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)stripeClient *billing.StripeClient // nil if Stripe not configuredredisClient *redis.Client // nil if Redis not configured (for health checks)@@ -134,6 +135,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oecho: e,manager: mgr,ptyManager: ptyMgr,+ mounts: newMountRegistry(),}if opts != nil {@@ -458,6 +460,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/:id/files/mkdir", pxy)api.DELETE("/sandboxes/:id/files", pxy)+ // Mounts (FUSE)+ api.POST("/sandboxes/:id/mounts", pxy)+ api.GET("/sandboxes/:id/mounts", pxy)+ api.DELETE("/sandboxes/:id/mounts", pxy)+// PTYapi.POST("/sandboxes/:id/pty", pxy)api.GET("/sandboxes/:id/pty/:sessionID", pxy)@@ -489,6 +496,10 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, oapi.POST("/sandboxes/:id/files/mkdir", s.makeDir)api.DELETE("/sandboxes/:id/files", s.removeFile)+ api.POST("/sandboxes/:id/mounts", s.addMount)+ api.GET("/sandboxes/:id/mounts", s.listMounts)+ api.DELETE("/sandboxes/:id/mounts", s.removeMount)+api.POST("/sandboxes/:id/pty", s.createPTY)api.GET("/sandboxes/:id/pty/:sessionID", s.ptyWebSocket)api.POST("/sandboxes/:id/pty/:sessionID/resize", s.resizePTY)diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex dbd4b400..4b1961ef 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1667,6 +1667,13 @@ func (s *Server) hibernateSandbox(c echo.Context) error {})}+ // FUSE mounts are torn down by the hibernate path (snapshot.go runs+ // `fusermount3 -u -a`) and v1 doesn't auto-restore them on wake — clear+ // the registry so list() reflects reality post-wake.+ if s.mounts != nil {+ s.mounts.clear(id)+ }+// Mark hibernated in sandbox routerif s.router != nil {timeout := 600 // default for explicit hibernatediff --git a/internal/api/sandbox_mounts.go b/internal/api/sandbox_mounts.gonew file mode 100644index 00000000..8148b09b--- /dev/null+++ b/internal/api/sandbox_mounts.go@@ -0,0 +1,331 @@+package api++import (+ "context"+ "crypto/sha1"+ "encoding/hex"+ "fmt"+ "net/http"+ "sort"+ "strings"+ "sync"++ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/pkg/types"+)++// MountRecord describes one active rclone-backed FUSE mount inside a sandbox.+// Creds are intentionally absent — they live only in the in-VM tmpfs config+// file written during addMount. The worker keeps no copy.+type MountRecord struct {+ Path string `json:"path"`+ Remote string `json:"remote"`+ Backend string `json:"backend,omitempty"`+ ReadOnly bool `json:"readOnly"`+}++// mountRegistry is a process-local map of active mounts per sandbox. v1+// intentionally doesn't persist mounts across hibernate or worker restarts;+// the hibernate path runs `fusermount3 -u -a` defensively before savevm+// regardless of what's in here, so a stale or empty registry is never a+// correctness problem — at worst, list() under-reports.+type mountRegistry struct {+ mu sync.Mutex+ m map[string][]MountRecord+}++func newMountRegistry() *mountRegistry {+ return &mountRegistry{m: make(map[string][]MountRecord)}+}++func (r *mountRegistry) put(sandboxID string, rec MountRecord) {+ r.mu.Lock()+ defer r.mu.Unlock()+ cur := r.m[sandboxID]+ for i := range cur {+ if cur[i].Path == rec.Path {+ cur[i] = rec+ r.m[sandboxID] = cur+ return+ }+ }+ r.m[sandboxID] = append(cur, rec)+}++func (r *mountRegistry) remove(sandboxID, path string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ cur := r.m[sandboxID]+ out := cur[:0]+ for _, rec := range cur {+ if rec.Path != path {+ out = append(out, rec)+ }+ }+ if len(out) == 0 {+ delete(r.m, sandboxID)+ } else {+ r.m[sandboxID] = out+ }+}++func (r *mountRegistry) get(sandboxID string) []MountRecord {+ r.mu.Lock()+ defer r.mu.Unlock()+ cur := r.m[sandboxID]+ if len(cur) == 0 {+ return nil+ }+ out := make([]MountRecord, len(cur))+ copy(out, cur)+ return out+}++func (r *mountRegistry) clear(sandboxID string) {+ r.mu.Lock()+ defer r.mu.Unlock()+ delete(r.m, sandboxID)+}++type addMountRequest struct {+ Path string `json:"path"` // absolute path inside the VM+ Remote string `json:"remote"` // rclone remote spec, e.g. "s3:my-bucket/sub"+ Backend string `json:"backend"` // one of s3, gcs, azureblob, sftp, webdav, dropbox+ Creds map[string]string `json:"creds"` // backend-specific config keys+ RcloneConfig string `json:"rcloneConfig"` // raw rclone config; takes precedence over backend+creds+ ReadOnly *bool `json:"readOnly"` // default true+ MountOptions []string `json:"mountOptions"` // extra args appended to `rclone mount`+}++func (s *Server) addMount(c echo.Context) error {+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ id := c.Param("id")++ var req addMountRequest+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body: " + err.Error()})+ }+ if req.Path == "" || req.Remote == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path and remote are required"})+ }+ if !strings.HasPrefix(req.Path, "/") {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path must be absolute"})+ }++ rcloneConf, err := renderRcloneConfig(req)+ if err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})+ }+ readOnly := true+ if req.ReadOnly != nil {+ readOnly = *req.ReadOnly+ }++ confPath := mountConfPath(req.Path)+ target := req.Path++ routeOp := func(ctx context.Context) error {+ // Old-image guard: surface a clear error rather than letting the user+ // puzzle out a cryptic `exec: rclone: not found`.+ probe, perr := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sh",+ Args: []string{"-c", "command -v rclone >/dev/null 2>&1 && command -v fusermount3 >/dev/null 2>&1"},+ Timeout: 10,+ })+ if perr != nil {+ return fmt.Errorf("probe sandbox: %w", perr)+ }+ if probe == nil || probe.ExitCode != 0 {+ return fmt.Errorf("sandbox image is missing `rclone` and/or `fusermount3` — rebuild from the latest default rootfs to use mounts")+ }++ if _, err := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", "mkdir -p /run/oc-agent/mounts && chmod 700 /run/oc-agent/mounts"},+ Timeout: 10,+ }); err != nil {+ return fmt.Errorf("prepare config dir: %w", err)+ }++ if err := s.manager.WriteFile(ctx, id, confPath, rcloneConf); err != nil {+ return fmt.Errorf("write rclone config: %w", err)+ }+ // WriteFile creates mode 0644; tighten so the sandbox user can't read creds.+ if _, err := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"chmod", "600", confPath},+ Timeout: 5,+ }); err != nil {+ return fmt.Errorf("chmod config: %w", err)+ }++ if _, err := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", fmt.Sprintf("mkdir -p %q && chown sandbox:sandbox %q", target, target)},+ Timeout: 10,+ }); err != nil {+ return fmt.Errorf("prepare mount target: %w", err)+ }++ mountArgs := []string{+ "rclone", "mount", req.Remote, target,+ "--config", confPath,+ "--daemon",+ "--allow-other",+ }+ if readOnly {+ mountArgs = append(mountArgs, "--read-only")+ } else {+ mountArgs = append(mountArgs, "--vfs-cache-mode", "writes")+ }+ mountArgs = append(mountArgs, req.MountOptions...)++ resp, err := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: mountArgs,+ Timeout: 30,+ })+ if err != nil {+ return fmt.Errorf("rclone mount: %w", err)+ }+ if resp.ExitCode != 0 {+ // Best-effort cleanup of the config file so creds don't linger after+ // a failed mount.+ _, _ = s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"rm", "-f", confPath},+ Timeout: 5,+ })+ msg := strings.TrimSpace(resp.Stderr)+ if msg == "" {+ msg = strings.TrimSpace(resp.Stdout)+ }+ return fmt.Errorf("rclone mount failed (exit %d): %s", resp.ExitCode, msg)+ }+ return nil+ }++ if err := s.routeOrCall(c, id, "mountAdd", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ rec := MountRecord{+ Path: req.Path,+ Remote: req.Remote,+ Backend: req.Backend,+ ReadOnly: readOnly,+ }+ s.mounts.put(id, rec)+ return c.JSON(http.StatusCreated, rec)+}++func (s *Server) listMounts(c echo.Context) error {+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ id := c.Param("id")+ recs := s.mounts.get(id)+ if recs == nil {+ recs = []MountRecord{}+ }+ return c.JSON(http.StatusOK, recs)+}++func (s *Server) removeMount(c echo.Context) error {+ if s.manager == nil {+ return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)+ }+ id := c.Param("id")+ path := c.QueryParam("path")+ if path == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})+ }+ confPath := mountConfPath(path)++ routeOp := func(ctx context.Context) error {+ _, err := s.manager.Exec(ctx, id, types.ProcessConfig{+ Command: "sudo",+ Args: []string{"sh", "-c", fmt.Sprintf("fusermount3 -u %q 2>/dev/null; rm -f %q 2>/dev/null; true", path, confPath)},+ Timeout: 15,+ })+ return err+ }+ if err := s.routeOrCall(c, id, "mountRemove", routeOp); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ s.mounts.remove(id, path)+ return c.NoContent(http.StatusNoContent)+}++func (s *Server) routeOrCall(c echo.Context, sandboxID, opName string, op func(context.Context) error) error {+ if s.router != nil {+ return s.router.Route(c.Request().Context(), sandboxID, opName, op)+ }+ return op(c.Request().Context())+}++// mountConfPath derives a deterministic tmpfs config-file path from the mount+// target. Tying the filename to the path means add→remove for the same path+// always touches the same config, and there's no need to track an opaque ID.+func mountConfPath(path string) string {+ sum := sha1.Sum([]byte(path))+ return "/run/oc-agent/mounts/" + hex.EncodeToString(sum[:])[:16] + ".conf"+}++// renderRcloneConfig builds a single-section rclone config from the typed+// backend+creds shape, or returns the raw user-supplied config if present.+//+// The section name is taken from the part before the colon in `remote`+// (rclone's "name:path" convention), so a remote like "s3:my-bucket" produces+// `[s3]` and `rclone mount s3:my-bucket /target` resolves correctly.+func renderRcloneConfig(req addMountRequest) (string, error) {+ if req.RcloneConfig != "" {+ return req.RcloneConfig, nil+ }+ colon := strings.Index(req.Remote, ":")+ if colon <= 0 {+ return "", fmt.Errorf(`remote must be "<name>:<path>" (got %q) when rcloneConfig is not supplied`, req.Remote)+ }+ name := req.Remote[:colon]++ var typ string+ switch req.Backend {+ case "s3":+ typ = "s3"+ case "gcs":+ typ = "google cloud storage"+ case "azureblob":+ typ = "azureblob"+ case "sftp":+ typ = "sftp"+ case "webdav":+ typ = "webdav"+ case "dropbox":+ typ = "dropbox"+ case "":+ return "", fmt.Errorf("backend is required when rcloneConfig is not supplied (or pass rcloneConfig directly)")+ default:+ return "", fmt.Errorf("unsupported backend %q (supported: s3, gcs, azureblob, sftp, webdav, dropbox — or pass rcloneConfig directly)", req.Backend)+ }++ var b strings.Builder+ fmt.Fprintf(&b, "[%s]\ntype = %s\n", name, typ)+ if req.Backend == "s3" {+ if _, ok := req.Creds["provider"]; !ok {+ b.WriteString("provider = AWS\n")+ }+ }+ // Stable key order so config rendering is deterministic (helps golden tests+ // and rules out spurious config-file churn on repeated adds).+ keys := make([]string, 0, len(req.Creds))+ for k := range req.Creds {+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ fmt.Fprintf(&b, "%s = %s\n", k, req.Creds[k])+ }+ return b.String(), nil+}diff --git a/internal/api/sandbox_mounts_test.go b/internal/api/sandbox_mounts_test.gonew file mode 100644index 00000000..2e5c30fe--- /dev/null+++ b/internal/api/sandbox_mounts_test.go@@ -0,0 +1,201 @@+package api++import (+ "strings"+ "testing"+)++func TestRenderRcloneConfig_RawPassthrough(t *testing.T) {+ raw := "[whatever]\ntype = s3\nfoo = bar\n"+ got, err := renderRcloneConfig(addMountRequest{+ Remote: "whatever:bucket",+ RcloneConfig: raw,+ })+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ if got != raw {+ t.Errorf("raw passthrough mutated config: got %q want %q", got, raw)+ }+}++func TestRenderRcloneConfig_S3DefaultsAWSProvider(t *testing.T) {+ got, err := renderRcloneConfig(addMountRequest{+ Remote: "s3:my-bucket",+ Backend: "s3",+ Creds: map[string]string{+ "access_key_id": "AKIA",+ "secret_access_key": "SECRET",+ "region": "us-east-1",+ },+ })+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ // Section header derived from the remote name (before the colon).+ if !strings.HasPrefix(got, "[s3]\n") {+ t.Errorf("expected [s3] section header, got: %q", got)+ }+ // AWS default provider injected because Creds didn't set it.+ if !strings.Contains(got, "provider = AWS\n") {+ t.Errorf("expected provider=AWS default, got: %q", got)+ }+ // All three creds present.+ for _, want := range []string{+ "access_key_id = AKIA\n",+ "secret_access_key = SECRET\n",+ "region = us-east-1\n",+ "type = s3\n",+ } {+ if !strings.Contains(got, want) {+ t.Errorf("missing %q in config:\n%s", want, got)+ }+ }+}++func TestRenderRcloneConfig_S3UserProviderWins(t *testing.T) {+ got, err := renderRcloneConfig(addMountRequest{+ Remote: "minio:bucket",+ Backend: "s3",+ Creds: map[string]string{+ "provider": "Minio",+ "access_key_id": "key",+ "secret_access_key": "secret",+ "endpoint": "http://minio:9000",+ },+ })+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ if strings.Contains(got, "provider = AWS\n") {+ t.Errorf("user-supplied provider was overridden; config:\n%s", got)+ }+ if !strings.Contains(got, "provider = Minio\n") {+ t.Errorf("expected provider=Minio, got:\n%s", got)+ }+}++func TestRenderRcloneConfig_GCSHasTypeWithSpace(t *testing.T) {+ got, err := renderRcloneConfig(addMountRequest{+ Remote: "gcs:my-bucket",+ Backend: "gcs",+ Creds: map[string]string{"service_account_credentials": "{\"type\":\"service_account\"}"},+ })+ if err != nil {+ t.Fatalf("unexpected err: %v", err)+ }+ // rclone's type for GCS is literally "google cloud storage" (with spaces).+ if !strings.Contains(got, "type = google cloud storage\n") {+ t.Errorf("expected GCS type string, got:\n%s", got)+ }+}++func TestRenderRcloneConfig_DeterministicKeyOrder(t *testing.T) {+ creds := map[string]string{"zeta": "z", "alpha": "a", "mu": "m"}+ a, _ := renderRcloneConfig(addMountRequest{Remote: "sftp:host", Backend: "sftp", Creds: creds})+ b, _ := renderRcloneConfig(addMountRequest{Remote: "sftp:host", Backend: "sftp", Creds: creds})+ if a != b {+ t.Errorf("repeated render produced different output:\nA:\n%s\nB:\n%s", a, b)+ }+ // alpha must come before mu must come before zeta (sorted key order).+ idxA := strings.Index(a, "alpha = ")+ idxM := strings.Index(a, "mu = ")+ idxZ := strings.Index(a, "zeta = ")+ if !(idxA < idxM && idxM < idxZ) {+ t.Errorf("expected sorted key order alpha < mu < zeta, got:\n%s", a)+ }+}++func TestRenderRcloneConfig_RejectsBareRemote(t *testing.T) {+ _, err := renderRcloneConfig(addMountRequest{Remote: "no-colon-here", Backend: "s3"})+ if err == nil {+ t.Fatal("expected error for remote without colon, got nil")+ }+}++func TestRenderRcloneConfig_RejectsUnknownBackend(t *testing.T) {+ _, err := renderRcloneConfig(addMountRequest{Remote: "x:y", Backend: "minio-direct"})+ if err == nil {+ t.Fatal("expected error for unknown backend, got nil")+ }+ if !strings.Contains(err.Error(), "rcloneConfig") {+ t.Errorf("error should suggest rcloneConfig escape hatch, got: %v", err)+ }+}++func TestRenderRcloneConfig_RequiresBackendOrRawConfig(t *testing.T) {+ _, err := renderRcloneConfig(addMountRequest{Remote: "x:y"})+ if err == nil {+ t.Fatal("expected error when no backend and no rcloneConfig, got nil")+ }+}++func TestMountConfPath_DeterministicAndSafe(t *testing.T) {+ a := mountConfPath("/mnt/data")+ b := mountConfPath("/mnt/data")+ if a != b {+ t.Errorf("mountConfPath not deterministic: %q vs %q", a, b)+ }+ c := mountConfPath("/mnt/other")+ if a == c {+ t.Errorf("different paths produced same conf path: %q", a)+ }+ if !strings.HasPrefix(a, "/run/oc-agent/mounts/") || !strings.HasSuffix(a, ".conf") {+ t.Errorf("conf path doesn't match expected shape: %q", a)+ }+ // The id segment must be filesystem-safe (no slashes, no path traversal).+ id := strings.TrimSuffix(strings.TrimPrefix(a, "/run/oc-agent/mounts/"), ".conf")+ if strings.ContainsAny(id, "/.\\ ") {+ t.Errorf("conf id contains unsafe chars: %q", id)+ }+}++func TestMountRegistry_PutListRemove(t *testing.T) {+ r := newMountRegistry()+ r.put("sb-1", MountRecord{Path: "/mnt/a", Remote: "s3:a", Backend: "s3", ReadOnly: true})+ r.put("sb-1", MountRecord{Path: "/mnt/b", Remote: "s3:b", Backend: "s3", ReadOnly: false})+ r.put("sb-2", MountRecord{Path: "/mnt/x", Remote: "gcs:x", Backend: "gcs", ReadOnly: true})++ if got := r.get("sb-1"); len(got) != 2 {+ t.Errorf("sb-1 want 2 entries, got %d", len(got))+ }+ if got := r.get("sb-2"); len(got) != 1 {+ t.Errorf("sb-2 want 1 entry, got %d", len(got))+ }+ if got := r.get("sb-nope"); got != nil {+ t.Errorf("unknown sandbox should return nil, got %v", got)+ }++ // put with the same path updates in-place (not append).+ r.put("sb-1", MountRecord{Path: "/mnt/a", Remote: "s3:a-v2", Backend: "s3", ReadOnly: true})+ got := r.get("sb-1")+ if len(got) != 2 {+ t.Fatalf("re-put on same path should update, not append. Got %d entries: %v", len(got), got)+ }+ var found bool+ for _, rec := range got {+ if rec.Path == "/mnt/a" && rec.Remote == "s3:a-v2" {+ found = true+ }+ }+ if !found {+ t.Errorf("update didn't take effect: %v", got)+ }++ r.remove("sb-1", "/mnt/a")+ if got := r.get("sb-1"); len(got) != 1 || got[0].Path != "/mnt/b" {+ t.Errorf("after remove, expected [/mnt/b], got %v", got)+ }++ // Removing last entry should drop the sandbox key entirely (nil result).+ r.remove("sb-1", "/mnt/b")+ if got := r.get("sb-1"); got != nil {+ t.Errorf("after removing last entry, expected nil, got %v", got)+ }++ // clear() drops a sandbox even with entries.+ r.clear("sb-2")+ if got := r.get("sb-2"); got != nil {+ t.Errorf("after clear, expected nil, got %v", got)+ }+}diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.goindex 9f83f931..bb3c40de 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -76,6 +76,20 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto// failure → kernel panic loop). Bubble the error up so the API caller// gets a clear refusal instead of a silently-corrupted sandbox.if vm.agent != nil {+ // Tear down any FUSE mounts before savevm so the snapshot doesn't+ // capture broken file descriptors / hung kernel threads waiting on a+ // FUSE daemon that won't exist on wake. Best-effort and idempotent:+ // fusermount3 -u -a is a no-op when there are no FUSE mounts, and the+ // `|| true` belt-and-braces means a partial failure can't block+ // hibernate. v1 does not auto-restore mounts on wake; callers re-issue.+ umountCtx, umountCancel := context.WithTimeout(ctx, 5*time.Second)+ _, _ = vm.agent.Exec(umountCtx, &pb.ExecRequest{+ Command: "/bin/sh",+ Args: []string{"-c", "fusermount3 -u -a 2>/dev/null || true"},+ RunAsRoot: true,+ })+ umountCancel()+if err := quiesceAndCloseAgent(ctx, vm.agent); err != nil {log.Printf("qemu: hibernate %s: refusing savevm — %v", vm.ID, err)return nil, fmt.Errorf("hibernate %s: %w", vm.ID, err)diff --git a/sdks/python/opencomputer/__init__.py b/sdks/python/opencomputer/__init__.pyindex ae6b3471..3df2a7c1 100644--- a/sdks/python/opencomputer/__init__.py+++ b/sdks/python/opencomputer/__init__.py@@ -5,6 +5,7 @@ from opencomputer.agent import Agent, AgentEvent, AgentSession, AgentSessionInfofrom opencomputer.filesystem import Filesystemfrom opencomputer.exec import Exec, ProcessResult, ExecSession, ExecSessionInfofrom opencomputer.image import Image+from opencomputer.mounts import Mounts, MountInfofrom opencomputer.pty import Pty, PtySessionfrom opencomputer.shell import Shell, ShellBusyError, ShellClosedErrorfrom opencomputer.template import Template@@ -39,6 +40,8 @@ __all__ = ["ExecSession","ExecSessionInfo","Image",+ "Mounts",+ "MountInfo","Pty","PtySession","Shell",diff --git a/sdks/python/opencomputer/mounts.py b/sdks/python/opencomputer/mounts.pynew file mode 100644index 00000000..9e11bed3--- /dev/null+++ b/sdks/python/opencomputer/mounts.py@@ -0,0 +1,120 @@+"""FUSE-backed remote filesystem mounts inside a sandbox.++Mounts use ``rclone mount`` under the hood — one driver covering ~40 backends+(S3, GCS, Azure Blob, SFTP, WebDAV, Dropbox, etc.). Credentials are passed+inline, written to a tmpfs file inside the VM (mode 0600), and never persisted+on the worker. v1 does NOT auto-restore mounts on hibernate/wake — callers+re-issue ``add(...)`` after a wake if they need the mount back.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Literal++import httpx++MountBackend = Literal["s3", "gcs", "azureblob", "sftp", "webdav", "dropbox"]+++@dataclass+class MountInfo:+ """An active mount as tracked by the worker."""++ path: str+ remote: str+ read_only: bool+ backend: str = ""+++@dataclass+class Mounts:+ """Mount remote filesystems via rclone+FUSE inside the sandbox."""++ _client: httpx.AsyncClient+ _sandbox_id: str++ async def add(+ self,+ path: str,+ remote: str,+ backend: MountBackend | None = None,+ creds: dict[str, str] | None = None,+ rclone_config: str | None = None,+ read_only: bool = True,+ mount_options: list[str] | None = None,+ ) -> MountInfo:+ """Mount a remote filesystem at ``path`` inside the sandbox.++ Args:+ path: Absolute path inside the VM where the remote will be mounted.+ remote: rclone remote spec — ``"<name>:<path>"`` (e.g. ``"s3:my-bucket/prefix"``).+ backend: One of ``s3``, ``gcs``, ``azureblob``, ``sftp``, ``webdav``,+ ``dropbox``. Determines how ``creds`` are templated into the+ rclone config. Omit when passing ``rclone_config`` directly.+ creds: Backend-specific config keys (rclone field names — e.g. for+ S3: ``access_key_id``, ``secret_access_key``, ``region``).+ rclone_config: Raw rclone config string. Overrides ``backend`` and+ ``creds`` — useful for backends not in the typed list or for+ advanced tuning.+ read_only: Default ``True``. Object-store FUSE mounts have+ well-known write footguns; opt in to RW explicitly.+ mount_options: Extra args appended to ``rclone mount`` (e.g.+ ``["--dir-cache-time", "1m"]``).+ """+ body: dict[str, object] = {+ "path": path,+ "remote": remote,+ "readOnly": read_only,+ }+ if backend is not None:+ body["backend"] = backend+ if creds is not None:+ body["creds"] = creds+ if rclone_config is not None:+ body["rcloneConfig"] = rclone_config+ if mount_options is not None:+ body["mountOptions"] = mount_options++ resp = await self._client.post(+ f"/sandboxes/{self._sandbox_id}/mounts", json=body+ )+ resp.raise_for_status()+ data = resp.json()+ return MountInfo(+ path=data["path"],+ remote=data["remote"],+ backend=data.get("backend", ""),+ read_only=data.get("readOnly", True),+ )++ async def list(self) -> list[MountInfo]:+ """List the mounts this worker is tracking for the sandbox.++ Returns empty after hibernate/wake — re-issue ``add()`` for any mounts+ you need back.+ """+ resp = await self._client.get(f"/sandboxes/{self._sandbox_id}/mounts")+ resp.raise_for_status()+ data = resp.json() or []+ return [+ MountInfo(+ path=entry["path"],+ remote=entry["remote"],+ backend=entry.get("backend", ""),+ read_only=entry.get("readOnly", True),+ )+ for entry in data+ ]++ async def remove(self, path: str) -> None:+ """Unmount a path previously passed to ``add()``. No-op if not mounted."""+ try:+ resp = await self._client.delete(+ f"/sandboxes/{self._sandbox_id}/mounts", params={"path": path}+ )+ if resp.status_code == 404:+ return+ resp.raise_for_status()+ except httpx.HTTPError:+ raisediff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.pyindex 5fe14e11..61b4f18e 100644--- a/sdks/python/opencomputer/sandbox.py+++ b/sdks/python/opencomputer/sandbox.py@@ -12,6 +12,7 @@ from opencomputer.agent import Agentfrom opencomputer.exec import Execfrom opencomputer.filesystem import Filesystemfrom opencomputer.image import Image+from opencomputer.mounts import Mountsfrom opencomputer.pty import Ptyfrom opencomputer.sse import parse_sse_stream@@ -514,6 +515,11 @@ class Sandbox:"""Access filesystem operations."""return Filesystem(self._ops_client, self.sandbox_id)+ @property+ def mounts(self) -> Mounts:+ """Mount remote filesystems (S3, GCS, SFTP, …) via rclone+FUSE."""+ return Mounts(self._ops_client, self.sandbox_id)+@propertydef exec(self) -> Exec:"""Access session-based command execution."""diff --git a/sdks/typescript/src/index.ts b/sdks/typescript/src/index.tsindex 1bd215b0..f19ba1fa 100644--- a/sdks/typescript/src/index.ts+++ b/sdks/typescript/src/index.ts@@ -15,6 +15,7 @@ export {export { Agent, type AgentEvent, type AgentConfig, type AgentStartOpts, type AgentSession, type McpServerConfig } from "./agent.js";export { Filesystem, type EntryInfo } from "./filesystem.js";export { Exec, type ProcessResult, type RunOpts, type ExecSession, type ExecSessionInfo, type ExecStartOpts, type ExecAttachOpts } from "./exec.js";+export { Mounts, type AddMountOpts, type MountInfo, type MountBackend } from "./mounts.js";export { type Shell, type ShellOpts, type ShellRunOpts, ShellBusyError, ShellClosedError } from "./shell.js";export { Pty, type PtySession, type PtyOpts } from "./pty.js";export { Templates, type TemplateInfo } from "./template.js";diff --git a/sdks/typescript/src/mounts.ts b/sdks/typescript/src/mounts.tsnew file mode 100644index 00000000..c4ad4db7--- /dev/null+++ b/sdks/typescript/src/mounts.ts@@ -0,0 +1,120 @@+/**+ * Backends supported by the typed `creds` shape. For any backend not in this+ * list (or for advanced rclone tuning), pass `rcloneConfig` instead — the raw+ * string is dropped into the in-VM config file unchanged.+ */+export type MountBackend =+ | "s3"+ | "gcs"+ | "azureblob"+ | "sftp"+ | "webdav"+ | "dropbox";++export interface AddMountOpts {+ /** Absolute path inside the sandbox where the remote will be mounted. */+ path: string;+ /** rclone remote spec — `<name>:<path>` (e.g. `"s3:my-bucket/prefix"`). */+ remote: string;+ /**+ * Backend type. Determines how `creds` are templated into the rclone+ * config. Omit and pass `rcloneConfig` directly for backends not listed.+ */+ backend?: MountBackend;+ /**+ * Backend-specific credential / config keys (rclone config field names —+ * e.g. for S3: `access_key_id`, `secret_access_key`, `region`).+ *+ * Creds are written to a tmpfs file inside the VM (mode 0600) and never+ * persisted on the worker. v1 does not auto-restore mounts on hibernate —+ * re-call `mounts.add` after wake if you need the mount back.+ */+ creds?: Record<string, string>;+ /**+ * Raw rclone config to use verbatim. Overrides `backend`+`creds`. Useful+ * for backends not in the typed list, or for advanced tuning.+ */+ rcloneConfig?: string;+ /** Default `true`. Object-store FUSE mounts have well-known write footguns. */+ readOnly?: boolean;+ /** Extra args appended to `rclone mount` (e.g. `["--dir-cache-time", "1m"]`). */+ mountOptions?: string[];+}++export interface MountInfo {+ path: string;+ remote: string;+ backend?: string;+ readOnly: boolean;+}++export class Mounts {+ constructor(+ private apiUrl: string,+ private apiKey: string,+ private sandboxId: string,+ private token: string = "",+ ) {}++ private get headers(): Record<string, string> {+ if (this.token) return { "Authorization": `Bearer ${this.token}` };+ return this.apiKey ? { "X-API-Key": this.apiKey } : {};+ }++ /**+ * Mount a remote filesystem via rclone+FUSE inside the sandbox.+ *+ * @example+ * ```ts+ * await sandbox.mounts.add({+ * path: "/mnt/data",+ * remote: "s3:my-bucket",+ * backend: "s3",+ * creds: { access_key_id: "...", secret_access_key: "...", region: "us-east-1" },+ * });+ * ```+ */+ async add(opts: AddMountOpts): Promise<MountInfo> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json", ...this.headers },+ body: JSON.stringify(opts),+ },+ );+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to add mount: ${resp.status} ${text}`);+ }+ return resp.json();+ }++ /**+ * List the mounts this worker is tracking for the sandbox. Returns empty+ * after hibernate/wake — re-issue `add()` for any mounts you need back.+ */+ async list(): Promise<MountInfo[]> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts`,+ { headers: this.headers },+ );+ if (!resp.ok) {+ const text = await resp.text();+ throw new Error(`Failed to list mounts: ${resp.status} ${text}`);+ }+ return resp.json();+ }++ /** Unmount a path previously passed to `add()`. No-op if not mounted. */+ async remove(path: string): Promise<void> {+ const resp = await fetch(+ `${this.apiUrl}/sandboxes/${this.sandboxId}/mounts?path=${encodeURIComponent(path)}`,+ { method: "DELETE", headers: this.headers },+ );+ if (!resp.ok && resp.status !== 404) {+ const text = await resp.text();+ throw new Error(`Failed to remove mount: ${resp.status} ${text}`);+ }+ }+}diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.tsindex b1f9cb1a..4098d261 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -1,6 +1,7 @@import { Agent } from "./agent.js";import { Filesystem } from "./filesystem.js";import { Exec } from "./exec.js";+import { Mounts } from "./mounts.js";import { Pty } from "./pty.js";import { Image } from "./image.js";import { parseSSEStream } from "./sse.js";@@ -190,6 +191,7 @@ export class Sandbox {readonly agent: Agent;readonly files: Filesystem;readonly exec: Exec;+ readonly mounts: Mounts;readonly pty: Pty;/** @deprecated Use `sandbox.exec` instead. This alias exists for backwards compatibility. */readonly commands: Exec;@@ -215,6 +217,7 @@ export class Sandbox {this.files = new Filesystem(apiUrl, apiKey, this.sandboxId, "");this.exec = new Exec(apiUrl, apiKey, this.sandboxId, "");this.commands = this.exec; // backwards-compatible alias+ this.mounts = new Mounts(apiUrl, apiKey, this.sandboxId, "");this.pty = new Pty(apiUrl, apiKey, this.sandboxId, "");}@@ -368,6 +371,7 @@ export class Sandbox {(this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");+ (this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");}@@ -635,6 +639,7 @@ export class Sandbox {(this as any).agent = new Agent(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).files = new Filesystem(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).exec = new Exec(this.apiUrl, this.apiKey, this.sandboxId, "");+ (this as any).mounts = new Mounts(this.apiUrl, this.apiKey, this.sandboxId, "");(this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");}