Skip to content

An open-source, faster Devin alternative

TypeScript

optionally persistent across hibernate

Brian Reardone6114bd26726
diff --git a/cmd/oc/internal/commands/mounts.go b/cmd/oc/internal/commands/mounts.go
index ddd121ed..355bc86a 100644
--- a/cmd/oc/internal/commands/mounts.go
+++ b/cmd/oc/internal/commands/mounts.go
@@ -13,10 +13,13 @@ import (
// 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"`
+ Path string `json:"path"`
+ Remote string `json:"remote"`
+ Backend string `json:"backend,omitempty"`
+ ReadOnly bool `json:"readOnly"`
+ Persistent bool `json:"persistent,omitempty"`
+ Status string `json:"status,omitempty"`
+ Error string `json:"error,omitempty"`
}
var mountsCmd = &cobra.Command{
@@ -42,6 +45,7 @@ var mountsAddCmd = &cobra.Command{
credsFlag, _ := cmd.Flags().GetStringArray("cred")
configFile, _ := cmd.Flags().GetString("config-file")
readWrite, _ := cmd.Flags().GetBool("read-write")
+ persistent, _ := cmd.Flags().GetBool("persistent")
extraOpts, _ := cmd.Flags().GetStringArray("opt")
creds := map[string]string{}
@@ -54,9 +58,10 @@ var mountsAddCmd = &cobra.Command{
}
body := map[string]any{
- "path": path,
- "remote": remote,
- "readOnly": !readWrite,
+ "path": path,
+ "remote": remote,
+ "readOnly": !readWrite,
+ "persistent": persistent,
}
if backend != "" {
body["backend"] = backend
@@ -85,7 +90,11 @@ var mountsAddCmd = &cobra.Command{
if info.ReadOnly {
ro = "ro"
}
- fmt.Printf("Mounted %s → %s (%s)\n", info.Remote, info.Path, ro)
+ persist := ""
+ if info.Persistent {
+ persist = ", persistent"
+ }
+ fmt.Printf("Mounted %s → %s (%s%s)\n", info.Remote, info.Path, ro, persist)
})
return nil
},
@@ -108,14 +117,25 @@ var mountsListCmd = &cobra.Command{
fmt.Println("No mounts.")
return
}
- headers := []string{"PATH", "REMOTE", "BACKEND", "MODE"}
+ headers := []string{"PATH", "REMOTE", "BACKEND", "MODE", "PERSIST", "STATUS"}
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})
+ persist := "no"
+ if m.Persistent {
+ persist = "yes"
+ }
+ status := m.Status
+ if status == "" {
+ status = "active"
+ }
+ if m.Error != "" {
+ status = status + ": " + m.Error
+ }
+ rows = append(rows, []string{m.Path, m.Remote, m.Backend, mode, persist, status})
}
printer.Table(headers, rows)
})
@@ -147,6 +167,7 @@ func init() {
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().Bool("persistent", false, "Persist the (encrypted) config server-side so the mount auto-restores on wake")
mountsAddCmd.Flags().StringArray("opt", nil, "Extra args appended to `rclone mount` (repeatable)")
_ = mountsAddCmd.MarkFlagRequired("path")
_ = mountsAddCmd.MarkFlagRequired("remote")
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index aed3e79b..5cbd6340 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -22,6 +22,7 @@ import (
"github.com/opensandbox/opensandbox/internal/blobstore"
"github.com/opensandbox/opensandbox/internal/cellevents"
"github.com/opensandbox/opensandbox/internal/config"
+ "github.com/opensandbox/opensandbox/internal/crypto"
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/metrics"
"github.com/opensandbox/opensandbox/internal/observability"
@@ -428,6 +429,16 @@ func main() {
defer store.Close()
log.Println("opensandbox-worker: PostgreSQL store connected (auto-wake enabled)")
+ // Wire the at-rest encryption key — same key the server uses, picked
+ // up from OPENSANDBOX_SECRET_ENCRYPTION_KEY[/_V*]. Required for
+ // persistent FUSE mounts (encrypts the rclone config blob).
+ if ring, kerr := crypto.NewKeyRingFromEnv(); kerr != nil {
+ log.Fatalf("opensandbox-worker: invalid encryption key config: %v", kerr)
+ } else if ring != nil {
+ store.SetEncryptor(ring.AsEncryptor())
+ log.Printf("opensandbox-worker: secret encryption configured (key version %d)", ring.PrimaryVersion())
+ }
+
hibernated, stopped, err := store.ReconcileWorkerSessions(ctx, cfg.WorkerID)
if err != nil {
log.Printf("opensandbox-worker: warning: session reconciliation failed: %v", err)
@@ -603,7 +614,7 @@ func main() {
}
// HTTP server
- httpServer := worker.NewHTTPServer(mgr, ptyMgr, execMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain)
+ httpServer := worker.NewHTTPServer(mgr, ptyMgr, execMgr, jwtIssuer, sandboxDBMgr, sbProxy, sbRouter, cfg.SandboxDomain, store)
httpAddr := fmt.Sprintf(":%d", cfg.Port)
log.Printf("opensandbox-worker: starting HTTP server on %s", httpAddr)
go func() {
diff --git a/docs/sandboxes/mounts.mdx b/docs/sandboxes/mounts.mdx
index 0106b9d4..55c36a2e 100644
--- a/docs/sandboxes/mounts.mdx
+++ b/docs/sandboxes/mounts.mdx
@@ -214,26 +214,81 @@ await sandbox.mounts.remove("/mnt/data");
## Hibernate behavior
-<Warning>
- **Mounts do not survive hibernate.** When a sandbox hibernates (manually or
- via idle timeout), all FUSE mounts are torn down before the snapshot is
- taken — otherwise the snapshot would capture broken file descriptors that
- hang processes on wake.
+By default, mounts do **not** survive hibernate. The mount is torn down in the
+VM before the snapshot is taken (otherwise the snapshot would capture broken
+file descriptors that hang processes on wake), and the server doesn't store
+your credentials anywhere — they live only in the VM's tmpfs for the lifetime
+of the mount.
- v1 does not auto-restore mounts on wake. After waking, call `mounts.add()`
- again for anything you need back. `mounts.list()` returns empty post-wake.
-</Warning>
+If you want the mount to come back automatically, opt in with `persistent: true`:
+
+<CodeGroup>
+
+```typescript TypeScript
+await sandbox.mounts.add({
+ path: "/mnt/data",
+ remote: "s3:my-bucket",
+ backend: "s3",
+ creds: {...},
+ persistent: true, // ← opt in
+});
+```
+
+```python Python
+await sandbox.mounts.add(
+ path="/mnt/data",
+ remote="s3:my-bucket",
+ backend="s3",
+ creds={...},
+ persistent=True,
+)
+```
+
+```bash CLI
+oc mounts add sb-abc123 \
+ --path /mnt/data --remote s3:my-bucket --backend s3 \
+ --cred access_key_id=... --cred secret_access_key=... \
+ --persistent
+```
-The simplest pattern is to remount on wake:
+</CodeGroup>
+
+With `persistent: true`:
+
+- The rendered rclone config (which includes your creds) is encrypted with the
+ server's `OPENSANDBOX_SECRET_ENCRYPTION_KEY` and stored in PostgreSQL.
+- On wake — explicit (`sandbox.wake()`) or auto-wake (when any operation hits a
+ hibernated sandbox) — the server replays each persistent mount in the
+ background.
+- Wake completes immediately; mount replay doesn't block it. Inspect
+ `mounts.list()` to see the current state of each mount.
+
+### Wake-time failures
+
+If a persistent mount fails to replay (rotated creds, expired token, network
+issue, deleted bucket, etc.), **the wake still succeeds** — we don't punish
+your whole sandbox for one bad mount. The mount shows up in `list()` with the
+failure surfaced:
```typescript
-const sandbox = await Sandbox.connect("sb-abc123");
-if (sandbox.status === "hibernated") {
- await sandbox.wake();
- await sandbox.mounts.add({ path: "/mnt/data", remote: "s3:my-bucket", backend: "s3", creds });
-}
+const mounts = await sandbox.mounts.list();
+// [
+// { path: "/mnt/data", remote: "s3:my-bucket", status: "active", persistent: true },
+// { path: "/mnt/stale", remote: "s3:old-bucket", status: "failed", persistent: true,
+// error: "rclone mount failed (exit 1): AccessDenied: ..." },
+// ]
```
+To recover, either `remove()` the broken mount or `add()` it again with fresh
+creds (re-adding overwrites the prior spec).
+
+<Note>
+ `persistent: true` requires the server to have `OPENSANDBOX_SECRET_ENCRYPTION_KEY`
+ configured (the same key already used for project secrets). On self-hosted
+ setups without this key, `persistent: true` returns a clear 503 — fall back to
+ non-persistent mounts and remount after wake.
+</Note>
+
## CLI
```bash
diff --git a/internal/api/router.go b/internal/api/router.go
index dc3bad09..8173ee24 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -24,6 +24,7 @@ import (
"github.com/opensandbox/opensandbox/internal/db"
"github.com/opensandbox/opensandbox/internal/edgeclient"
"github.com/opensandbox/opensandbox/internal/metrics"
+ "github.com/opensandbox/opensandbox/internal/mounts"
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
@@ -59,7 +60,7 @@ type Server struct {
sandboxDomain string // base domain for sandbox subdomains
cfClient *cloudflare.Client // nil if Cloudflare not configured
pendingCreates sync.Map // map[sandboxID]*pendingCreate — async sandbox creation tracking
- mounts *mountRegistry // process-local FUSE mount tracker; cleared on hibernate
+ mountSvc *mounts.Service // shared with worker.HTTPServer; nil disables the mounts API
sandboxAPIProxy *proxy.SandboxAPIProxy // nil except in server mode (proxies data-plane to workers)
stripeClient *billing.StripeClient // nil if Stripe not configured
redisClient *redis.Client // nil if Redis not configured (for health checks)
@@ -135,7 +136,14 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
echo: e,
manager: mgr,
ptyManager: ptyMgr,
- mounts: newMountRegistry(),
+ }
+ // Mount service is only useful in combined mode (this process owns the
+ // sandbox manager). In server mode the CP proxies to a worker, which
+ // instantiates its own mounts.Service backed by its own manager.
+ if mgr != nil {
+ // Store is nil until opts is processed below; the persistent-mount
+ // path will return ErrPersistenceUnavailable if it's missing then.
+ s.mountSvc = mounts.NewService(mgr, nil)
}
if opts != nil {
@@ -154,6 +162,21 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
s.execSessionManager = opts.ExecSessionManager
s.sandboxDBs = opts.SandboxDBs
s.router = opts.Router
+ // Now that we have the store, upgrade the mount service so persistent
+ // mounts work. The earlier NewService(mgr, nil) was a placeholder for
+ // the no-store case.
+ if mgr != nil && s.store != nil {
+ s.mountSvc = mounts.NewService(mgr, s.store)
+ }
+ // Wire the post-auto-wake hook so persistent FUSE mounts are replayed
+ // when the router auto-wakes a hibernated sandbox on an incoming request.
+ // Explicit-wake API callers (POST /sandboxes/:id/wake) hit a separate
+ // path; that handler triggers replay directly.
+ if s.router != nil && s.mountSvc != nil {
+ s.router.SetOnWake(func(sandboxID string) {
+ s.mountSvc.OnWake(context.Background(), sandboxID)
+ })
+ }
s.workerRegistry = opts.WorkerRegistry
s.checkpointStore = opts.CheckpointStore
s.sandboxDomain = opts.SandboxDomain
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 4b1961ef..7cfea66c 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -1667,11 +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)
+ // FUSE mounts are torn down in the VM by snapshot.go (`fusermount3 -u -a`
+ // before savevm). Drop non-persistent rows from the registry; persistent
+ // rows are kept with status="replaying" so list() reflects the intent
+ // across the hibernate→wake gap, and mounts.Service.OnWake will rebuild
+ // them when the sandbox is woken.
+ if s.mountSvc != nil {
+ s.mountSvc.OnHibernate(id)
}
// Mark hibernated in sandbox router
@@ -1844,6 +1846,15 @@ func (s *Server) wakeSandbox(c echo.Context) error {
// Apply pending checkpoint patches in background
go s.applyPendingPatches(id, s.workerID)
+ // Replay any persistent FUSE mounts. Explicit wake doesn't flow through
+ // router.doWake (which is the auto-wake hook point), so we trigger replay
+ // directly here. Background context so the wake response isn't held up
+ // by remote-storage round-trips; failures show up in mounts.list() with
+ // status="failed" and the error.
+ if s.mountSvc != nil {
+ go s.mountSvc.OnWake(context.Background(), id)
+ }
+
// Issue fresh JWT
orgID, _ := auth.GetOrgID(c)
if s.jwtIssuer != nil {
diff --git a/internal/api/sandbox_mounts.go b/internal/api/sandbox_mounts.go
index 8148b09b..7f2f2b2a 100644
--- a/internal/api/sandbox_mounts.go
+++ b/internal/api/sandbox_mounts.go
@@ -2,239 +2,52 @@ package api
import (
"context"
- "crypto/sha1"
- "encoding/hex"
- "fmt"
+ "errors"
"net/http"
- "sort"
- "strings"
- "sync"
"github.com/labstack/echo/v4"
- "github.com/opensandbox/opensandbox/pkg/types"
+ "github.com/opensandbox/opensandbox/internal/mounts"
)
-// 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`
-}
+// MountRecord and the request body type live in internal/mounts. Re-exposed
+// here only so existing exported field names (used by SDKs) don't change.
func (s *Server) addMount(c echo.Context) error {
- if s.manager == nil {
+ if s.mountSvc == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
id := c.Param("id")
- var req addMountRequest
+ var req mounts.AddRequest
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
+ var rec mounts.MountRecord
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
+ var err error
+ rec, err = s.mountSvc.Add(ctx, id, req)
+ return err
}
-
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,
+ status := http.StatusInternalServerError
+ if errors.Is(err, mounts.ErrPersistenceUnavailable) {
+ status = http.StatusServiceUnavailable
+ }
+ return c.JSON(status, map[string]string{"error": err.Error()})
}
- s.mounts.put(id, rec)
return c.JSON(http.StatusCreated, rec)
}
func (s *Server) listMounts(c echo.Context) error {
- if s.manager == nil {
+ if s.mountSvc == 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)
+ return c.JSON(http.StatusOK, s.mountSvc.List(c.Param("id")))
}
func (s *Server) removeMount(c echo.Context) error {
- if s.manager == nil {
+ if s.mountSvc == nil {
return c.JSON(http.StatusServiceUnavailable, errSandboxNotAvailable)
}
id := c.Param("id")
@@ -242,20 +55,10 @@ func (s *Server) removeMount(c echo.Context) error {
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
- }
+ routeOp := func(ctx context.Context) error { return s.mountSvc.Remove(ctx, id, path) }
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)
}
@@ -265,67 +68,3 @@ func (s *Server) routeOrCall(c echo.Context, sandboxID, opName string, op func(c
}
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/db/migrations/045_sandbox_mounts.down.sql b/internal/db/migrations/045_sandbox_mounts.down.sql
new file mode 100644
index 00000000..f044050f
--- /dev/null
+++ b/internal/db/migrations/045_sandbox_mounts.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS sandbox_mounts;
diff --git a/internal/db/migrations/045_sandbox_mounts.up.sql b/internal/db/migrations/045_sandbox_mounts.up.sql
new file mode 100644
index 00000000..b21175ac
--- /dev/null
+++ b/internal/db/migrations/045_sandbox_mounts.up.sql
@@ -0,0 +1,30 @@
+-- Persistent FUSE mounts attached to a sandbox.
+--
+-- Each row is one rclone mount that has been declared `persistent: true`. The
+-- worker stores the rendered rclone config (which embeds backend credentials)
+-- here, encrypted with the same SECRET_ENCRYPTION_KEY used for the rest of
+-- our at-rest secrets. On wake — both explicit and auto-wake — the worker
+-- reads this table, decrypts the configs, and replays each mount via the
+-- existing mount orchestration.
+--
+-- Non-persistent mounts (the v1 default) live only in the worker's in-memory
+-- registry and do NOT touch this table — they vanish on hibernate by design.
+--
+-- last_error is set when the wake-time replay fails (bad creds, network, etc).
+-- The mount row stays in the table so `mounts.list()` can surface the failure
+-- to the user; they remove or re-add via the normal SDK calls.
+CREATE TABLE sandbox_mounts (
+ sandbox_id TEXT NOT NULL,
+ path TEXT NOT NULL, -- absolute path inside the VM
+ remote TEXT NOT NULL, -- rclone remote spec, e.g. "s3:my-bucket/prefix"
+ backend TEXT NOT NULL DEFAULT '', -- "s3" | "gcs" | ... | "" when rcloneConfig supplied raw
+ read_only BOOLEAN NOT NULL DEFAULT TRUE,
+ mount_options JSONB NOT NULL DEFAULT '[]'::jsonb, -- extra args appended to `rclone mount`
+ encrypted_config BYTEA NOT NULL, -- nonce || ciphertext of the rclone config string
+ last_error TEXT NOT NULL DEFAULT '', -- set on wake-time replay failure; '' = healthy
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (sandbox_id, path)
+);
+
+CREATE INDEX sandbox_mounts_sandbox ON sandbox_mounts (sandbox_id);
diff --git a/internal/db/sandbox_mounts.go b/internal/db/sandbox_mounts.go
new file mode 100644
index 00000000..3e85dbc5
--- /dev/null
+++ b/internal/db/sandbox_mounts.go
@@ -0,0 +1,124 @@
+package db
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "github.com/jackc/pgx/v5"
+)
+
+// PersistentMount is one row of sandbox_mounts. The rclone config is stored
+// encrypted on disk; callers receive the still-encrypted bytes and decrypt
+// via Store.Encryptor() when they actually need to render the config (typically
+// during wake-time replay).
+type PersistentMount struct {
+ SandboxID string
+ Path string
+ Remote string
+ Backend string
+ ReadOnly bool
+ MountOptions []string
+ EncryptedConfig []byte
+ LastError string
+}
+
+// UpsertSandboxMount creates or replaces a persistent mount row. Re-issuing
+// `mounts.add()` against the same path overwrites the prior spec; this matches
+// the in-memory registry's put-with-same-path semantics.
+func (s *Store) UpsertSandboxMount(ctx context.Context, m PersistentMount) error {
+ opts, err := json.Marshal(m.MountOptions)
+ if err != nil {
+ return fmt.Errorf("marshal mount options: %w", err)
+ }
+ if len(opts) == 0 || string(opts) == "null" {
+ opts = []byte("[]")
+ }
+ _, err = s.pool.Exec(ctx, `
+ INSERT INTO sandbox_mounts (sandbox_id, path, remote, backend, read_only, mount_options, encrypted_config, last_error)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, '')
+ ON CONFLICT (sandbox_id, path) DO UPDATE SET
+ remote = EXCLUDED.remote,
+ backend = EXCLUDED.backend,
+ read_only = EXCLUDED.read_only,
+ mount_options = EXCLUDED.mount_options,
+ encrypted_config = EXCLUDED.encrypted_config,
+ last_error = '',
+ updated_at = now()
+ `, m.SandboxID, m.Path, m.Remote, m.Backend, m.ReadOnly, opts, m.EncryptedConfig)
+ if err != nil {
+ return fmt.Errorf("upsert mount %s/%s: %w", m.SandboxID, m.Path, err)
+ }
+ return nil
+}
+
+// DeleteSandboxMount removes a single mount row by (sandbox_id, path). Returns
+// nil even when no row matches — `mounts.remove()` is idempotent.
+func (s *Store) DeleteSandboxMount(ctx context.Context, sandboxID, path string) error {
+ _, err := s.pool.Exec(ctx, `
+ DELETE FROM sandbox_mounts WHERE sandbox_id = $1 AND path = $2
+ `, sandboxID, path)
+ if err != nil {
+ return fmt.Errorf("delete mount %s/%s: %w", sandboxID, path, err)
+ }
+ return nil
+}
+
+// DeleteSandboxMounts wipes every mount row for a sandbox (used on sandbox kill).
+func (s *Store) DeleteSandboxMounts(ctx context.Context, sandboxID string) error {
+ _, err := s.pool.Exec(ctx, `DELETE FROM sandbox_mounts WHERE sandbox_id = $1`, sandboxID)
+ if err != nil {
+ return fmt.Errorf("delete mounts for %s: %w", sandboxID, err)
+ }
+ return nil
+}
+
+// ListSandboxMounts returns all persistent mounts attached to a sandbox.
+// Returns an empty slice (not nil) when the sandbox has no rows so callers can
+// safely range without a nil check.
+func (s *Store) ListSandboxMounts(ctx context.Context, sandboxID string) ([]PersistentMount, error) {
+ rows, err := s.pool.Query(ctx, `
+ SELECT sandbox_id, path, remote, backend, read_only, mount_options, encrypted_config, last_error
+ FROM sandbox_mounts
+ WHERE sandbox_id = $1
+ ORDER BY path
+ `, sandboxID)
+ if err != nil {
+ return nil, fmt.Errorf("list mounts for %s: %w", sandboxID, err)
+ }
+ defer rows.Close()
+
+ out := []PersistentMount{}
+ for rows.Next() {
+ var m PersistentMount
+ var optsJSON []byte
+ if err := rows.Scan(&m.SandboxID, &m.Path, &m.Remote, &m.Backend, &m.ReadOnly, &optsJSON, &m.EncryptedConfig, &m.LastError); err != nil {
+ return nil, fmt.Errorf("scan mount row: %w", err)
+ }
+ if len(optsJSON) > 0 && string(optsJSON) != "null" {
+ if err := json.Unmarshal(optsJSON, &m.MountOptions); err != nil {
+ return nil, fmt.Errorf("unmarshal mount options for %s/%s: %w", m.SandboxID, m.Path, err)
+ }
+ }
+ out = append(out, m)
+ }
+ if err := rows.Err(); err != nil && err != pgx.ErrNoRows {
+ return nil, fmt.Errorf("iterate mount rows: %w", err)
+ }
+ return out, nil
+}
+
+// SetSandboxMountError records (or clears) the wake-time replay error for a
+// mount. Passing an empty string clears the error, used after a successful
+// replay or on a fresh upsert.
+func (s *Store) SetSandboxMountError(ctx context.Context, sandboxID, path, errMsg string) error {
+ _, err := s.pool.Exec(ctx, `
+ UPDATE sandbox_mounts
+ SET last_error = $3, updated_at = now()
+ WHERE sandbox_id = $1 AND path = $2
+ `, sandboxID, path, errMsg)
+ if err != nil {
+ return fmt.Errorf("set mount error for %s/%s: %w", sandboxID, path, err)
+ }
+ return nil
+}
diff --git a/internal/db/sandbox_mounts_pgfixture_test.go b/internal/db/sandbox_mounts_pgfixture_test.go
new file mode 100644
index 00000000..23552d42
--- /dev/null
+++ b/internal/db/sandbox_mounts_pgfixture_test.go
@@ -0,0 +1,196 @@
+//go:build pgfixture
+
+// Integration tests for the persistent-mount Store methods. Run only under
+// `go test -tags=pgfixture` against a real Postgres pointed at by
+// TEST_DATABASE_URL. The schema (UPSERT semantics, JSONB round-tripping,
+// composite primary key) is what makes these worth running against actual PG
+// rather than mocked.
+//
+// Run locally:
+//
+// TEST_DATABASE_URL=postgres://user:pass@localhost:5432/dbname?sslmode=disable \
+// go test -tags=pgfixture ./internal/db/ -run Mount -v
+package db
+
+import (
+ "bytes"
+ "context"
+ "reflect"
+ "sort"
+ "testing"
+)
+
+func TestSandboxMounts_UpsertListDelete_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ sb := "sb-mounts-test-1"
+ t.Cleanup(func() { _ = store.DeleteSandboxMounts(ctx, sb) })
+
+ m1 := PersistentMount{
+ SandboxID: sb,
+ Path: "/mnt/data",
+ Remote: "s3:my-bucket",
+ Backend: "s3",
+ ReadOnly: true,
+ MountOptions: []string{"--vfs-cache-mode", "writes"},
+ EncryptedConfig: []byte{0x01, 0x02, 0x03},
+ }
+ m2 := PersistentMount{
+ SandboxID: sb,
+ Path: "/mnt/other",
+ Remote: "gcs:bucket-2",
+ Backend: "gcs",
+ ReadOnly: false,
+ MountOptions: nil,
+ EncryptedConfig: []byte{0xff, 0xfe},
+ }
+
+ if err := store.UpsertSandboxMount(ctx, m1); err != nil {
+ t.Fatalf("upsert m1: %v", err)
+ }
+ if err := store.UpsertSandboxMount(ctx, m2); err != nil {
+ t.Fatalf("upsert m2: %v", err)
+ }
+
+ got, err := store.ListSandboxMounts(ctx, sb)
+ if err != nil {
+ t.Fatalf("list: %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("expected 2 rows, got %d: %+v", len(got), got)
+ }
+ // Order by path so the assertion is stable.
+ sort.Slice(got, func(i, j int) bool { return got[i].Path < got[j].Path })
+
+ // JSONB round-trip: nil MountOptions on insert should come back as nil OR
+ // empty slice — accept either, but both should be empty.
+ if len(got[1].MountOptions) != 0 {
+ t.Errorf("m2 expected empty MountOptions after round-trip, got %v", got[1].MountOptions)
+ }
+ if !reflect.DeepEqual(got[0].MountOptions, m1.MountOptions) {
+ t.Errorf("m1 MountOptions round-trip: got %v want %v", got[0].MountOptions, m1.MountOptions)
+ }
+ if !bytes.Equal(got[0].EncryptedConfig, m1.EncryptedConfig) {
+ t.Errorf("m1 encrypted blob round-trip differs")
+ }
+ if got[0].LastError != "" {
+ t.Errorf("m1 LastError should be empty after upsert, got %q", got[0].LastError)
+ }
+
+ // UPSERT: re-insert m1 with different remote should overwrite, not duplicate.
+ m1b := m1
+ m1b.Remote = "s3:my-bucket-renamed"
+ m1b.EncryptedConfig = []byte{0xaa, 0xbb}
+ // Pre-poison last_error to confirm UPSERT clears it.
+ if err := store.SetSandboxMountError(ctx, sb, m1.Path, "stale error"); err != nil {
+ t.Fatalf("set error: %v", err)
+ }
+ if err := store.UpsertSandboxMount(ctx, m1b); err != nil {
+ t.Fatalf("re-upsert m1: %v", err)
+ }
+ got, err = store.ListSandboxMounts(ctx, sb)
+ if err != nil {
+ t.Fatalf("list 2: %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("UPSERT should not duplicate; got %d rows", len(got))
+ }
+ sort.Slice(got, func(i, j int) bool { return got[i].Path < got[j].Path })
+ if got[0].Remote != "s3:my-bucket-renamed" {
+ t.Errorf("re-upsert didn't update Remote: got %q", got[0].Remote)
+ }
+ if !bytes.Equal(got[0].EncryptedConfig, m1b.EncryptedConfig) {
+ t.Errorf("re-upsert didn't update EncryptedConfig")
+ }
+ if got[0].LastError != "" {
+ t.Errorf("UPSERT must clear last_error (incident-resilience); got %q", got[0].LastError)
+ }
+
+ // Single delete.
+ if err := store.DeleteSandboxMount(ctx, sb, m1.Path); err != nil {
+ t.Fatalf("delete m1: %v", err)
+ }
+ got, err = store.ListSandboxMounts(ctx, sb)
+ if err != nil {
+ t.Fatalf("list 3: %v", err)
+ }
+ if len(got) != 1 || got[0].Path != m2.Path {
+ t.Errorf("after deleting m1, expected only m2; got %+v", got)
+ }
+
+ // Idempotent delete on missing row.
+ if err := store.DeleteSandboxMount(ctx, sb, "/nope"); err != nil {
+ t.Errorf("delete of missing row should be idempotent; got %v", err)
+ }
+
+ // Bulk delete.
+ if err := store.DeleteSandboxMounts(ctx, sb); err != nil {
+ t.Fatalf("bulk delete: %v", err)
+ }
+ got, err = store.ListSandboxMounts(ctx, sb)
+ if err != nil {
+ t.Fatalf("list 4: %v", err)
+ }
+ if len(got) != 0 {
+ t.Errorf("bulk delete left rows: %+v", got)
+ }
+}
+
+func TestSandboxMounts_SetSandboxMountError_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+
+ sb := "sb-mounts-test-2"
+ t.Cleanup(func() { _ = store.DeleteSandboxMounts(ctx, sb) })
+
+ m := PersistentMount{
+ SandboxID: sb,
+ Path: "/mnt/data",
+ Remote: "s3:bucket",
+ Backend: "s3",
+ ReadOnly: true,
+ EncryptedConfig: []byte{0x01},
+ }
+ if err := store.UpsertSandboxMount(ctx, m); err != nil {
+ t.Fatalf("upsert: %v", err)
+ }
+
+ if err := store.SetSandboxMountError(ctx, sb, m.Path, "AccessDenied"); err != nil {
+ t.Fatalf("set error: %v", err)
+ }
+ got, _ := store.ListSandboxMounts(ctx, sb)
+ if len(got) != 1 || got[0].LastError != "AccessDenied" {
+ t.Errorf("SetSandboxMountError didn't take effect: %+v", got)
+ }
+
+ // Clearing the error (empty string) is the post-successful-replay path.
+ if err := store.SetSandboxMountError(ctx, sb, m.Path, ""); err != nil {
+ t.Fatalf("clear error: %v", err)
+ }
+ got, _ = store.ListSandboxMounts(ctx, sb)
+ if len(got) != 1 || got[0].LastError != "" {
+ t.Errorf("clearing error didn't take effect: %+v", got)
+ }
+
+ // SetSandboxMountError on a missing (sandbox_id, path) is a no-op,
+ // not an error — keeps the wake-time replay path lock-free.
+ if err := store.SetSandboxMountError(ctx, sb, "/does-not-exist", "x"); err != nil {
+ t.Errorf("SetSandboxMountError on missing row should not error; got %v", err)
+ }
+}
+
+func TestSandboxMounts_ListEmptyReturnsEmptySlice_pgfixture(t *testing.T) {
+ ctx := context.Background()
+ store := openPgStore(t)
+ got, err := store.ListSandboxMounts(ctx, "sb-never-existed")
+ if err != nil {
+ t.Fatalf("list on unknown sandbox: %v", err)
+ }
+ if got == nil {
+ t.Errorf("ListSandboxMounts should return non-nil empty slice, got nil")
+ }
+ if len(got) != 0 {
+ t.Errorf("expected empty slice, got %+v", got)
+ }
+}
diff --git a/internal/db/store.go b/internal/db/store.go
index 8586c9c6..b7765256 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -142,6 +142,7 @@ func (s *Store) Migrate(ctx context.Context) error {
{42, "migrations/042_global_sync_outbox.up.sql"},
{43, "migrations/043_credit_halt.up.sql"},
{44, "migrations/044_drop_secret_store_fk.up.sql"},
+ {45, "migrations/045_sandbox_mounts.up.sql"},
}
for _, m := range migrations {
diff --git a/internal/api/sandbox_mounts_test.go b/internal/mounts/render_test.go
similarity index 65%
rename from internal/api/sandbox_mounts_test.go
rename to internal/mounts/render_test.go
index 2e5c30fe..5df9ac08 100644
--- a/internal/api/sandbox_mounts_test.go
+++ b/internal/mounts/render_test.go
@@ -1,4 +1,4 @@
-package api
+package mounts
import (
"strings"
@@ -7,7 +7,7 @@ import (
func TestRenderRcloneConfig_RawPassthrough(t *testing.T) {
raw := "[whatever]\ntype = s3\nfoo = bar\n"
- got, err := renderRcloneConfig(addMountRequest{
+ got, err := renderRcloneConfig(AddRequest{
Remote: "whatever:bucket",
RcloneConfig: raw,
})
@@ -20,7 +20,7 @@ func TestRenderRcloneConfig_RawPassthrough(t *testing.T) {
}
func TestRenderRcloneConfig_S3DefaultsAWSProvider(t *testing.T) {
- got, err := renderRcloneConfig(addMountRequest{
+ got, err := renderRcloneConfig(AddRequest{
Remote: "s3:my-bucket",
Backend: "s3",
Creds: map[string]string{
@@ -54,7 +54,7 @@ func TestRenderRcloneConfig_S3DefaultsAWSProvider(t *testing.T) {
}
func TestRenderRcloneConfig_S3UserProviderWins(t *testing.T) {
- got, err := renderRcloneConfig(addMountRequest{
+ got, err := renderRcloneConfig(AddRequest{
Remote: "minio:bucket",
Backend: "s3",
Creds: map[string]string{
@@ -76,7 +76,7 @@ func TestRenderRcloneConfig_S3UserProviderWins(t *testing.T) {
}
func TestRenderRcloneConfig_GCSHasTypeWithSpace(t *testing.T) {
- got, err := renderRcloneConfig(addMountRequest{
+ got, err := renderRcloneConfig(AddRequest{
Remote: "gcs:my-bucket",
Backend: "gcs",
Creds: map[string]string{"service_account_credentials": "{\"type\":\"service_account\"}"},
@@ -92,8 +92,8 @@ func TestRenderRcloneConfig_GCSHasTypeWithSpace(t *testing.T) {
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})
+ a, _ := renderRcloneConfig(AddRequest{Remote: "sftp:host", Backend: "sftp", Creds: creds})
+ b, _ := renderRcloneConfig(AddRequest{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)
}
@@ -107,14 +107,14 @@ func TestRenderRcloneConfig_DeterministicKeyOrder(t *testing.T) {
}
func TestRenderRcloneConfig_RejectsBareRemote(t *testing.T) {
- _, err := renderRcloneConfig(addMountRequest{Remote: "no-colon-here", Backend: "s3"})
+ _, err := renderRcloneConfig(AddRequest{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"})
+ _, err := renderRcloneConfig(AddRequest{Remote: "x:y", Backend: "minio-direct"})
if err == nil {
t.Fatal("expected error for unknown backend, got nil")
}
@@ -124,7 +124,7 @@ func TestRenderRcloneConfig_RejectsUnknownBackend(t *testing.T) {
}
func TestRenderRcloneConfig_RequiresBackendOrRawConfig(t *testing.T) {
- _, err := renderRcloneConfig(addMountRequest{Remote: "x:y"})
+ _, err := renderRcloneConfig(AddRequest{Remote: "x:y"})
if err == nil {
t.Fatal("expected error when no backend and no rcloneConfig, got nil")
}
@@ -150,8 +150,69 @@ func TestMountConfPath_DeterministicAndSafe(t *testing.T) {
}
}
+func TestRemoteFromConfig(t *testing.T) {
+ cases := []struct {
+ name string
+ conf string
+ want string
+ }{
+ {"single section", "[s3]\ntype = s3\n", "s3"},
+ {"leading whitespace", " [gcs] \ntype = google cloud storage\n", "gcs"},
+ {"comment first then section", "# header comment\n[box]\ntype = box\n", "box"},
+ {"empty config", "", ""},
+ {"no section header", "type = s3\naccess_key_id = x\n", ""},
+ {"first section wins", "[a]\ntype = s3\n[b]\ntype = sftp\n", "a"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := remoteFromConfig(tc.conf); got != tc.want {
+ t.Errorf("remoteFromConfig(%q) = %q, want %q", tc.conf, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestMountRegistry_ClearNonPersistent(t *testing.T) {
+ r := newRegistry()
+ // Mix of persistent + non-persistent for the same sandbox.
+ r.put("sb-1", MountRecord{Path: "/mnt/ephemeral", Remote: "s3:eph", Status: "active"})
+ r.put("sb-1", MountRecord{Path: "/mnt/durable", Remote: "s3:dur", Persistent: true, Status: "active"})
+ r.put("sb-1", MountRecord{Path: "/mnt/durable2", Remote: "s3:dur2", Persistent: true, Status: "active"})
+ r.put("sb-2", MountRecord{Path: "/mnt/x", Remote: "s3:x", Status: "active"})
+
+ r.clearNonPersistent("sb-1")
+
+ got := r.get("sb-1")
+ if len(got) != 2 {
+ t.Fatalf("expected 2 persistent entries to remain on sb-1, got %d: %v", len(got), got)
+ }
+ for _, rec := range got {
+ if !rec.Persistent {
+ t.Errorf("non-persistent record leaked through clearNonPersistent: %+v", rec)
+ }
+ if rec.Status != "replaying" {
+ t.Errorf("persistent record status after clearNonPersistent want %q got %q", "replaying", rec.Status)
+ }
+ }
+
+ // Other sandboxes untouched.
+ if got := r.get("sb-2"); len(got) != 1 {
+ t.Errorf("clearNonPersistent leaked into other sandbox: %v", got)
+ }
+}
+
+func TestMountRegistry_ClearNonPersistent_AllNonPersistent(t *testing.T) {
+ r := newRegistry()
+ r.put("sb-1", MountRecord{Path: "/mnt/a", Status: "active"})
+ r.put("sb-1", MountRecord{Path: "/mnt/b", Status: "active"})
+ r.clearNonPersistent("sb-1")
+ if got := r.get("sb-1"); got != nil {
+ t.Errorf("clearNonPersistent with no persistent entries should drop the sandbox; got %v", got)
+ }
+}
+
func TestMountRegistry_PutListRemove(t *testing.T) {
- r := newMountRegistry()
+ r := newRegistry()
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})
@@ -193,9 +254,10 @@ func TestMountRegistry_PutListRemove(t *testing.T) {
t.Errorf("after removing last entry, expected nil, got %v", got)
}
- // clear() drops a sandbox even with entries.
- r.clear("sb-2")
+ // clearNonPersistent() drops all non-persistent entries (in this test, all
+ // of sb-2's entries are non-persistent).
+ r.clearNonPersistent("sb-2")
if got := r.get("sb-2"); got != nil {
- t.Errorf("after clear, expected nil, got %v", got)
+ t.Errorf("after clearNonPersistent, expected nil, got %v", got)
}
}
diff --git a/internal/mounts/service.go b/internal/mounts/service.go
new file mode 100644
index 00000000..b5bb4f00
--- /dev/null
+++ b/internal/mounts/service.go
@@ -0,0 +1,507 @@
+// Package mounts implements rclone-backed FUSE mounts inside a sandbox.
+//
+// Two callers wire this into HTTP layers:
+//
+// - internal/api — combined-mode CP, where the same process hosts sandboxes
+// - internal/worker — the worker that owns the sandbox in server mode (the
+// CP proxies /api/sandboxes/:id/mounts here)
+//
+// Both call the same Service so behavior is identical regardless of which
+// route the request took to reach the worker that actually owns the sandbox.
+package mounts
+
+import (
+ "context"
+ "crypto/sha1"
+ "encoding/hex"
+ "fmt"
+ "log"
+ "sort"
+ "strings"
+ "sync"
+
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+// MountRecord describes one rclone-backed FUSE mount inside a sandbox. For
+// non-persistent mounts, the in-memory Registry is the only place it lives;
+// for persistent mounts, a parallel row exists in the sandbox_mounts PG table.
+//
+// Status is one of:
+// - "active" — mounted and serving I/O
+// - "replaying" — wake-time remount in progress (persistent only)
+// - "failed" — wake-time remount failed; Error is set (persistent only)
+type MountRecord struct {
+ Path string `json:"path"`
+ Remote string `json:"remote"`
+ Backend string `json:"backend,omitempty"`
+ ReadOnly bool `json:"readOnly"`
+ Persistent bool `json:"persistent,omitempty"`
+ Status string `json:"status,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+// AddRequest is the wire shape the HTTP layer parses and hands to Service.Add.
+type AddRequest 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"` // s3, gcs, azureblob, sftp, webdav, dropbox
+ Creds map[string]string `json:"creds"` // backend-specific config keys
+ RcloneConfig string `json:"rcloneConfig"` // raw config; overrides backend+creds
+ ReadOnly *bool `json:"readOnly"` // default true
+ Persistent bool `json:"persistent"` // encrypt + persist in PG; auto-restore on wake
+ MountOptions []string `json:"mountOptions"` // extra args appended to `rclone mount`
+}
+
+// Service holds the cross-cutting state for the mounts feature.
+//
+// Registry is process-local and intentionally so: non-persistent mounts vanish
+// on hibernate by design, and persistent mounts are rehydrated from PG on wake.
+// Store is optional — when nil, persistent mounts are unavailable (Add returns
+// a clear ErrPersistenceUnavailable).
+type Service struct {
+ manager sandbox.Manager
+ store *db.Store
+ registry *Registry
+}
+
+// ErrPersistenceUnavailable is returned by Service.Add when the caller passes
+// Persistent:true but the server has no Store / no encryption key.
+var ErrPersistenceUnavailable = fmt.Errorf("persistent mounts require OPENSANDBOX_SECRET_ENCRYPTION_KEY to be configured")
+
+// NewService wires a Service. Pass nil for store when persistent mounts aren't
+// supported in this binary (e.g. local dev without PG).
+func NewService(manager sandbox.Manager, store *db.Store) *Service {
+ return &Service{
+ manager: manager,
+ store: store,
+ registry: newRegistry(),
+ }
+}
+
+// List returns the current view of mounts the worker knows about for this
+// sandbox. Non-nil empty slice when there are none, so HTTP handlers can
+// marshal directly.
+func (s *Service) List(sandboxID string) []MountRecord {
+ recs := s.registry.get(sandboxID)
+ if recs == nil {
+ return []MountRecord{}
+ }
+ return recs
+}
+
+// Add validates the request, performs the live mount in the sandbox, records
+// the in-memory entry, and (when Persistent) encrypts + persists the config so
+// it survives hibernate.
+//
+// On rollback paths (persist failure after a successful live mount), Add tears
+// down the live mount so the user view is consistent — no "persistent in name
+// only" footgun.
+func (s *Service) Add(ctx context.Context, sandboxID string, req AddRequest) (MountRecord, error) {
+ if req.Path == "" || req.Remote == "" {
+ return MountRecord{}, fmt.Errorf("path and remote are required")
+ }
+ if !strings.HasPrefix(req.Path, "/") {
+ return MountRecord{}, fmt.Errorf("path must be absolute")
+ }
+ if req.Persistent {
+ if s.store == nil || s.store.Encryptor() == nil {
+ return MountRecord{}, ErrPersistenceUnavailable
+ }
+ }
+
+ rcloneConf, err := renderRcloneConfig(req)
+ if err != nil {
+ return MountRecord{}, err
+ }
+ readOnly := true
+ if req.ReadOnly != nil {
+ readOnly = *req.ReadOnly
+ }
+
+ if err := s.doMount(ctx, sandboxID, req.Path, rcloneConf, readOnly, req.MountOptions); err != nil {
+ return MountRecord{}, err
+ }
+
+ rec := MountRecord{
+ Path: req.Path,
+ Remote: req.Remote,
+ Backend: req.Backend,
+ ReadOnly: readOnly,
+ Persistent: req.Persistent,
+ Status: "active",
+ }
+ s.registry.put(sandboxID, rec)
+
+ if req.Persistent {
+ ct, err := s.store.Encryptor().Encrypt([]byte(rcloneConf))
+ if err != nil {
+ s.rollbackLiveMount(ctx, sandboxID, req.Path)
+ return MountRecord{}, fmt.Errorf("encrypt mount config: %w", err)
+ }
+ if err := s.store.UpsertSandboxMount(ctx, db.PersistentMount{
+ SandboxID: sandboxID,
+ Path: req.Path,
+ Remote: req.Remote,
+ Backend: req.Backend,
+ ReadOnly: readOnly,
+ MountOptions: req.MountOptions,
+ EncryptedConfig: ct,
+ }); err != nil {
+ s.rollbackLiveMount(ctx, sandboxID, req.Path)
+ return MountRecord{}, fmt.Errorf("persist mount: %w", err)
+ }
+ }
+ return rec, nil
+}
+
+// Remove unmounts and forgets the mount. Idempotent — no error when the path
+// isn't mounted. Always best-effort PG delete (no error if the row never existed).
+func (s *Service) Remove(ctx context.Context, sandboxID, path string) error {
+ if err := s.unmountInVM(ctx, sandboxID, path); err != nil {
+ return err
+ }
+ s.registry.remove(sandboxID, path)
+ if s.store != nil {
+ if err := s.store.DeleteSandboxMount(ctx, sandboxID, path); err != nil {
+ log.Printf("mounts: failed to delete persistent mount row %s/%s: %v", sandboxID, path, err)
+ }
+ }
+ return nil
+}
+
+// OnHibernate clears the non-persistent entries from the registry so list()
+// reflects reality post-hibernate. Persistent entries stay (status flips to
+// "replaying") so the UI shows the intent across the hibernate→wake gap.
+//
+// Call this from the same place that triggers `fusermount3 -u -a` in the VM
+// (snapshot.go does the in-VM teardown; this is the registry-side complement).
+func (s *Service) OnHibernate(sandboxID string) {
+ s.registry.clearNonPersistent(sandboxID)
+}
+
+// OnWake is the SandboxRouter post-wake hook. Reads persistent mounts from
+// PG, pre-populates the registry with status="replaying", and replays each
+// mount in its own goroutine.
+//
+// Wake completion is NOT blocked on replay; failures surface as
+// status="failed" in list() and last_error in PG. The user can remove the
+// broken mount or re-add with fresh creds.
+func (s *Service) OnWake(ctx context.Context, sandboxID string) {
+ if s.store == nil || s.store.Encryptor() == nil {
+ return
+ }
+ mounts, err := s.store.ListSandboxMounts(ctx, sandboxID)
+ if err != nil {
+ log.Printf("mounts: list persistent mounts for %s: %v", sandboxID, err)
+ return
+ }
+ for _, m := range mounts {
+ s.registry.put(sandboxID, MountRecord{
+ Path: m.Path,
+ Remote: m.Remote,
+ Backend: m.Backend,
+ ReadOnly: m.ReadOnly,
+ Persistent: true,
+ Status: "replaying",
+ })
+ go s.replayOne(sandboxID, m)
+ }
+}
+
+func (s *Service) replayOne(sandboxID string, m db.PersistentMount) {
+ // Background context — wake replay must not be tied to whatever request
+ // originally triggered the wake (it may have ended already).
+ ctx := context.Background()
+ plaintext, err := s.store.Encryptor().Decrypt(m.EncryptedConfig)
+ if err != nil {
+ s.markFailed(ctx, sandboxID, m, fmt.Sprintf("decrypt config: %v", err))
+ return
+ }
+ if err := s.doMount(ctx, sandboxID, m.Path, string(plaintext), m.ReadOnly, m.MountOptions); err != nil {
+ s.markFailed(ctx, sandboxID, m, err.Error())
+ return
+ }
+ s.markActive(ctx, sandboxID, m)
+}
+
+func (s *Service) markActive(ctx context.Context, sandboxID string, m db.PersistentMount) {
+ s.registry.put(sandboxID, MountRecord{
+ Path: m.Path, Remote: m.Remote, Backend: m.Backend, ReadOnly: m.ReadOnly,
+ Persistent: true, Status: "active",
+ })
+ if s.store != nil {
+ _ = s.store.SetSandboxMountError(ctx, sandboxID, m.Path, "")
+ }
+}
+
+func (s *Service) markFailed(ctx context.Context, sandboxID string, m db.PersistentMount, msg string) {
+ log.Printf("mounts: persistent replay failed for %s/%s: %s", sandboxID, m.Path, msg)
+ s.registry.put(sandboxID, MountRecord{
+ Path: m.Path, Remote: m.Remote, Backend: m.Backend, ReadOnly: m.ReadOnly,
+ Persistent: true, Status: "failed", Error: msg,
+ })
+ if s.store != nil {
+ _ = s.store.SetSandboxMountError(ctx, sandboxID, m.Path, msg)
+ }
+}
+
+func (s *Service) rollbackLiveMount(ctx context.Context, sandboxID, path string) {
+ _ = s.unmountInVM(ctx, sandboxID, path)
+ s.registry.remove(sandboxID, path)
+}
+
+// doMount is the shared orchestration: probe rclone is present, write the
+// config to tmpfs, mkdir the target, exec `rclone mount --daemon`.
+func (s *Service) doMount(ctx context.Context, sandboxID, target, rcloneConf string, readOnly bool, mountOptions []string) error {
+ confPath := mountConfPath(target)
+
+ probe, perr := s.manager.Exec(ctx, sandboxID, 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, sandboxID, 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, sandboxID, confPath, rcloneConf); err != nil {
+ return fmt.Errorf("write rclone config: %w", err)
+ }
+ if _, err := s.manager.Exec(ctx, sandboxID, 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, sandboxID, 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)
+ }
+
+ remote := remoteFromConfig(rcloneConf)
+ if remote == "" {
+ return fmt.Errorf("could not derive remote name from rclone config")
+ }
+
+ mountArgs := []string{
+ "rclone", "mount", remote, target,
+ "--config", confPath,
+ "--daemon",
+ // --daemon waits for "mount ready" before forking; without a timeout, an
+ // unreachable remote makes the call hang indefinitely (rclone's default
+ // is "wait forever"). Cap at 30s so bad creds / network issues surface
+ // as a clear error in the API response instead of an HTTP 524 from the
+ // upstream proxy timeout.
+ "--daemon-timeout", "30s",
+ "--allow-other",
+ }
+ if readOnly {
+ mountArgs = append(mountArgs, "--read-only")
+ } else {
+ mountArgs = append(mountArgs, "--vfs-cache-mode", "writes")
+ }
+ mountArgs = append(mountArgs, mountOptions...)
+
+ resp, err := s.manager.Exec(ctx, sandboxID, types.ProcessConfig{
+ Command: "sudo",
+ Args: mountArgs,
+ Timeout: 30,
+ })
+ if err != nil {
+ return fmt.Errorf("rclone mount: %w", err)
+ }
+ if resp.ExitCode != 0 {
+ _, _ = s.manager.Exec(ctx, sandboxID, 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
+}
+
+func (s *Service) unmountInVM(ctx context.Context, sandboxID, path string) error {
+ confPath := mountConfPath(path)
+ _, err := s.manager.Exec(ctx, sandboxID, 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
+}
+
+// --- Registry ---
+
+type Registry struct {
+ mu sync.Mutex
+ m map[string][]MountRecord
+}
+
+func newRegistry() *Registry {
+ return &Registry{m: make(map[string][]MountRecord)}
+}
+
+func (r *Registry) 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 *Registry) 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 *Registry) 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 *Registry) clearNonPersistent(sandboxID string) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ cur := r.m[sandboxID]
+ out := cur[:0]
+ for _, rec := range cur {
+ if rec.Persistent {
+ rec.Status = "replaying"
+ out = append(out, rec)
+ }
+ }
+ if len(out) == 0 {
+ delete(r.m, sandboxID)
+ } else {
+ r.m[sandboxID] = out
+ }
+}
+
+// --- Helpers (exported because tests in other packages exercise them) ---
+
+// MountConfPath derives a deterministic tmpfs path for the mount's rclone
+// config. Hashing the target path means add→remove for the same mount path
+// always touches the same file with no opaque ID to track.
+func MountConfPath(path string) string { return mountConfPath(path) }
+
+func mountConfPath(path string) string {
+ sum := sha1.Sum([]byte(path))
+ return "/run/oc-agent/mounts/" + hex.EncodeToString(sum[:])[:16] + ".conf"
+}
+
+// RemoteFromConfig extracts the first `[section]` name from a rclone config.
+// rclone mount takes that name as the `<remote>:<path>` prefix on the command
+// line, so we need it before invoking the mount.
+func RemoteFromConfig(conf string) string { return remoteFromConfig(conf) }
+
+func remoteFromConfig(conf string) string {
+ for _, line := range strings.Split(conf, "\n") {
+ line = strings.TrimSpace(line)
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ return strings.TrimSuffix(strings.TrimPrefix(line, "["), "]")
+ }
+ }
+ return ""
+}
+
+// RenderRcloneConfig builds a single-section rclone config from the typed
+// backend+creds shape, or returns the raw user-supplied config if present.
+// Stable key order so config rendering is deterministic.
+func RenderRcloneConfig(req AddRequest) (string, error) { return renderRcloneConfig(req) }
+
+func renderRcloneConfig(req AddRequest) (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")
+ }
+ }
+ 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/sandbox/router.go b/internal/sandbox/router.go
index 76b1aa8e..2839ce42 100644
--- a/internal/sandbox/router.go
+++ b/internal/sandbox/router.go
@@ -63,6 +63,14 @@ type RouterConfig struct {
DefaultTimeout time.Duration
OnHibernate func(sandboxID string, result *HibernateResult)
OnKill func(sandboxID string) // called when a sandbox is killed on timeout (hibernate failed or no checkpoint store)
+ // OnWake fires after an auto-wake completes successfully (state transitioned
+ // to StateRunning, rolling timer started). Runs in its own goroutine so a
+ // slow callback can't stall the routed operation that triggered the wake.
+ // Use SetOnWake to attach late if you can't supply it at construction time
+ // (e.g. circular dep between router and API server). Explicit-wake API
+ // callers do NOT flow through doWake, so they must invoke their own
+ // post-wake logic — see api.Server.wakeSandbox.
+ OnWake func(sandboxID string)
}
// SandboxRouter routes sandbox interactions through a state machine,
@@ -78,6 +86,7 @@ type SandboxRouter struct {
defaultTimeout time.Duration
onHibernate func(sandboxID string, result *HibernateResult)
onKill func(sandboxID string)
+ onWake func(sandboxID string)
mu sync.RWMutex
sandboxes map[string]*sandboxEntry
@@ -97,10 +106,21 @@ func NewSandboxRouter(cfg RouterConfig) *SandboxRouter {
defaultTimeout: dt,
onHibernate: cfg.OnHibernate,
onKill: cfg.OnKill,
+ onWake: cfg.OnWake,
sandboxes: make(map[string]*sandboxEntry),
}
}
+// SetOnWake attaches (or replaces) the post-auto-wake callback after
+// construction. Useful when the consumer of the hook (e.g. the API server)
+// can't be passed into RouterConfig because of a construction-order or
+// circular-dependency issue.
+func (r *SandboxRouter) SetOnWake(fn func(sandboxID string)) {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.onWake = fn
+}
+
// Use registers middleware that wraps every routed operation.
// Middleware is applied in the order registered (first registered = outermost).
func (r *SandboxRouter) Use(mw Middleware) {
@@ -487,6 +507,17 @@ func (r *SandboxRouter) doWake(ctx context.Context, sandboxID string, entry *san
})
}
entry.mu.Unlock()
+
+ // Fire post-wake hook in its own goroutine — a slow user-supplied callback
+ // (e.g. persistent mount replay that talks to S3) must not stall the
+ // routed operation that triggered the auto-wake. Read the field under the
+ // router mutex because SetOnWake can re-bind it.
+ r.mu.RLock()
+ hook := r.onWake
+ r.mu.RUnlock()
+ if hook != nil {
+ go hook(sandboxID)
+ }
}
// resetTimeout resets the rolling timeout for a sandbox.
diff --git a/internal/worker/http_server.go b/internal/worker/http_server.go
index 14eae37f..30d36399 100644
--- a/internal/worker/http_server.go
+++ b/internal/worker/http_server.go
@@ -1,11 +1,14 @@
package worker
import (
+ "context"
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/opensandbox/opensandbox/internal/auth"
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/mounts"
"github.com/opensandbox/opensandbox/internal/observability"
"github.com/opensandbox/opensandbox/internal/obslog"
"github.com/opensandbox/opensandbox/internal/proxy"
@@ -22,11 +25,14 @@ type HTTPServer struct {
jwtIssuer *auth.JWTIssuer
sandboxDBs *sandbox.SandboxDBManager
router *sandbox.SandboxRouter
+ mountSvc *mounts.Service // nil when store is unavailable
sandboxDomain string
}
// NewHTTPServer creates a new worker HTTP server for direct SDK access.
-func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string) *HTTPServer {
+// Pass a non-nil store to enable the mounts API (and persistent mounts in
+// particular — they need PG + encryptor for at-rest cred storage).
+func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *sandbox.ExecSessionManager, jwtIssuer *auth.JWTIssuer, sandboxDBs *sandbox.SandboxDBManager, sbProxy *proxy.SandboxProxy, sbRouter *sandbox.SandboxRouter, sandboxDomain string, store *db.Store) *HTTPServer {
e := echo.New()
e.HideBanner = true
e.HidePort = true
@@ -41,6 +47,18 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
router: sbRouter,
sandboxDomain: sandboxDomain,
}
+ if mgr != nil {
+ s.mountSvc = mounts.NewService(mgr, store)
+ // Wire post-auto-wake hook so persistent mounts replay when the worker's
+ // router auto-wakes a sandbox on incoming request. Without this, only
+ // CP-initiated explicit wakes trigger replay; auto-wake-on-request
+ // (the most common flow) would silently lose persistent mounts.
+ if sbRouter != nil {
+ sbRouter.SetOnWake(func(sandboxID string) {
+ s.mountSvc.OnWake(context.Background(), sandboxID)
+ })
+ }
+ }
// Global middleware. Sentry goes first so it can observe panics and
// attach request context before echo's Recover middleware handles them.
@@ -88,6 +106,11 @@ func NewHTTPServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, execMgr *san
api.POST("/sandboxes/:id/files/mkdir", s.makeDir)
api.DELETE("/sandboxes/:id/files", s.removeFile)
+ // Mounts (FUSE via rclone)
+ api.POST("/sandboxes/:id/mounts", s.addMount)
+ api.GET("/sandboxes/:id/mounts", s.listMounts)
+ api.DELETE("/sandboxes/:id/mounts", s.removeMount)
+
// Token refresh
api.POST("/sandboxes/:id/token/refresh", s.refreshToken)
diff --git a/internal/worker/mounts.go b/internal/worker/mounts.go
new file mode 100644
index 00000000..b57b9ccf
--- /dev/null
+++ b/internal/worker/mounts.go
@@ -0,0 +1,72 @@
+package worker
+
+import (
+ "context"
+ "errors"
+ "net/http"
+
+ "github.com/labstack/echo/v4"
+ "github.com/opensandbox/opensandbox/internal/mounts"
+)
+
+// HTTP handlers for the mounts API served directly from the worker. The
+// control-plane proxies /api/sandboxes/:id/mounts to here in server mode (and
+// in combined mode, the api.Server has its own handlers that hit the same
+// underlying mounts.Service shape). Behavior identical to the CP-side handlers.
+
+func (s *HTTPServer) addMount(c echo.Context) error {
+ if s.mountSvc == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "mounts not available"})
+ }
+ id := c.Param("id")
+
+ var req mounts.AddRequest
+ if err := c.Bind(&req); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid body: " + err.Error()})
+ }
+
+ var rec mounts.MountRecord
+ routeOp := func(ctx context.Context) error {
+ var err error
+ rec, err = s.mountSvc.Add(ctx, id, req)
+ return err
+ }
+ if err := s.routeOrCall(c, id, "mountAdd", routeOp); err != nil {
+ status := http.StatusInternalServerError
+ if errors.Is(err, mounts.ErrPersistenceUnavailable) {
+ status = http.StatusServiceUnavailable
+ }
+ return c.JSON(status, map[string]string{"error": err.Error()})
+ }
+ return c.JSON(http.StatusCreated, rec)
+}
+
+func (s *HTTPServer) listMounts(c echo.Context) error {
+ if s.mountSvc == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "mounts not available"})
+ }
+ return c.JSON(http.StatusOK, s.mountSvc.List(c.Param("id")))
+}
+
+func (s *HTTPServer) removeMount(c echo.Context) error {
+ if s.mountSvc == nil {
+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "mounts not available"})
+ }
+ id := c.Param("id")
+ path := c.QueryParam("path")
+ if path == "" {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "path query parameter is required"})
+ }
+ routeOp := func(ctx context.Context) error { return s.mountSvc.Remove(ctx, id, path) }
+ if err := s.routeOrCall(c, id, "mountRemove", routeOp); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
+ }
+ return c.NoContent(http.StatusNoContent)
+}
+
+func (s *HTTPServer) 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())
+}
diff --git a/sdks/python/opencomputer/mounts.py b/sdks/python/opencomputer/mounts.py
index 9e11bed3..9bb50dc1 100644
--- a/sdks/python/opencomputer/mounts.py
+++ b/sdks/python/opencomputer/mounts.py
@@ -19,12 +19,21 @@ MountBackend = Literal["s3", "gcs", "azureblob", "sftp", "webdav", "dropbox"]
@dataclass
class MountInfo:
- """An active mount as tracked by the worker."""
+ """An active mount as tracked by the worker.
+
+ ``status`` is one of ``"active"``, ``"replaying"``, or ``"failed"`` for
+ persistent mounts. Empty for non-persistent ones. ``error`` is set when
+ ``status == "failed"`` (typically a wake-time remount failure — bad creds,
+ expired tokens, network).
+ """
path: str
remote: str
read_only: bool
backend: str = ""
+ persistent: bool = False
+ status: str = ""
+ error: str = ""
@dataclass
@@ -42,6 +51,7 @@ class Mounts:
creds: dict[str, str] | None = None,
rclone_config: str | None = None,
read_only: bool = True,
+ persistent: bool = False,
mount_options: list[str] | None = None,
) -> MountInfo:
"""Mount a remote filesystem at ``path`` inside the sandbox.
@@ -59,6 +69,12 @@ class Mounts:
advanced tuning.
read_only: Default ``True``. Object-store FUSE mounts have
well-known write footguns; opt in to RW explicitly.
+ persistent: When ``True``, the encrypted rclone config is stored
+ server-side so the mount auto-restores on wake (both explicit
+ and idle-wake). Failed remounts surface in ``list()`` with
+ ``status="failed"`` instead of silently disappearing. Default
+ ``False``: non-persistent mounts vanish on hibernate and the
+ server never stores the credentials.
mount_options: Extra args appended to ``rclone mount`` (e.g.
``["--dir-cache-time", "1m"]``).
"""
@@ -66,6 +82,7 @@ class Mounts:
"path": path,
"remote": remote,
"readOnly": read_only,
+ "persistent": persistent,
}
if backend is not None:
body["backend"] = backend
@@ -81,12 +98,7 @@ class Mounts:
)
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),
- )
+ return _mount_from_dict(data)
async def list(self) -> list[MountInfo]:
"""List the mounts this worker is tracking for the sandbox.
@@ -97,15 +109,7 @@ class Mounts:
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
- ]
+ return [_mount_from_dict(entry) for entry in data]
async def remove(self, path: str) -> None:
"""Unmount a path previously passed to ``add()``. No-op if not mounted."""
@@ -118,3 +122,15 @@ class Mounts:
resp.raise_for_status()
except httpx.HTTPError:
raise
+
+
+def _mount_from_dict(data: dict) -> MountInfo:
+ return MountInfo(
+ path=data["path"],
+ remote=data["remote"],
+ backend=data.get("backend", ""),
+ read_only=data.get("readOnly", True),
+ persistent=data.get("persistent", False),
+ status=data.get("status", ""),
+ error=data.get("error", ""),
+ )
diff --git a/sdks/typescript/src/mounts.ts b/sdks/typescript/src/mounts.ts
index c4ad4db7..dd365a54 100644
--- a/sdks/typescript/src/mounts.ts
+++ b/sdks/typescript/src/mounts.ts
@@ -37,6 +37,16 @@ export interface AddMountOpts {
rcloneConfig?: string;
/** Default `true`. Object-store FUSE mounts have well-known write footguns. */
readOnly?: boolean;
+ /**
+ * When `true`, the encrypted rclone config is persisted server-side so the
+ * mount is automatically restored on wake (both explicit and idle-wake). If
+ * the post-wake remount fails, the mount appears in `list()` with
+ * `status: "failed"` and an `error` message instead of silently disappearing.
+ *
+ * Defaults to `false` — non-persistent mounts vanish on hibernate and the
+ * server never stores the credentials.
+ */
+ persistent?: boolean;
/** Extra args appended to `rclone mount` (e.g. `["--dir-cache-time", "1m"]`). */
mountOptions?: string[];
}
@@ -46,6 +56,11 @@ export interface MountInfo {
remote: string;
backend?: string;
readOnly: boolean;
+ persistent?: boolean;
+ /** "active" | "replaying" | "failed". Empty/absent for non-persistent mounts. */
+ status?: string;
+ /** Set when `status === "failed"`. */
+ error?: string;
}
export class Mounts {