Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

feat(execd): serve the session-private /tmp through the files API

高然0f6d4ae9c5d3
diff --git a/components/execd/pkg/isolation/bwrap.go b/components/execd/pkg/isolation/bwrap.go
index 75cff2aff..611716fee 100644
--- a/components/execd/pkg/isolation/bwrap.go
+++ b/components/execd/pkg/isolation/bwrap.go
@@ -61,9 +61,15 @@ func buildArgvWithLifecycle(
// 2. Root filesystem (read-only).
argv = append(argv, "--ro-bind", "/", "/")
- // 3. /tmp — skip if an overlay mounts over /tmp (its mount would override).
- if !overlaysCoverPath(opts.Overlays, "/tmp") {
- argv = append(argv, bwrapTmpSegment(opts.Profile)...)
+ // 3. /tmp — the session-private host-backed bind when the runner
+ // provisioned a backing dir, else the profile default. Skipped if an
+ // overlay mounts over /tmp (its mount would override).
+ if !OverlaysCoverPath(opts.Overlays, "/tmp") {
+ if opts.TmpDir != "" {
+ argv = append(argv, "--bind", opts.TmpDir, "/tmp")
+ } else {
+ argv = append(argv, bwrapTmpSegment(opts.Profile)...)
+ }
}
// 4. Overlay mounts (workspace, root overlay, extra overlays), ordered
@@ -227,6 +233,9 @@ func validateWrapOptions(opts WrapOptions) error {
if opts.UidMode != "" && !opts.UidMode.Valid() {
return fmt.Errorf("isolation: unknown uid mode %q", opts.UidMode)
}
+ if opts.TmpDir != "" && !filepath.IsAbs(opts.TmpDir) {
+ return fmt.Errorf("isolation: tmp dir %q must be an absolute path", opts.TmpDir)
+ }
return validateBinds(opts.Binds)
}
@@ -344,20 +353,6 @@ func bwrapTmpSegment(p Profile) []string {
}
}
-// overlaysCoverPath reports whether any overlay mounts over path, either
-// at path itself or at one of its ancestors: bubblewrap applies mounts in
-// argv order and a later shallower mount shadows the subtree of any earlier
-// segment, so an ancestor overlay already provides path.
-func overlaysCoverPath(overlays []OverlaySpec, path string) bool {
- for _, ov := range overlays {
- p := filepath.Clean(ov.Path)
- if p == path || p == "/" || strings.HasPrefix(path, p+"/") {
- return true
- }
- }
- return false
-}
-
// pathDepth counts the segments of a cleaned absolute path: "/" → 0,
// "/workspace" → 1, "/workspace/sub" → 2.
func pathDepth(p string) int {
diff --git a/components/execd/pkg/isolation/bwrap_test.go b/components/execd/pkg/isolation/bwrap_test.go
index 83fe96c76..542968e4d 100644
--- a/components/execd/pkg/isolation/bwrap_test.go
+++ b/components/execd/pkg/isolation/bwrap_test.go
@@ -84,6 +84,51 @@ func TestBuildArgv_TmpSegment(t *testing.T) {
}
}
+func TestBuildArgv_TmpDir(t *testing.T) {
+ t.Run("host_backed_bind_replaces_profile_segment", func(t *testing.T) {
+ opts := basicWrapOpts()
+ opts.Profile = ProfileStrict
+ opts.TmpDir = "/var/lib/execd/isolation/abc/tmp"
+ argv, err := buildArgv(opts, "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ s := strings.Join(argv, " ")
+ if !strings.Contains(s, "--bind /var/lib/execd/isolation/abc/tmp /tmp") {
+ t.Errorf("missing host-backed /tmp bind:\n %s", s)
+ }
+ if strings.Contains(s, "--tmpfs /tmp") {
+ t.Errorf("profile tmpfs segment must be replaced:\n %s", s)
+ }
+ })
+
+ t.Run("overlay_on_tmp_skips_host_bind", func(t *testing.T) {
+ opts := basicWrapOpts()
+ opts.Profile = ProfileStrict
+ opts.TmpDir = "/var/lib/execd/isolation/abc/tmp"
+ opts.Overlays = append(opts.Overlays, OverlaySpec{Path: "/tmp", Mode: WorkspaceRW})
+ argv, err := buildArgv(opts, "")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ s := strings.Join(argv, " ")
+ if strings.Contains(s, "/var/lib/execd/isolation/abc/tmp") {
+ t.Errorf("host-backed /tmp bind must be skipped when an overlay covers /tmp:\n %s", s)
+ }
+ if !strings.Contains(s, "--bind /tmp /tmp") {
+ t.Errorf("overlay segment missing:\n %s", s)
+ }
+ })
+
+ t.Run("relative_tmp_dir_rejected", func(t *testing.T) {
+ opts := basicWrapOpts()
+ opts.TmpDir = "relative/tmp"
+ if _, err := buildArgv(opts, ""); err == nil {
+ t.Error("expected error for relative tmp dir")
+ }
+ })
+}
+
func TestBuildArgv_WorkspaceSegment(t *testing.T) {
ws := func(mode WorkspaceMode) WrapOptions {
opts := basicWrapOpts()
@@ -164,11 +209,11 @@ func TestOverlaysCoverPath(t *testing.T) {
{Path: "/data", Mode: WorkspaceOverlay},
}
- assert.True(t, overlaysCoverPath(overlays, "/tmp"),
+ assert.True(t, OverlaysCoverPath(overlays, "/tmp"),
"a / overlay is an ancestor of /tmp and covers it")
- assert.True(t, overlaysCoverPath(overlays, "/data/sub"),
+ assert.True(t, OverlaysCoverPath(overlays, "/data/sub"),
"an exact overlay path covers its own subtree")
- assert.False(t, overlaysCoverPath(overlays[1:], "/tmp"),
+ assert.False(t, OverlaysCoverPath(overlays[1:], "/tmp"),
"a sibling overlay must not cover /tmp")
}
diff --git a/components/execd/pkg/isolation/isolator.go b/components/execd/pkg/isolation/isolator.go
index 9579a7cec..a31803317 100644
--- a/components/execd/pkg/isolation/isolator.go
+++ b/components/execd/pkg/isolation/isolator.go
@@ -18,6 +18,8 @@ package isolation
import (
"context"
"os/exec"
+ "path/filepath"
+ "strings"
)
// Profile presets default isolation settings.
@@ -149,16 +151,36 @@ type Capabilities struct {
// WrapOptions configures a single isolated execution.
type WrapOptions struct {
- Profile Profile
- Overlays []OverlaySpec
- ExtraWritable []string
- Binds []BindMount
+ Profile Profile
+ Overlays []OverlaySpec
+ ExtraWritable []string
+ Binds []BindMount
+ // TmpDir is an absolute host directory bound to the namespace /tmp,
+ // replacing the profile's /tmp segment. It is the session-private /tmp
+ // backing directory under the session's upper-root subtree, so the
+ // files API can serve the same content run sees. Empty keeps the
+ // profile default (strict: private tmpfs, balanced: shared bind).
+ TmpDir string
ShareNet bool
EnvPassthrough EnvSpec
Uid, Gid *uint32
UidMode UidMode // "" or "setpriv" → setpriv; "userns" → user namespace
}
+// OverlaysCoverPath reports whether any overlay mounts over path, either
+// at path itself or at one of its ancestors: bubblewrap applies mounts in
+// argv order and a later shallower mount shadows the subtree of any earlier
+// segment, so an ancestor overlay already provides path.
+func OverlaysCoverPath(overlays []OverlaySpec, path string) bool {
+ for _, ov := range overlays {
+ p := filepath.Clean(ov.Path)
+ if p == path || p == "/" || strings.HasPrefix(path, p+"/") {
+ return true
+ }
+ }
+ return false
+}
+
// Isolator wraps an *exec.Cmd in a namespace-isolated execution environment.
type Isolator interface {
Name() string
diff --git a/components/execd/pkg/isolation/upper.go b/components/execd/pkg/isolation/upper.go
index a9e62af00..19cec78a3 100644
--- a/components/execd/pkg/isolation/upper.go
+++ b/components/execd/pkg/isolation/upper.go
@@ -30,6 +30,11 @@ import (
const cleanupRegistryName = ".execd-cleanup"
+// tmpDirName is the per-session directory backing the namespace /tmp bind
+// (strict profile). It lives inside the session subtree, so session
+// teardown removes it with everything else.
+const tmpDirName = "tmp"
+
// UpperManager manages upper directories for overlay workspaces.
type UpperManager struct {
root string
@@ -152,9 +157,50 @@ func (m *UpperManager) Allocate() (sessionID, upperDir, workDir string, err erro
return id, pairs[0].UpperDir, pairs[0].WorkDir, nil
}
+// TmpDir returns the /tmp backing directory of an allocated session.
+func (m *UpperManager) TmpDir(sessionID string) string {
+ return filepath.Join(m.root, sessionID, tmpDirName)
+}
+
+// AllocateSessionDir creates a session directory without overlay pairs, for
+// sessions whose mounts need no host uppers. The directory still carries a
+// durable cleanup record and holds the session's /tmp backing directory, so
+// teardown and crash recovery treat it like any allocated session.
+// Returns ErrUpperLimitExceeded if maxBytes > 0 and current usage already
+// meets or exceeds the limit.
+func (m *UpperManager) AllocateSessionDir() (sessionID string, err error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if m.maxBytes > 0 {
+ usage, usageErr := m.usageLocked()
+ if usageErr != nil {
+ return "", fmt.Errorf("upper: measure usage before allocation: %w", usageErr)
+ }
+ if usage >= m.maxBytes {
+ return "", fmt.Errorf("%w: %d >= %d bytes", ErrUpperLimitExceeded, usage, m.maxBytes)
+ }
+ }
+
+ id, err := m.createCleanupRecordLocked()
+ if err != nil {
+ return "", err
+ }
+ sessionDir := filepath.Join(m.root, id)
+ if err := os.MkdirAll(filepath.Join(sessionDir, tmpDirName), 0o755); err != nil {
+ if rollbackErr := m.rollbackAllocationLocked(id, sessionDir, nil); rollbackErr != nil {
+ return "", errors.Join(err, rollbackErr)
+ }
+ return "", fmt.Errorf("upper: mkdir session dir %s: %w", sessionDir, err)
+ }
+ m.entries[id] = &UpperEntry{InUse: true, dir: sessionDir}
+ return id, nil
+}
+
// AllocateN creates a new session directory holding n upper + work pairs,
// one per overlay mount. Pair 0 lives at <root>/<id>/upper and
-// <root>/<id>/work; pair i>0 at <root>/<id>/upper-<i> and work-<i>.
+// <root>/<id>/work; pair i>0 at <root>/<id>/upper-<i> and work-<i>. The
+// session directory also holds the /tmp backing directory (TmpDir).
// Returns ErrUpperLimitExceeded if maxBytes > 0 and current usage already
// meets or exceeds the limit.
func (m *UpperManager) AllocateN(n int) (sessionID string, pairs []UpperDirPair, err error) {
@@ -188,6 +234,9 @@ func (m *UpperManager) AllocateN(n int) (sessionID string, pairs []UpperDirPair,
}
return "", nil, cause
}
+ if err := os.MkdirAll(filepath.Join(sessionDir, tmpDirName), 0o755); err != nil {
+ return failAllocation(fmt.Errorf("upper: mkdir %s: %w", filepath.Join(sessionDir, tmpDirName), err))
+ }
for i := range n {
upperName, workName := "upper", "work"
if i > 0 {
diff --git a/components/execd/pkg/isolation/upper_test.go b/components/execd/pkg/isolation/upper_test.go
index 676da6dcc..dd9beded6 100644
--- a/components/execd/pkg/isolation/upper_test.go
+++ b/components/execd/pkg/isolation/upper_test.go
@@ -729,3 +729,69 @@ func newTestUpperManager(t *testing.T) *UpperManager {
}
return mgr
}
+
+func TestAllocateSessionDir(t *testing.T) {
+ mgr := newTestUpperManager(t)
+
+ id, err := mgr.AllocateSessionDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !validSessionID(id) {
+ t.Fatalf("AllocateSessionDir id = %q, want a valid session id", id)
+ }
+
+ tmpDir := mgr.TmpDir(id)
+ info, err := os.Stat(tmpDir)
+ if err != nil || !info.IsDir() {
+ t.Fatalf("tmp dir %s missing: %v", tmpDir, err)
+ }
+ sessionDir := filepath.Dir(tmpDir)
+ for _, name := range []string{"upper", "work"} {
+ if _, err := os.Stat(filepath.Join(sessionDir, name)); !os.IsNotExist(err) {
+ t.Errorf("pair-less session dir should not hold %q: %v", name, err)
+ }
+ }
+
+ // Remove tears down the whole session subtree and retires the record.
+ if err := mgr.Remove(id); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(sessionDir); !os.IsNotExist(err) {
+ t.Errorf("session dir survived Remove: %v", err)
+ }
+}
+
+func TestAllocateSessionDir_ReleasedEntryCollects(t *testing.T) {
+ mgr := newTestUpperManager(t)
+
+ id, err := mgr.AllocateSessionDir()
+ if err != nil {
+ t.Fatal(err)
+ }
+ mgr.Release(id)
+
+ // A released pair-less entry still collects cleanly.
+ freed := mgr.Collect()
+ if len(freed) != 1 || freed[0] != id {
+ t.Fatalf("Collect freed = %v, want [%s]", freed, id)
+ }
+}
+
+func TestAllocateN_CreatesTmpDir(t *testing.T) {
+ mgr := newTestUpperManager(t)
+
+ id, pairs, err := mgr.AllocateN(2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(mgr.TmpDir(id))
+ if err != nil || !info.IsDir() {
+ t.Fatalf("AllocateN session missing tmp dir: %v", err)
+ }
+ for _, pair := range pairs {
+ if pair.UpperDir == mgr.TmpDir(id) || pair.WorkDir == mgr.TmpDir(id) {
+ t.Fatal("tmp dir must not collide with upper/work pairs")
+ }
+ }
+}
diff --git a/components/execd/pkg/runtime/bwrap_test/bwrap_tmp_files_test.go b/components/execd/pkg/runtime/bwrap_test/bwrap_tmp_files_test.go
new file mode 100644
index 000000000..6ca4ef5ae
--- /dev/null
+++ b/components/execd/pkg/runtime/bwrap_test/bwrap_tmp_files_test.go
@@ -0,0 +1,178 @@
+// Copyright 2026 The OpenSandbox Authors
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//go:build linux && bwrap
+
+package bwrap_test
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/alibaba/opensandbox/execd/pkg/isolation"
+ "github.com/alibaba/opensandbox/execd/pkg/runtime"
+)
+
+// newStrictRunner creates a runner whose upper root lives in a known temp
+// dir, so tests can locate the session /tmp backing directories on the host.
+func newStrictRunner(t *testing.T) (*runtime.IsolatedRunner, string) {
+ t.Helper()
+ upperRoot := filepath.Join(t.TempDir(), "isolation")
+ r := newRunnerWithConfig(t, isolation.Config{
+ UpperRoot: upperRoot,
+ UpperMaxBytes: 1 << 30,
+ AllowedWritable: []string{"/tmp"},
+ })
+ return r, upperRoot
+}
+
+// strictSession creates a default (strict profile) session: its /tmp is the
+// session-private bind backed by a host dir under the runner's upper root.
+func strictSession(t *testing.T, r *runtime.IsolatedRunner) string {
+ t.Helper()
+ id, err := r.CreateIsolatedSession(&runtime.IsolatedSessionOptions{
+ WorkspacePath: t.TempDir(),
+ WorkspaceMode: "rw",
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = r.DeleteIsolatedSession(id) })
+ return id
+}
+
+// tmpBackingDir returns the /tmp backing directory of the single live
+// session under upperRoot.
+func tmpBackingDir(t *testing.T, upperRoot string) string {
+ t.Helper()
+ hits, err := filepath.Glob(filepath.Join(upperRoot, "*", "tmp"))
+ require.NoError(t, err)
+ require.Len(t, hits, 1, "expected exactly one session /tmp backing dir under %s", upperRoot)
+ return hits[0]
+}
+
+// TestTmpFiles_RunWriteVisibleViaFilesAPI is the issue #2413 scenario: a
+// command inside the strict session writes /tmp with shell redirection, and
+// the session files API must read the same data back through /tmp.
+func TestTmpFiles_RunWriteVisibleViaFilesAPI(t *testing.T) {
+ r, upperRoot := newStrictRunner(t)
+ id := strictSession(t, r)
+ backing := tmpBackingDir(t, upperRoot)
+
+ runInSession(t, r, id, "echo run-data > /tmp/run.txt", nil)
+
+ // Host side: the write landed in the session's backing dir.
+ host, err := os.ReadFile(filepath.Join(backing, "run.txt"))
+ require.NoError(t, err)
+ assert.Equal(t, "run-data\n", string(host))
+
+ // Files API side: /tmp routes to the same directory.
+ mv, err := r.GetMergedView(id)
+ require.NoError(t, err)
+ data, err := mv.ReadFile("/tmp/run.txt")
+ require.NoError(t, err, "files API must read data run wrote into /tmp")
+ assert.Equal(t, "run-data\n", string(data))
+}
+
+// TestTmpFiles_APIWriteVisibleToRun is the reverse direction: the files API
+// writes /tmp, and a shell command inside the session observes it.
+func TestTmpFiles_APIWriteVisibleToRun(t *testing.T) {
+ r, upperRoot := newStrictRunner(t)
+ id := strictSession(t, r)
+ backing := tmpBackingDir(t, upperRoot)
+
+ mv, err := r.GetMergedView(id)
+ require.NoError(t, err)
+ require.NoError(t, mv.WriteFile("/tmp/api.txt", []byte("api-data"), 0o644))
+
+ host, err := os.ReadFile(filepath.Join(backing, "api.txt"))
+ require.NoError(t, err)
+ assert.Equal(t, "api-data", string(host))
+
+ var lines []string
+ runInSession(t, r, id, "cat /tmp/api.txt", func(line string) { lines = append(lines, line) })
+ assert.Equal(t, []string{"api-data"}, lines)
+}
+
+// TestTmpFiles_SessionPrivateAndTeardown: two strict sessions see two
+// distinct /tmp namespaces, and deleting a session removes its /tmp backing
+// directory together with the rest of its session state.
+func TestTmpFiles_SessionPrivateAndTeardown(t *testing.T) {
+ r, upperRoot := newStrictRunner(t)
+ idA := strictSession(t, r)
+ idB := strictSession(t, r)
+
+ runInSession(t, r, idA, "echo secret-a > /tmp/a.txt", nil)
+ runInSession(t, r, idB, "echo secret-b > /tmp/b.txt", nil)
+
+ mvA, err := r.GetMergedView(idA)
+ require.NoError(t, err)
+ mvB, err := r.GetMergedView(idB)
+ require.NoError(t, err)
+
+ data, err := mvA.ReadFile("/tmp/a.txt")
+ require.NoError(t, err)
+ assert.Equal(t, "secret-a\n", string(data))
+
+ _, err = mvB.ReadFile("/tmp/a.txt")
+ require.Error(t, err, "session B must not see session A's /tmp content")
+ _, err = mvA.ReadFile("/tmp/b.txt")
+ require.Error(t, err, "session A must not see session B's /tmp content")
+
+ require.NoError(t, r.DeleteIsolatedSession(idA))
+ _, err = mvA.ReadFile("/tmp/a.txt")
+ require.Error(t, err, "deleted session's files view must be gone")
+
+ // Session A's subtree (including its /tmp backing dir) is removed;
+ // session B's backing dir and content survive.
+ remainingDirs, err := filepath.Glob(filepath.Join(upperRoot, "*", "tmp"))
+ require.NoError(t, err)
+ require.Len(t, remainingDirs, 1, "only session B's /tmp backing dir should remain")
+ remaining, err := filepath.Glob(filepath.Join(upperRoot, "*", "tmp", "a.txt"))
+ require.NoError(t, err)
+ assert.Empty(t, remaining, "session A's /tmp files must be gone after delete")
+
+ data, err = mvB.ReadFile("/tmp/b.txt")
+ require.NoError(t, err)
+ assert.Equal(t, "secret-b\n", string(data))
+}
+
+// TestTmpFiles_MountOnTmpServedByFilesAPI: a session mount covering /tmp
+// replaces the session-private bind inside the namespace, and the files API
+// must follow the same priority — serving the covering mount's view, not a
+// host bind. (An overlay-mode /tmp lower cannot stack in every environment,
+// so the covering mount uses rw bind semantics.)
+func TestTmpFiles_MountOnTmpServedByFilesAPI(t *testing.T) {
+ r, _ := newStrictRunner(t)
+
+ id, err := r.CreateIsolatedSession(&runtime.IsolatedSessionOptions{
+ WorkspacePath: t.TempDir(),
+ WorkspaceMode: "rw",
+ Overlays: []runtime.IsolatedOverlayOptions{
+ {Path: "/tmp", Mode: "rw"},
+ },
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = r.DeleteIsolatedSession(id) })
+
+ runInSession(t, r, id, "echo mount-tmp > /tmp/mounted.txt", nil)
+
+ mv, err := r.GetMergedView(id)
+ require.NoError(t, err)
+ data, err := mv.ReadFile("/tmp/mounted.txt")
+ require.NoError(t, err, "files API must serve a mount covering /tmp")
+ assert.Equal(t, "mount-tmp\n", string(data))
+}
diff --git a/components/execd/pkg/runtime/isolated_session.go b/components/execd/pkg/runtime/isolated_session.go
index f927b4f64..8045564f6 100644
--- a/components/execd/pkg/runtime/isolated_session.go
+++ b/components/execd/pkg/runtime/isolated_session.go
@@ -131,12 +131,17 @@ type isolatedSession struct {
doneCh chan struct{} // closed after process wait and lifecycle drain
lifecycleMonitorDone chan struct{} // closed after drain-failure monitor exits
upperID string // key in UpperManager, used for Release/Remove
- overlays []sessionOverlay
- createdAt time.Time
- lastRunAt time.Time
- isolator isolation.Isolator
- lifecycle isolation.WorkloadLifecycle
- identity isolation.WorkloadIdentity
+ // tmpDir is the host directory backing the namespace /tmp bind (strict
+ // profile, no overlay covering /tmp). Empty keeps the profile's /tmp
+ // segment; when set, the files view serves /tmp from it. Immutable
+ // after allocation.
+ tmpDir string
+ overlays []sessionOverlay
+ createdAt time.Time
+ lastRunAt time.Time
+ isolator isolation.Isolator
+ lifecycle isolation.WorkloadLifecycle
+ identity isolation.WorkloadIdentity
// activeBackgroundRuns: in-flight detached runs. While non-zero, idle GC
// must not collect the session (background processes die with the bwrap
// process group).
@@ -193,7 +198,11 @@ func (s *isolatedSession) start() error {
wrapOpts := isolation.WrapOptions{
ExtraWritable: s.opts.ExtraWritable,
Binds: s.opts.Binds,
- ShareNet: true,
+ // Empty for balanced sessions and sessions whose overlays cover
+ // /tmp: allocation only sets tmpDir for the hosted-private-/tmp
+ // shape, and bwrap falls back to the profile segment on empty.
+ TmpDir: s.tmpDir,
+ ShareNet: true,
}
switch s.opts.Profile {
diff --git a/components/execd/pkg/runtime/isolated_session_binds_view_test.go b/components/execd/pkg/runtime/isolated_session_binds_view_test.go
index 430660ecd..8988d39e5 100644
--- a/components/execd/pkg/runtime/isolated_session_binds_view_test.go
+++ b/components/execd/pkg/runtime/isolated_session_binds_view_test.go
@@ -476,3 +476,117 @@ type BindMountSpec struct {
source string
dest string
}
+
+// TestNewMergedView_TmpBindRouting covers the hosted private /tmp: the
+// strict profile binds a host directory under the session's upper-root
+// subtree as /tmp, and the files view must serve the same content run
+// writes there (issue #2413).
+func TestNewMergedView_TmpBindRouting(t *testing.T) {
+ base, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ wsLower := filepath.Join(base, "ws")
+ wsUpper := filepath.Join(base, "upper-ws")
+ tmpHost := filepath.Join(base, "session-dir", "tmp")
+ for _, dir := range []string{wsLower, wsUpper, tmpHost} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(tmpHost, "seed.txt"), []byte("tmp-seed"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ persist := true
+ s := newBindsViewSession(t,
+ []IsolatedOverlayOptions{{Path: wsLower, Mode: "overlay", Persist: &persist}},
+ map[int]string{0: wsUpper},
+ nil,
+ )
+ s.tmpDir = tmpHost
+ view := newMergedView(s)
+ if _, ok := view.(*isolation.MultiMergedView); !ok {
+ t.Fatalf("view type %T, want *isolation.MultiMergedView once /tmp is hosted", view)
+ }
+
+ t.Run("read_and_write_via_tmp_reach_host_dir", func(t *testing.T) {
+ data, err := view.ReadFile("/tmp/seed.txt")
+ if err != nil || string(data) != "tmp-seed" {
+ t.Fatalf("ReadFile /tmp/seed.txt = %q, %v", data, err)
+ }
+ if err := view.WriteFile("/tmp/api.txt", []byte("api"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ got, err := os.ReadFile(filepath.Join(tmpHost, "api.txt"))
+ if err != nil || string(got) != "api" {
+ t.Fatalf("/tmp write did not reach the host backing dir: %v, %q", err, got)
+ }
+ })
+
+ t.Run("readdir_lists_tmp", func(t *testing.T) {
+ entries, err := view.ReadDir("/tmp")
+ if err != nil {
+ t.Fatal(err)
+ }
+ names := make(map[string]bool, len(entries))
+ for _, e := range entries {
+ names[e.Name()] = true
+ }
+ for _, want := range []string{"seed.txt", "api.txt"} {
+ if !names[want] {
+ t.Fatalf("ReadDir /tmp missing %q, got %v", want, names)
+ }
+ }
+ })
+
+ t.Run("workspace_routing_unaffected", func(t *testing.T) {
+ if err := os.WriteFile(filepath.Join(wsLower, "seed.txt"), []byte("seed"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := view.Stat(filepath.Join(wsLower, "seed.txt")); err != nil {
+ t.Fatalf("workspace Stat = %v", err)
+ }
+ if _, err := view.Stat("/etc/hostname"); !errors.Is(err, isolation.ErrPathOutsideOverlays) {
+ t.Fatalf("Stat /etc/hostname = %v, want ErrPathOutsideOverlays", err)
+ }
+ })
+}
+
+// TestNewMergedView_BindOnTmpShadowsTmpBind mirrors bwrap argv order: a
+// caller bind at dest /tmp is applied after the session's /tmp bind and
+// shadows it inside the namespace, so the files view must route /tmp to
+// the caller's bind source too.
+func TestNewMergedView_BindOnTmpShadowsTmpBind(t *testing.T) {
+ base, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ wsLower := filepath.Join(base, "ws")
+ tmpHost := filepath.Join(base, "session-dir", "tmp")
+ bindSrc := filepath.Join(base, "bind-src")
+ for _, dir := range []string{wsLower, tmpHost, bindSrc} {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join(tmpHost, "marker.txt"), []byte("session-tmp"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(bindSrc, "marker.txt"), []byte("caller-bind"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ s := newBindsViewSession(t,
+ []IsolatedOverlayOptions{{Path: wsLower, Mode: "rw"}},
+ nil,
+ []isolation.BindMount{{Source: bindSrc, Dest: "/tmp"}},
+ )
+ s.tmpDir = tmpHost
+ view := newMergedView(s)
+
+ data, err := view.ReadFile("/tmp/marker.txt")
+ if err != nil || string(data) != "caller-bind" {
+ t.Fatalf("ReadFile /tmp/marker.txt = %q, %v; want the caller bind to shadow the session /tmp bind", data, err)
+ }
+}
diff --git a/components/execd/pkg/runtime/isolated_session_ctrl.go b/components/execd/pkg/runtime/isolated_session_ctrl.go
index 87ca637bf..a7ba64d1d 100644
--- a/components/execd/pkg/runtime/isolated_session_ctrl.go
+++ b/components/execd/pkg/runtime/isolated_session_ctrl.go
@@ -452,9 +452,28 @@ func (r *IsolatedRunner) CreateIsolatedSession(opts *IsolatedSessionOptions) (st
return id, nil
}
+// sessionTmpBindHosted reports whether the session's namespace /tmp is the
+// session-private bind backed by its upper-root directory: strict profile
+// (the default) with no overlay covering /tmp. Only that shape hosts /tmp
+// on the host side, so only it can be served by the files view.
+func sessionTmpBindHosted(session *isolatedSession) bool {
+ switch isolation.Profile(session.opts.Profile) {
+ case isolation.ProfileStrict, "":
+ default:
+ return false
+ }
+ specs := make([]isolation.OverlaySpec, 0, len(session.overlays))
+ for _, ov := range session.overlays {
+ specs = append(specs, isolation.OverlaySpec{Path: ov.path, Mode: ov.mode})
+ }
+ return !isolation.OverlaysCoverPath(specs, "/tmp")
+}
+
// allocateSessionUppers assigns host upper/work pairs to a session's
// persistent overlays. Ephemeral overlays use the bwrap tmpfs upper and need
-// no allocation.
+// no allocation, but every session still gets an upper-root subtree: it
+// holds the /tmp backing directory and the durable cleanup record that makes
+// teardown crash-safe.
func (r *IsolatedRunner) allocateSessionUppers(session *isolatedSession) error {
persistCount := 0
for _, ov := range session.overlays {
@@ -462,14 +481,24 @@ func (r *IsolatedRunner) allocateSessionUppers(session *isolatedSession) error {
persistCount++
}
}
+
+ var (
+ upperID string
+ pairs []isolation.UpperDirPair
+ err error
+ )
if persistCount == 0 {
- return nil
+ upperID, err = r.upperMgr.AllocateSessionDir()
+ } else {
+ upperID, pairs, err = r.upperMgr.AllocateN(persistCount)
}
- upperID, pairs, err := r.upperMgr.AllocateN(persistCount)
if err != nil {
return fmt.Errorf("allocate upper: %w", err)
}
session.upperID = upperID
+ if sessionTmpBindHosted(session) {
+ session.tmpDir = r.upperMgr.TmpDir(upperID)
+ }
next := 0
for i := range session.overlays {
ov := &session.overlays[i]
@@ -1035,8 +1064,9 @@ func newMergedView(s *isolatedSession) vfs.FS {
}
// Without binds, preserve the historical view shapes (a bare MergedView
- // for the single-overlay session).
- if len(s.opts.Binds) == 0 {
+ // for the single-overlay session). A hosted /tmp counts as a second
+ // mount and falls through to the router.
+ if s.tmpDir == "" && len(s.opts.Binds) == 0 {
switch len(views) {
case 0:
return isolation.NewMultiMergedView(nil)
@@ -1045,6 +1075,20 @@ func newMergedView(s *isolatedSession) vfs.FS {
}
}
+ // The strict profile's private /tmp is the session's host-backed bind
+ // under its upper-root subtree; serve it so files and run share one
+ // /tmp view. Appending it last is safe: no overlay shares the /tmp
+ // destination (guarded at allocation), deeper overlay prefixes win by
+ // length, and binds registered earlier keep the equal-prefix tie
+ // against a caller bind on /tmp — mirroring bwrap's argv shadow order.
+ if s.tmpDir != "" {
+ views = append(views, isolation.OverlayView{
+ Path: "/tmp",
+ Root: s.tmpDir,
+ FS: isolation.NewBindView(s.tmpDir, false, uid, gid),
+ })
+ }
+
// RelativeBase indexing below requires at least one overlay; Create
// enforces that, but newMergedView must not panic if that invariant
// ever changes.
diff --git a/components/execd/pkg/runtime/isolated_session_overlays_test.go b/components/execd/pkg/runtime/isolated_session_overlays_test.go
index 9a02fded9..a904acab3 100644
--- a/components/execd/pkg/runtime/isolated_session_overlays_test.go
+++ b/components/execd/pkg/runtime/isolated_session_overlays_test.go
@@ -144,8 +144,10 @@ func TestCreateIsolatedSession_MultiOverlayAllocation(t *testing.T) {
}
}
-func TestCreateIsolatedSession_AllEphemeralOverlaysSkipUpperAllocation(t *testing.T) {
+func TestCreateIsolatedSession_AllEphemeralOverlaysStillOwnHostState(t *testing.T) {
runner := newTestRunner(t)
+ iso := &capturingIsolator{stubIsolator: *newStubIsolator()}
+ runner.isolator = iso
ephemeral := false
id, err := runner.CreateIsolatedSession(&IsolatedSessionOptions{
Overlays: []IsolatedOverlayOptions{
@@ -161,12 +163,95 @@ func TestCreateIsolatedSession_AllEphemeralOverlaysSkipUpperAllocation(t *testin
if session == nil {
t.Fatal("created session was not published")
}
- if session.upperID != "" {
- t.Errorf("ephemeral-only session allocated upper entry %q", session.upperID)
+ // Ephemeral overlays need no upper pairs, but the session still owns an
+ // upper-root subtree: it holds the /tmp backing dir and the durable
+ // cleanup record.
+ if session.upperID == "" {
+ t.Fatal("ephemeral-only session did not allocate its upper-root subtree")
}
if session.overlays[0].upperDir != "" {
t.Errorf("ephemeral overlay upper = %q, want empty", session.overlays[0].upperDir)
}
+
+ // Strict profile (default) hosts /tmp on a bind from that subtree.
+ if session.tmpDir != runner.upperMgr.TmpDir(session.upperID) {
+ t.Errorf("session.tmpDir = %q, want %q", session.tmpDir, runner.upperMgr.TmpDir(session.upperID))
+ }
+ if info, err := os.Stat(session.tmpDir); err != nil || !info.IsDir() {
+ t.Fatalf("/tmp backing dir missing: %v", err)
+ }
+ wrap, ok := iso.lastWrap()
+ if !ok {
+ t.Fatal("isolator did not receive WrapOptions")
+ }
+ if wrap.TmpDir != session.tmpDir {
+ t.Errorf("WrapOptions.TmpDir = %q, want %q", wrap.TmpDir, session.tmpDir)
+ }
+}
+
+func TestCreateIsolatedSession_TmpBindHostedShapes(t *testing.T) {
+ cases := []struct {
+ name string
+ profile string
+ overlays []IsolatedOverlayOptions
+ wantHosted bool
+ }{
+ {
+ name: "strict_ephemeral_hosts_tmp",
+ profile: string(isolation.ProfileStrict),
+ overlays: []IsolatedOverlayOptions{{Path: filepath.Join(t.TempDir(), "ws"), Mode: "rw"}},
+ wantHosted: true,
+ },
+ {
+ name: "balanced_keeps_shared_tmp",
+ profile: string(isolation.ProfileBalanced),
+ overlays: []IsolatedOverlayOptions{{Path: filepath.Join(t.TempDir(), "ws"), Mode: "rw"}},
+ wantHosted: false,
+ },
+ {
+ name: "overlay_on_tmp_suppresses_host_bind",
+ profile: string(isolation.ProfileStrict),
+ overlays: []IsolatedOverlayOptions{
+ {Path: filepath.Join(t.TempDir(), "ws"), Mode: "rw"},
+ {Path: "/tmp", Mode: "rw"},
+ },
+ wantHosted: false,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ runner := newTestRunner(t)
+ iso := &capturingIsolator{stubIsolator: *newStubIsolator()}
+ runner.isolator = iso
+ id, err := runner.CreateIsolatedSession(&IsolatedSessionOptions{
+ Profile: tc.profile,
+ Overlays: tc.overlays,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer runner.DeleteIsolatedSession(id)
+
+ session := runner.lookup(id)
+ if session == nil {
+ t.Fatal("created session was not published")
+ }
+ if tc.wantHosted && session.tmpDir == "" {
+ t.Fatal("strict session without /tmp overlay must host /tmp")
+ }
+ if !tc.wantHosted && session.tmpDir != "" {
+ t.Fatalf("session.tmpDir = %q, want empty", session.tmpDir)
+ }
+ wrap, ok := iso.lastWrap()
+ if !ok {
+ t.Fatal("isolator did not receive WrapOptions")
+ }
+ if wrap.TmpDir != session.tmpDir {
+ t.Errorf("WrapOptions.TmpDir = %q, want %q", wrap.TmpDir, session.tmpDir)
+ }
+ })
+ }
}
func TestNormalizeIsolatedOptions_MergesWorkspaceWithOverlays(t *testing.T) {
diff --git a/docs/guides/isolation-sessions.md b/docs/guides/isolation-sessions.md
index 573e1eb18..b373cae62 100644
--- a/docs/guides/isolation-sessions.md
+++ b/docs/guides/isolation-sessions.md
@@ -287,7 +287,7 @@ A session can carry **several independent overlay mounts** via the `overlays` re
- Each entry has its own mount semantics, so workspace files, system-level changes (`apt install` → `/usr`, config → `/etc`), and additional project directories get **independent copy-on-write uppers**.
- Mounts are applied shallow-first; a nested overlay (e.g. `/workspace` on top of a `/` root overlay) shadows its ancestors within its own subtree. Paths must be absolute and unique.
- `persist` (overlay mode only, default `true`): `true` allocates a host upper directory under `upper_root`; `false` uses an ephemeral tmpfs upper whose writes are discarded when the session ends. `rw`/`ro` entries must not set `persist`. An ephemeral upper lives inside the namespace only, so the files API serves `persist=false` overlays from their host-side content: in-session writes under such an overlay are not observable through the files API and files-API writes into it are rejected.
-- The files API routes each request to the session mount (overlay or bind) whose mount path is the longest prefix of the requested path; relative paths resolve against the first overlay. Paths outside every session mount — a `binds` destination that was not configured, a strict profile's private `/tmp`, `/etc`, ... — are rejected with an error instead of being silently resolved against the workspace.
+- The files API routes each request to the session mount (overlay or bind) whose mount path is the longest prefix of the requested path; relative paths resolve against the first overlay. Paths outside every session mount — a `binds` destination that was not configured, `/etc`, ... — are rejected with an error instead of being silently resolved against the workspace. The exception is the strict profile's private `/tmp`, which is host-backed and therefore served like any other session mount (see [Profiles and Defaults](#profiles-and-defaults)).
- Background runs use the **first** overlay for their log location: it must be `rw`, or `overlay` with `persist: true`; otherwise background runs are rejected.
---
@@ -326,9 +326,11 @@ The `profile` field currently controls only how `/tmp` is exposed inside the nam
| Profile | `/tmp` |
|---|---|
-| `strict` (default) | Private tmpfs (`--tmpfs /tmp`) |
+| `strict` (default) | Session-private tmpfs (`--tmpfs /tmp`) |
| `balanced` | Shared with the sandbox (`--bind /tmp /tmp`) |
+In the `strict` profile the private `/tmp` is backed by a host directory under the session's `upper_root` subtree, bind-mounted into the namespace, so `session.files` and `session.run` see the same `/tmp` content in both directions. The directory is created empty at session start, lives only as long as the session, and is removed with the rest of the session state on `DELETE` / idle collection. A `binds` entry or overlay sharing the `/tmp` destination still shadows it, exactly as inside the namespace. The `balanced` profile shares the sandbox's own `/tmp`, which stays outside the files API's mount view.
+
`workspace.mode` and `env_passthrough` are **independent** of the profile: when they are omitted, execd normalizes `workspace.mode` to `overlay` and `env_passthrough.mode` to `deny` regardless of which profile you pick. Set those fields explicitly if you want persistent workspace writes (`"rw"`) or host env passthrough (`"allow"`).
---
@@ -348,7 +350,7 @@ Private Sessions are not recoverable across an execd restart. Deployments that e
## Filesystem Proxy
-Reads and writes the session's **merged** mount view — the workspace overlays plus every `binds` destination — from outside the namespace. This is how SDKs `upload`, `download`, and `list` without spawning a shell, including against bind-mounted persistent data. The files API serves exactly those session mounts: absolute paths outside every mount (namespace-only locations such as a strict profile's private `/tmp`, or unconfigured `binds` destinations) are rejected with an error rather than resolving to a different file. All paths are per session under `/v1/isolated/session/{id}/`:
+Reads and writes the session's **merged** mount view — the workspace overlays plus every `binds` destination — from outside the namespace. This is how SDKs `upload`, `download`, and `list` without spawning a shell, including against bind-mounted persistent data. The files API serves exactly those session mounts: absolute paths outside every mount (namespace-only locations such as an unconfigured `binds` destination) are rejected with an error rather than resolving to a different file. The strict profile's private `/tmp` is host-backed and is part of the view (see [Profiles and Defaults](#profiles-and-defaults)). All paths are per session under `/v1/isolated/session/{id}/`:
| Method | Path |
|---|---|
diff --git a/sdks/sandbox/python/src/opensandbox/api/execd/api/isolated_execution/create_isolated_session.py b/sdks/sandbox/python/src/opensandbox/api/execd/api/isolated_execution/create_isolated_session.py
index cd06fbd6a..5f5dc83df 100644
--- a/sdks/sandbox/python/src/opensandbox/api/execd/api/isolated_execution/create_isolated_session.py
+++ b/sdks/sandbox/python/src/opensandbox/api/execd/api/isolated_execution/create_isolated_session.py
@@ -96,7 +96,9 @@ def sync_detailed(
overlay and bind mounts: paths under each mount resolve as the namespace sees them, and
absolute paths outside every overlay or bind are rejected instead of resolving against the
workspace (unlike binds, extra_writable paths are not served by the files API unless an
- overlay covers them).
+ overlay covers them). The strict profile's private `/tmp` is a session-owned bind under
+ the upper root and is part of that view; a caller bind or overlay on `/tmp` shadows it as
+ inside the namespace.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -132,7 +134,9 @@ def sync(
overlay and bind mounts: paths under each mount resolve as the namespace sees them, and
absolute paths outside every overlay or bind are rejected instead of resolving against the
workspace (unlike binds, extra_writable paths are not served by the files API unless an
- overlay covers them).
+ overlay covers them). The strict profile's private `/tmp` is a session-owned bind under
+ the upper root and is part of that view; a caller bind or overlay on `/tmp` shadows it as
+ inside the namespace.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -163,7 +167,9 @@ async def asyncio_detailed(
overlay and bind mounts: paths under each mount resolve as the namespace sees them, and
absolute paths outside every overlay or bind are rejected instead of resolving against the
workspace (unlike binds, extra_writable paths are not served by the files API unless an
- overlay covers them).
+ overlay covers them). The strict profile's private `/tmp` is a session-owned bind under
+ the upper root and is part of that view; a caller bind or overlay on `/tmp` shadows it as
+ inside the namespace.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
@@ -197,7 +203,9 @@ async def asyncio(
overlay and bind mounts: paths under each mount resolve as the namespace sees them, and
absolute paths outside every overlay or bind are rejected instead of resolving against the
workspace (unlike binds, extra_writable paths are not served by the files API unless an
- overlay covers them).
+ overlay covers them). The strict profile's private `/tmp` is a session-owned bind under
+ the upper root and is part of that view; a caller bind or overlay on `/tmp` shadows it as
+ inside the namespace.
Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
diff --git a/sdks/sandbox/python/src/opensandbox/api/execd/models/create_isolated_session_request.py b/sdks/sandbox/python/src/opensandbox/api/execd/models/create_isolated_session_request.py
index 944b2cb07..bb651194a 100644
--- a/sdks/sandbox/python/src/opensandbox/api/execd/models/create_isolated_session_request.py
+++ b/sdks/sandbox/python/src/opensandbox/api/execd/models/create_isolated_session_request.py
@@ -43,10 +43,13 @@ class CreateIsolatedSessionRequest:
present `workspace` is prepended to `overlays`. The session files API serves exactly the overlay and bind mounts:
paths under each mount resolve as the namespace sees them, and absolute paths outside every overlay or bind are
rejected instead of resolving against the workspace (unlike binds, extra_writable paths are not served by the files
- API unless an overlay covers them).
+ API unless an overlay covers them). The strict profile's private `/tmp` is a session-owned bind under the upper root
+ and is part of that view; a caller bind or overlay on `/tmp` shadows it as inside the namespace.
Attributes:
- profile (CreateIsolatedSessionRequestProfile | Unset):
+ profile (CreateIsolatedSessionRequestProfile | Unset): Isolation profile. `strict` (default) gives the session a
+ private `/tmp` backed by a host directory that the session files API also serves; `balanced` shares the
+ sandbox's own `/tmp`, which the files API does not serve.
workspace (IsolatedWorkspaceSpec | Unset):
overlays (list[IsolatedOverlaySpec] | Unset): Independent overlay mounts inside one namespace. Each entry gets
its own copy-on-write upper (or a direct/ro bind for rw/ro modes). bubblewrap applies mounts shallow-first, so a
diff --git a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/get_sandbox_network_policy.py b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/get_sandbox_network_policy.py
index 936d579df..04a10a6dd 100644
--- a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/get_sandbox_network_policy.py
+++ b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/get_sandbox_network_policy.py
@@ -63,6 +63,11 @@ def _parse_response(
return response_404
+ if response.status_code == 409:
+ response_409 = ErrorResponse.from_dict(response.json())
+
+ return response_409
+
if response.status_code == 500:
response_500 = ErrorResponse.from_dict(response.json())
@@ -97,11 +102,10 @@ def sync_detailed(
) -> Response[ErrorResponse | PolicyStatusResponse]:
"""Read sandbox network policy
- For Fsb, reads persisted egress Action Binding intent in the tenant's
- Sandbox CR, not live enforcement state. An absent binding defaults to
- deny-first when an egress handler is configured; this is not proof of
- enforcement on a pool without that handler. Other backends proxy the
- sandbox-side egress service. Requires lifecycle API authentication.
+ Fsb reads the egress-held policy record — the response reflects
+ exactly what the egress enforces, not the create-time binding input.
+ Other backends proxy the sandbox-side egress service. Requires
+ lifecycle API authentication.
Args:
sandbox_id (str):
@@ -132,11 +136,10 @@ def sync(
) -> ErrorResponse | PolicyStatusResponse | None:
"""Read sandbox network policy
- For Fsb, reads persisted egress Action Binding intent in the tenant's
- Sandbox CR, not live enforcement state. An absent binding defaults to
- deny-first when an egress handler is configured; this is not proof of
- enforcement on a pool without that handler. Other backends proxy the
- sandbox-side egress service. Requires lifecycle API authentication.
+ Fsb reads the egress-held policy record — the response reflects
+ exactly what the egress enforces, not the create-time binding input.
+ Other backends proxy the sandbox-side egress service. Requires
+ lifecycle API authentication.
Args:
sandbox_id (str):
@@ -162,11 +165,10 @@ async def asyncio_detailed(
) -> Response[ErrorResponse | PolicyStatusResponse]:
"""Read sandbox network policy
- For Fsb, reads persisted egress Action Binding intent in the tenant's
- Sandbox CR, not live enforcement state. An absent binding defaults to
- deny-first when an egress handler is configured; this is not proof of
- enforcement on a pool without that handler. Other backends proxy the
- sandbox-side egress service. Requires lifecycle API authentication.
+ Fsb reads the egress-held policy record — the response reflects
+ exactly what the egress enforces, not the create-time binding input.
+ Other backends proxy the sandbox-side egress service. Requires
+ lifecycle API authentication.
Args:
sandbox_id (str):
@@ -195,11 +197,10 @@ async def asyncio(
) -> ErrorResponse | PolicyStatusResponse | None:
"""Read sandbox network policy
- For Fsb, reads persisted egress Action Binding intent in the tenant's
- Sandbox CR, not live enforcement state. An absent binding defaults to
- deny-first when an egress handler is configured; this is not proof of
- enforcement on a pool without that handler. Other backends proxy the
- sandbox-side egress service. Requires lifecycle API authentication.
+ Fsb reads the egress-held policy record — the response reflects
+ exactly what the egress enforces, not the create-time binding input.
+ Other backends proxy the sandbox-side egress service. Requires
+ lifecycle API authentication.
Args:
sandbox_id (str):
diff --git a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/patch_sandbox_network_policy.py b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/patch_sandbox_network_policy.py
index 65b1131df..27c1465fd 100644
--- a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/patch_sandbox_network_policy.py
+++ b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/patch_sandbox_network_policy.py
@@ -126,9 +126,10 @@ def sync_detailed(
take priority over existing rules with the same target and replace
them in place; within one patch payload, the first rule for a target
wins; existing rules for other targets and the current defaultAction
- are preserved. Fsb commits the merged binding through FastPath with
- UID/generation conflict protection. Other backends proxy the
- sandbox-side egress service.
+ are preserved. Fsb composes the merge server-side (relay GET → merge
+ → relay PUT carrying the read revision) — a concurrent writer wins
+ and the stale merge is a 409. Other backends proxy the sandbox-side
+ egress service.
Args:
sandbox_id (str):
@@ -167,9 +168,10 @@ def sync(
take priority over existing rules with the same target and replace
them in place; within one patch payload, the first rule for a target
wins; existing rules for other targets and the current defaultAction
- are preserved. Fsb commits the merged binding through FastPath with
- UID/generation conflict protection. Other backends proxy the
- sandbox-side egress service.
+ are preserved. Fsb composes the merge server-side (relay GET → merge
+ → relay PUT carrying the read revision) — a concurrent writer wins
+ and the stale merge is a 409. Other backends proxy the sandbox-side
+ egress service.
Args:
sandbox_id (str):
@@ -203,9 +205,10 @@ async def asyncio_detailed(
take priority over existing rules with the same target and replace
them in place; within one patch payload, the first rule for a target
wins; existing rules for other targets and the current defaultAction
- are preserved. Fsb commits the merged binding through FastPath with
- UID/generation conflict protection. Other backends proxy the
- sandbox-side egress service.
+ are preserved. Fsb composes the merge server-side (relay GET → merge
+ → relay PUT carrying the read revision) — a concurrent writer wins
+ and the stale merge is a 409. Other backends proxy the sandbox-side
+ egress service.
Args:
sandbox_id (str):
@@ -242,9 +245,10 @@ async def asyncio(
take priority over existing rules with the same target and replace
them in place; within one patch payload, the first rule for a target
wins; existing rules for other targets and the current defaultAction
- are preserved. Fsb commits the merged binding through FastPath with
- UID/generation conflict protection. Other backends proxy the
- sandbox-side egress service.
+ are preserved. Fsb composes the merge server-side (relay GET → merge
+ → relay PUT carrying the read revision) — a concurrent writer wins
+ and the stale merge is a 409. Other backends proxy the sandbox-side
+ egress service.
Args:
sandbox_id (str):
diff --git a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/replace_sandbox_network_policy.py b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/replace_sandbox_network_policy.py
index a17705130..641906006 100644
--- a/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/replace_sandbox_network_policy.py
+++ b/sdks/sandbox/python/src/opensandbox/api/lifecycle/api/sandboxes/replace_sandbox_network_policy.py
@@ -119,9 +119,12 @@ def sync_detailed(
"""Replace the complete sandbox network policy
Replaces defaultAction and all rules, rather than merging them. Fsb
- commits the egress binding through FastPath, preserving unrelated bindings
- with UID/generation conflict protection. Success does not imply handler
- convergence. Other backends proxy the sandbox-side egress service.
+ relays the replacement to the egress-held policy record through the
+ FastPath handler relay — the ack means the egress applied it (and, with
+ policy persistence, that it is durable). The create-time binding input
+ is the bootstrap only; runtime changes never rewrite it, and a paused
+ (sealed) sandbox rejects mutations until resume. Other backends proxy
+ the sandbox-side egress service.
Args:
sandbox_id (str):
@@ -158,9 +161,12 @@ def sync(
"""Replace the complete sandbox network policy
Replaces defaultAction and all rules, rather than merging them. Fsb
- commits the egress binding through FastPath, preserving unrelated bindings
- with UID/generation conflict protection. Success does not imply handler
- convergence. Other backends proxy the sandbox-side egress service.
+ relays the replacement to the egress-held policy record through the
+ FastPath handler relay — the ack means the egress applied it (and, with
+ policy persistence, that it is durable). The create-time binding input
+ is the bootstrap only; runtime changes never rewrite it, and a paused
+ (sealed) sandbox rejects mutations until resume. Other backends proxy
+ the sandbox-side egress service.
Args:
sandbox_id (str):
@@ -192,9 +198,12 @@ async def asyncio_detailed(
"""Replace the complete sandbox network policy
Replaces defaultAction and all rules, rather than merging them. Fsb
- commits the egress binding through FastPath, preserving unrelated bindings
- with UID/generation conflict protection. Success does not imply handler
- convergence. Other backends proxy the sandbox-side egress service.
+ relays the replacement to the egress-held policy record through the
+ FastPath handler relay — the ack means the egress applied it (and, with
+ policy persistence, that it is durable). The create-time binding input
+ is the bootstrap only; runtime changes never rewrite it, and a paused
+ (sealed) sandbox rejects mutations until resume. Other backends proxy
+ the sandbox-side egress service.
Args:
sandbox_id (str):
@@ -229,9 +238,12 @@ async def asyncio(
"""Replace the complete sandbox network policy
Replaces defaultAction and all rules, rather than merging them. Fsb
- commits the egress binding through FastPath, preserving unrelated bindings
- with UID/generation conflict protection. Success does not imply handler
- convergence. Other backends proxy the sandbox-side egress service.
+ relays the replacement to the egress-held policy record through the
+ FastPath handler relay — the ack means the egress applied it (and, with
+ policy persistence, that it is durable). The create-time binding input
+ is the bootstrap only; runtime changes never rewrite it, and a paused
+ (sealed) sandbox rejects mutations until resume. Other backends proxy
+ the sandbox-side egress service.
Args:
sandbox_id (str):
diff --git a/specs/execd-api.yaml b/specs/execd-api.yaml
index f2236750a..27ed91da6 100644
--- a/specs/execd-api.yaml
+++ b/specs/execd-api.yaml
@@ -2967,11 +2967,19 @@ components:
them, and absolute paths outside every overlay or bind are
rejected instead of resolving against the workspace (unlike
binds, extra_writable paths are not served by the files API
- unless an overlay covers them).
+ unless an overlay covers them). The strict profile's private
+ `/tmp` is a session-owned bind under the upper root and is part
+ of that view; a caller bind or overlay on `/tmp` shadows it as
+ inside the namespace.
properties:
profile:
type: string
enum: ["strict", "balanced"]
+ description: >-
+ Isolation profile. `strict` (default) gives the session a private
+ `/tmp` backed by a host directory that the session files API also
+ serves; `balanced` shares the sandbox's own `/tmp`, which the
+ files API does not serve.
workspace:
$ref: "#/components/schemas/IsolatedWorkspaceSpec"
overlays: