Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(execd): serve binds mount points through the isolated session files API (#2299)
ephaa3c76f5049ae
diff --git a/components/execd/pkg/isolation/bind_view.go b/components/execd/pkg/isolation/bind_view.gonew file mode 100644index 000000000..4a44eb3ec--- /dev/null+++ b/components/execd/pkg/isolation/bind_view.go@@ -0,0 +1,256 @@+// 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.++package isolation++import (+ "fmt"+ "io"+ "io/fs"+ "os"+ "path/filepath"+ "sort"+ "strings"++ "github.com/alibaba/opensandbox/execd/pkg/vfs"+)++// BindView serves a bwrap bind mount's namespace paths directly from the+// bind's host source directory.+//+// Unlike MergedView, a bind is a live 1:1 mount with no copy-on-write+// layers, so the view has no overlay semantics: there are no whiteout+// conventions (a host file named ".wh.x" is a real file, exactly as the+// namespace sees it) and symlinked paths are followed (the kernel resolves+// them the same way for processes inside the namespace — bubblewrap bind+// mounts do not redirect symlink traversal). Read-only binds reject every+// mutation, matching --ro-bind.+//+// The bind source is an operator-allowlisted trusted host directory+// (validateBinds resolves symlinks and enforces allowed_writable before the+// session starts), so this view intentionally applies no per-path symlink+// policy of its own.+//+// Compile-time check: BindView satisfies vfs.FS.+var _ vfs.FS = (*BindView)(nil)++// BindView is a passthrough vfs.FS over a bind mount's host source.+type BindView struct {+ Source string+ ReadOnly bool+ // Uid/Gid own newly created files and directories, mirroring the+ // MergedView rw chown so in-namespace identities can access what the+ // files API creates.+ Uid, Gid uint32+}++// NewBindView creates a passthrough view over source.+func NewBindView(source string, readOnly bool, uid, gid uint32) *BindView {+ return &BindView{Source: source, ReadOnly: readOnly, Uid: uid, Gid: gid}+}++func (b *BindView) resolve(path string) (string, error) {+ cleaned := filepath.Clean(path)+ // Strip the source prefix so absolute namespace paths (which may arrive+ // with either the dest or the source prefix) resolve identically.+ if strings.HasPrefix(cleaned, b.Source+"/") {+ cleaned = strings.TrimPrefix(cleaned, b.Source+"/")+ } else if cleaned == b.Source {+ cleaned = "."+ }+ if strings.HasPrefix(cleaned, "..") {+ return "", fmt.Errorf("path traversal denied: %s", path)+ }+ return filepath.Join(b.Source, cleaned), nil+}++func (b *BindView) denyWrite(op string) error {+ return &os.PathError{Op: op, Path: b.Source, Err: fmt.Errorf("bind is read-only")}+}++func (b *BindView) Stat(path string) (os.FileInfo, error) {+ p, err := b.resolve(path)+ if err != nil {+ return nil, err+ }+ return os.Stat(p)+}++func (b *BindView) ReadFile(path string) ([]byte, error) {+ p, err := b.resolve(path)+ if err != nil {+ return nil, err+ }+ return os.ReadFile(p)+}++func (b *BindView) WriteFile(path string, data []byte, perm os.FileMode) error {+ if b.ReadOnly {+ return b.denyWrite("write")+ }+ p, err := b.resolve(path)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return err+ }+ if err := os.WriteFile(p, data, perm); err != nil {+ return err+ }+ return os.Chown(p, int(b.Uid), int(b.Gid))+}++func (b *BindView) WriteFileReader(path string, r io.Reader, perm os.FileMode) (int64, error) {+ if b.ReadOnly {+ return 0, b.denyWrite("write")+ }+ p, err := b.resolve(path)+ if err != nil {+ return 0, err+ }+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ return 0, err+ }+ f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)+ if err != nil {+ return 0, err+ }+ defer f.Close()+ n, err := io.Copy(f, r)+ if err != nil {+ return n, err+ }+ return n, os.Chown(p, int(b.Uid), int(b.Gid))+}++func (b *BindView) Remove(path string) error {+ if b.ReadOnly {+ return b.denyWrite("remove")+ }+ p, err := b.resolve(path)+ if err != nil {+ return err+ }+ return os.Remove(p)+}++func (b *BindView) RemoveAll(path string) error {+ if b.ReadOnly {+ return b.denyWrite("remove")+ }+ p, err := b.resolve(path)+ if err != nil {+ return err+ }+ return os.RemoveAll(p)+}++func (b *BindView) MkdirAll(path string, perm os.FileMode) error {+ if b.ReadOnly {+ return b.denyWrite("mkdir")+ }+ p, err := b.resolve(path)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(p, perm); err != nil {+ return err+ }+ return os.Chown(p, int(b.Uid), int(b.Gid))+}++func (b *BindView) Rename(oldPath, newPath string) error {+ if b.ReadOnly {+ return b.denyWrite("rename")+ }+ oldP, err := b.resolve(oldPath)+ if err != nil {+ return err+ }+ newP, err := b.resolve(newPath)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(newP), 0o755); err != nil {+ return err+ }+ return os.Rename(oldP, newP)+}++func (b *BindView) Chmod(path string, mode os.FileMode) error {+ if b.ReadOnly {+ return b.denyWrite("chmod")+ }+ p, err := b.resolve(path)+ if err != nil {+ return err+ }+ return os.Chmod(p, mode)+}++func (b *BindView) ReadDir(path string) ([]os.DirEntry, error) {+ p, err := b.resolve(path)+ if err != nil {+ return nil, err+ }+ return os.ReadDir(p)+}++func (b *BindView) Open(path string) (*os.File, error) {+ p, err := b.resolve(path)+ if err != nil {+ return nil, err+ }+ return os.Open(p)+}++// Search walks the source directory (no whiteout masking) and returns paths+// relative to the source root, matching MergedView.Search's convention; the+// router rebases rewritten-route results onto the namespace mount path.+func (b *BindView) Search(root, pattern string) ([]string, error) {+ rootP, err := b.resolve(root)+ if err != nil {+ return nil, err+ }++ var results []string+ _ = filepath.WalkDir(rootP, func(p string, d fs.DirEntry, err error) error {+ if err != nil {+ return nil //nolint:nilerr // skip unreadable dirs+ }+ if d.IsDir() {+ return nil+ }+ rel, relErr := filepath.Rel(b.Source, p)+ if relErr != nil {+ return nil //nolint:nilerr // skip paths outside the source+ }+ if matched, _ := filepath.Match(pattern, filepath.Base(rel)); matched {+ results = append(results, rel)+ }+ return nil+ })+ sort.Strings(results)+ return results, nil+}++func (b *BindView) ReplaceContent(path, old, newStr string) error {+ data, err := b.ReadFile(path)+ if err != nil {+ return err+ }+ content := strings.ReplaceAll(string(data), old, newStr)+ return b.WriteFile(path, []byte(content), 0o644) //nolint:gosec+}diff --git a/components/execd/pkg/isolation/merged_view_router.go b/components/execd/pkg/isolation/merged_view_router.goindex 0967fa62f..0fb13c001 100644--- a/components/execd/pkg/isolation/merged_view_router.go+++ b/components/execd/pkg/isolation/merged_view_router.go@@ -27,18 +27,22 @@ import ()// ErrPathOutsideOverlays is returned when a path does not fall under any-// registered overlay mount.-var ErrPathOutsideOverlays = errors.New("path is outside all overlay mounts")+// registered session mount (overlay or bind).+var ErrPathOutsideOverlays = errors.New("path is outside all session mounts")-// OverlayView binds one overlay mount path (the destination inside the-// namespace) to the view serving it.+// OverlayView binds one mount path (the destination inside the namespace)+// to the view serving it.type OverlayView struct {- // Path must equal the view's own root (for MergedView, its LowerDir):- // routing forwards the requested path unchanged, so a view rooted- // elsewhere would resolve paths outside its root instead of failing- // with ErrPathOutsideOverlays.+ // Path is the mount destination inside the namespace; routing matches+ // request paths against it by longest prefix.Path stringFS vfs.FS+ // Root is the path the view is actually rooted at when it differs from+ // Path — a bind view serves dest-prefixed namespace paths from the+ // bind's host source directory. Empty means Root == Path and request+ // paths are forwarded unchanged; otherwise the matched Path prefix is+ // stripped and Root is prepended before the operation is delegated.+ Root string// RelativeBase marks this view as the base for relative paths.// Single-workspace sessions treat relative paths as workspace-relative,// so callers with a workspace overlay mark its view; otherwise a /@@ -48,23 +52,26 @@ type OverlayView struct {RelativeBase bool}-// MultiMergedView routes filesystem operations to the overlay-scoped view+// MultiMergedView routes filesystem operations to the mount-scoped view// whose mount path is the longest prefix of the requested path. It lets one-// session expose several independent overlay mounts (workspace, system root,-// extra project directories) through a single vfs.FS.+// session expose several independent mounts (workspace, system root, extra+// project directories, bind mounts) through a single vfs.FS.//// Routing rules:-// - Absolute paths route to the longest matching overlay prefix, so-// /workspace/a resolves against the /workspace overlay even when a-// broader / root overlay is also registered. A view mounted at /+// - Absolute paths route to the longest matching mount prefix, so+// /workspace/a resolves against the /workspace mount even when a+// broader / root mount is also registered. A view mounted at /// matches every absolute path.+// - Equal-length prefixes keep registration order: register bind views+// before overlay views to mirror bwrap, where a later mount shadows+// earlier ones sharing a destination.// - Relative paths resolve against the view marked RelativeBase (the-// workspace view), falling back to the shallowest (root-most) overlay+// workspace view), falling back to the shallowest (root-most) mount// when none is marked — mirroring single-workspace behavior where// relative paths are workspace-relative.// - Rename is routed by both paths; a rename whose source and-// destination resolve to different overlays is rejected.-// - Paths outside every overlay return ErrPathOutsideOverlays.+// destination resolve to different mounts is rejected.+// - Paths outside every mount return ErrPathOutsideOverlays.type MultiMergedView struct {routes []overlayRoute // sorted by prefix length, longest firstrelativeBase vfs.FS@@ -72,14 +79,15 @@ type MultiMergedView struct {type overlayRoute struct {prefix string+ root string // view root; empty forwards paths unchangedfs vfs.FS}var _ vfs.FS = (*MultiMergedView)(nil)-// NewMultiMergedView builds a router from overlay views. Mount paths are+// NewMultiMergedView builds a router from mount views. Mount paths are// cleaned; non-absolute mount paths can never match an absolute request-// path and are dropped.+// path and are dropped, as are non-absolute view roots.func NewMultiMergedView(views []OverlayView) *MultiMergedView {routes := make([]overlayRoute, 0, len(views))var relativeBase vfs.FS@@ -91,7 +99,15 @@ func NewMultiMergedView(views []OverlayView) *MultiMergedView {if !filepath.IsAbs(prefix) {continue}- routes = append(routes, overlayRoute{prefix: prefix, fs: v.FS})+ route := overlayRoute{prefix: prefix, fs: v.FS}+ if v.Root != "" {+ root := filepath.Clean(v.Root)+ if !filepath.IsAbs(root) {+ continue+ }+ route.root = root+ }+ routes = append(routes, route)if v.RelativeBase {relativeBase = v.FS}@@ -122,137 +138,162 @@ func prefixDepth(p string) int {return strings.Count(p, "/")}-// route resolves the view serving path. Relative paths go to the view-// marked RelativeBase, or the shallowest registered overlay when none is.-func (m *MultiMergedView) route(path string) (vfs.FS, error) {+// route resolves the view serving path and returns the path rewritten to+// the view's own root. Relative paths go to the view marked RelativeBase,+// or the shallowest registered mount when none is.+func (m *MultiMergedView) route(path string) (*overlayRoute, string, error) {cleaned := filepath.Clean(path)if !filepath.IsAbs(cleaned) {if m.relativeBase == nil {- return nil, fmt.Errorf("%w: %s", ErrPathOutsideOverlays, path)+ return nil, "", fmt.Errorf("%w: %s", ErrPathOutsideOverlays, path)+ }+ // Relative paths only ever reach non-rewritten workspace views;+ // bind views are never marked RelativeBase.+ for i := range m.routes {+ if m.routes[i].fs == m.relativeBase {+ return &m.routes[i], cleaned, nil+ }}- return m.relativeBase, nil+ return &overlayRoute{fs: m.relativeBase}, cleaned, nil}- for _, r := range m.routes {+ for i := range m.routes {+ r := &m.routes[i]// r.prefix+"/" would be "//" for a "/" prefix, which no cleaned// absolute path starts with; match the root view directly.if cleaned == r.prefix || r.prefix == "/" ||strings.HasPrefix(cleaned, r.prefix+"/") {- return r.fs, nil+ if r.root == "" || r.root == r.prefix {+ return r, cleaned, nil+ }+ rel := strings.TrimPrefix(cleaned, r.prefix) // "" or "/suffix"+ return r, filepath.Join(r.root, rel), nil}}- return nil, fmt.Errorf("%w: %s", ErrPathOutsideOverlays, path)+ return nil, "", fmt.Errorf("%w: %s", ErrPathOutsideOverlays, path)}func (m *MultiMergedView) Stat(path string) (os.FileInfo, error) {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return nil, err}- return fs.Stat(path)+ return rt.fs.Stat(p)}func (m *MultiMergedView) ReadFile(path string) ([]byte, error) {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return nil, err}- return fs.ReadFile(path)+ return rt.fs.ReadFile(p)}func (m *MultiMergedView) WriteFile(path string, data []byte, perm os.FileMode) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.WriteFile(path, data, perm)+ return rt.fs.WriteFile(p, data, perm)}func (m *MultiMergedView) WriteFileReader(path string, r io.Reader, perm os.FileMode) (int64, error) {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return 0, err}- return fs.WriteFileReader(path, r, perm)+ return rt.fs.WriteFileReader(p, r, perm)}func (m *MultiMergedView) Remove(path string) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.Remove(path)+ return rt.fs.Remove(p)}func (m *MultiMergedView) RemoveAll(path string) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.RemoveAll(path)+ return rt.fs.RemoveAll(p)}func (m *MultiMergedView) MkdirAll(path string, perm os.FileMode) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.MkdirAll(path, perm)+ return rt.fs.MkdirAll(p, perm)}// Rename routes both paths and rejects a rename whose source and-// destination resolve to different overlays: delegating to the source view+// destination resolve to different mounts: delegating to the source view// would silently place the destination inside that view's upper.func (m *MultiMergedView) Rename(oldPath, newPath string) error {- fs, err := m.route(oldPath)+ rt, oldP, err := m.route(oldPath)if err != nil {return err}- dstFS, err := m.route(newPath)+ dstRT, newP, err := m.route(newPath)if err != nil {return err}- if dstFS != fs {- return fmt.Errorf("rename across overlays is not supported: %s -> %s", oldPath, newPath)+ if dstRT.fs != rt.fs {+ return fmt.Errorf("rename across mounts is not supported: %s -> %s", oldPath, newPath)}- return fs.Rename(oldPath, newPath)+ return rt.fs.Rename(oldP, newP)}func (m *MultiMergedView) Chmod(path string, mode os.FileMode) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.Chmod(path, mode)+ return rt.fs.Chmod(p, mode)}func (m *MultiMergedView) ReadDir(path string) ([]os.DirEntry, error) {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return nil, err}- return fs.ReadDir(path)+ return rt.fs.ReadDir(p)}func (m *MultiMergedView) Open(path string) (*os.File, error) {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return nil, err}- return fs.Open(path)+ return rt.fs.Open(p)}+// Search routes by the search root. Views with a rewritten root (binds)+// return paths relative to that root, so results are rebased onto the+// namespace mount path and follow-up Stat/Open calls route back to the+// same view instead of falling to the workspace relative base.func (m *MultiMergedView) Search(root, pattern string) ([]string, error) {- fs, err := m.route(root)+ rt, p, err := m.route(root)if err != nil {return nil, err}- return fs.Search(root, pattern)+ results, err := rt.fs.Search(p, pattern)+ if err != nil || rt.root == "" || rt.root == rt.prefix {+ return results, err+ }+ rebased := make([]string, 0, len(results))+ for _, rel := range results {+ rebased = append(rebased, filepath.Join(rt.prefix, rel))+ }+ return rebased, nil}func (m *MultiMergedView) ReplaceContent(path, old, newStr string) error {- fs, err := m.route(path)+ rt, p, err := m.route(path)if err != nil {return err}- return fs.ReplaceContent(path, old, newStr)+ return rt.fs.ReplaceContent(p, old, newStr)}diff --git a/components/execd/pkg/isolation/merged_view_router_test.go b/components/execd/pkg/isolation/merged_view_router_test.goindex 4b3ec76aa..1fcd21098 100644--- a/components/execd/pkg/isolation/merged_view_router_test.go+++ b/components/execd/pkg/isolation/merged_view_router_test.go@@ -269,7 +269,186 @@ func TestMultiMergedView_RenameRouting(t *testing.T) {t.Run("cross_overlay_rename_rejected", func(t *testing.T) {err := router.Rename("/workspace/a", "/data/b")require.Error(t, err)- assert.Contains(t, err.Error(), "rename across overlays is not supported")+ assert.Contains(t, err.Error(), "rename across mounts is not supported")assert.Empty(t, dataFS.renameArgs, "the destination view must not receive a cross-overlay rename")})}++// newBindRouterFixture builds a workspace overlay at <tmp>/ws plus two binds+// whose view roots differ from their mount paths:+//+// <tmp>/ws → overlay (lower + upper), routed by /ws+// <tmp>/bind-rw → rw bind source, routed by /data+// <tmp>/bind-ro → ro bind source, routed by /configs+func newBindRouterFixture(t *testing.T) (*MultiMergedView, string) {+ t.Helper()++ base, err := filepath.EvalSymlinks(t.TempDir())+ require.NoError(t, err)+ wsLower := filepath.Join(base, "ws")+ wsUpper := filepath.Join(base, "upper-ws")+ rwSrc := filepath.Join(base, "bind-rw")+ roSrc := filepath.Join(base, "bind-ro")++ for _, d := range []string{wsLower, wsUpper, rwSrc, roSrc} {+ require.NoError(t, os.MkdirAll(d, 0o755))+ }++ uid := uint32(os.Getuid())+ gid := uint32(os.Getgid())+ router := NewMultiMergedView([]OverlayView{+ {+ Path: "/data",+ Root: rwSrc,+ FS: NewBindView(rwSrc, false, uid, gid),+ },+ {+ Path: "/configs",+ Root: roSrc,+ FS: NewBindView(roSrc, true, uid, gid),+ },+ {+ Path: wsLower,+ FS: NewMergedView(wsLower, wsUpper, WorkspaceOverlay, uid, gid),+ RelativeBase: true,+ },+ })+ return router, base+}++func TestMultiMergedView_RewrittenRootRouting(t *testing.T) {+ router, base := newBindRouterFixture(t)+ rwSrc := filepath.Join(base, "bind-rw")+ roSrc := filepath.Join(base, "bind-ro")++ require.NoError(t, os.WriteFile(filepath.Join(rwSrc, "seed.txt"), []byte("seed"), 0o644))+ require.NoError(t, os.WriteFile(filepath.Join(roSrc, "ro.txt"), []byte("ro"), 0o644))++ t.Run("read_via_mount_path_serves_view_root", func(t *testing.T) {+ data, err := router.ReadFile("/data/seed.txt")+ require.NoError(t, err)+ assert.Equal(t, "seed", string(data))+ })++ t.Run("write_via_mount_path_lands_in_view_root", func(t *testing.T) {+ require.NoError(t, router.WriteFile("/data/api.txt", []byte("api"), 0o644))+ data, err := os.ReadFile(filepath.Join(rwSrc, "api.txt"))+ require.NoError(t, err)+ assert.Equal(t, "api", string(data))+ })++ t.Run("stat_and_readdir_follow_rewrite", func(t *testing.T) {+ info, err := router.Stat("/data/seed.txt")+ require.NoError(t, err)+ assert.False(t, info.IsDir())++ entries, err := router.ReadDir("/configs")+ require.NoError(t, err)+ names := make([]string, 0, len(entries))+ for _, e := range entries {+ names = append(names, e.Name())+ }+ assert.Contains(t, names, "ro.txt")+ })++ t.Run("ro_mode_semantics_survive_rewrite", func(t *testing.T) {+ data, err := router.ReadFile("/configs/ro.txt")+ require.NoError(t, err)+ assert.Equal(t, "ro", string(data))++ err = router.WriteFile("/configs/denied.txt", []byte("x"), 0o644)+ require.Error(t, err)+ assert.Contains(t, err.Error(), "read-only")+ })++ t.Run("search_results_rebase_onto_mount_path", func(t *testing.T) {+ require.NoError(t, os.MkdirAll(filepath.Join(rwSrc, "sub"), 0o755))+ require.NoError(t, os.WriteFile(filepath.Join(rwSrc, "sub", "deep.txt"), []byte("D"), 0o644))++ results, err := router.Search("/data", "**.txt")+ require.NoError(t, err)+ assert.Contains(t, results, "/data/seed.txt")+ assert.Contains(t, results, "/data/sub/deep.txt")++ // The rebased paths must Stat back onto the same view — this is what+ // the SearchFiles handler does per result.+ for _, p := range results {+ _, err := router.Stat(p)+ require.NoError(t, err, "rebased search result %s must stat", p)+ }+ })++ t.Run("bind_follows_symlinks_like_the_namespace", func(t *testing.T) {+ // A symlink inside the bind source resolves on the host, exactly as+ // the kernel resolves it for processes inside the namespace.+ target := filepath.Join(rwSrc, "real.txt")+ require.NoError(t, os.WriteFile(target, []byte("via-link"), 0o644))+ link := filepath.Join(rwSrc, "alias.txt")+ require.NoError(t, os.Symlink(target, link))++ data, err := router.ReadFile("/data/alias.txt")+ require.NoError(t, err)+ assert.Equal(t, "via-link", string(data))+ })++ t.Run("bind_has_no_whiteout_semantics", func(t *testing.T) {+ // ".wh."-prefixed files are real host files in a bind, not overlay+ // whiteout markers.+ require.NoError(t, os.WriteFile(filepath.Join(rwSrc, "plain.txt"), []byte("P"), 0o644))+ require.NoError(t, os.WriteFile(filepath.Join(rwSrc, ".wh.plain.txt"), []byte(""), 0o644))++ data, err := router.ReadFile("/data/plain.txt")+ require.NoError(t, err)+ assert.Equal(t, "P", string(data))++ data, err = router.ReadFile("/data/.wh.plain.txt")+ require.NoError(t, err, "whiteout-style names must stay readable in a bind")+ assert.Empty(t, string(data))+ })++ t.Run("nested_mount_prefix_wins_over_broader", func(t *testing.T) {+ // A bind dest nested under the workspace prefix routes to the bind,+ // not the workspace overlay (longest prefix, rewritten root or not).+ wsFS := &stubFS{name: "workspace"}+ nestedFS := &stubFS{name: "nested-bind"}+ nestedRouter := NewMultiMergedView([]OverlayView{+ {Path: "/ws/nested-bind", Root: "/bind-src", FS: nestedFS},+ {Path: "/ws", FS: wsFS},+ })+ data, err := nestedRouter.ReadFile("/ws/nested-bind/n.txt")+ require.NoError(t, err)+ assert.Equal(t, "nested-bind", string(data))++ data, err = nestedRouter.ReadFile("/ws/other.txt")+ require.NoError(t, err)+ assert.Equal(t, "workspace", string(data))+ })++ t.Run("path_outside_all_mounts_rejected", func(t *testing.T) {+ _, err := router.ReadFile("/etc/passwd")+ require.Error(t, err)+ assert.True(t, errors.Is(err, ErrPathOutsideOverlays))++ require.Error(t, router.WriteFile("/etc/evil", []byte("x"), 0o644))+ })++ t.Run("rewrite_preserves_relative_base", func(t *testing.T) {+ require.NoError(t, router.WriteFile("relative.txt", []byte("R"), 0o644))+ _, err := os.Stat(filepath.Join(base, "upper-ws", "relative.txt"))+ require.NoError(t, err, "relative write must resolve against the workspace overlay, not a bind root")+ })+}++func TestMultiMergedView_EqualPrefixInsertionOrderWins(t *testing.T) {+ // Binds register before overlays so equal-prefix ties mirror bwrap's+ // later-mount-wins shadowing.+ bindFS := &stubFS{name: "bind"}+ overlayFS := &stubFS{name: "overlay"}+ router := NewMultiMergedView([]OverlayView{+ {Path: "/shared", Root: "/bind-src", FS: bindFS},+ {Path: "/shared", FS: overlayFS},+ })+ data, err := router.ReadFile("/shared/x")+ require.NoError(t, err)+ assert.Equal(t, "bind", string(data))+}diff --git a/components/execd/pkg/runtime/bwrap_test/bwrap_binds_files_test.go b/components/execd/pkg/runtime/bwrap_test/bwrap_binds_files_test.gonew file mode 100644index 000000000..aebf33894--- /dev/null+++ b/components/execd/pkg/runtime/bwrap_test/bwrap_binds_files_test.go@@ -0,0 +1,270 @@+// 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 (+ "context"+ "errors"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/alibaba/opensandbox/execd/pkg/isolation"+ "github.com/alibaba/opensandbox/execd/pkg/runtime"+)++// newBindsSession creates a session with a rw workspace plus one bind and+// returns the runner, session id, and the bind source and dest directories.+// The bind source is pre-created so callers can seed host-side content.+func newBindsSession(t *testing.T, readOnly bool) (*runtime.IsolatedRunner, string, string, string) {+ t.Helper()++ srcDir := t.TempDir()+ destDir := t.TempDir()++ r := newRunner(t)+ opts := &runtime.IsolatedSessionOptions{+ Profile: "balanced",+ WorkspacePath: t.TempDir(),+ WorkspaceMode: "rw",+ Binds: []isolation.BindMount{+ {Source: srcDir, Dest: destDir, ReadOnly: readOnly},+ },+ }+ id, err := r.CreateIsolatedSession(opts)+ require.NoError(t, err)+ t.Cleanup(func() { _ = r.DeleteIsolatedSession(id) })+ return r, id, srcDir, destDir+}++func runInSession(t *testing.T, r *runtime.IsolatedRunner, id, code string, onStdout runtime.StdoutCallback) {+ t.Helper()+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ require.NoError(t, r.RunInIsolatedSession(ctx, id, code, nil, onStdout))+}++// TestBindsFiles_RunWriteVisibleViaFilesAPI is the reported scenario: a+// process inside the session writes into the bind dest with shell+// redirection, and the session files API must read the same data back+// through the bind dest path.+func TestBindsFiles_RunWriteVisibleViaFilesAPI(t *testing.T) {+ r, id, _, destDir := newBindsSession(t, false)++ runInSession(t, r, id, "echo run-data > "+destDir+"/run.txt", nil)++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)+ data, err := mv.ReadFile(filepath.Join(destDir, "run.txt"))+ require.NoError(t, err, "files API must read data written by run into the bind")+ assert.Equal(t, "run-data\n", string(data))+}++// TestBindsFiles_APIWriteVisibleToRun is the reverse direction: the files+// API writes through the bind dest, and a shell command inside the session+// observes it in the namespace.+func TestBindsFiles_APIWriteVisibleToRun(t *testing.T) {+ r, id, srcDir, destDir := newBindsSession(t, false)++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)+ require.NoError(t, mv.WriteFile(filepath.Join(destDir, "api.txt"), []byte("api-data"), 0o644))++ // Host side: the write must have gone to the bind source.+ host, err := os.ReadFile(filepath.Join(srcDir, "api.txt"))+ require.NoError(t, err)+ assert.Equal(t, "api-data", string(host))++ // Namespace side: run must see it at the bind dest.+ var lines []string+ runInSession(t, r, id, "cat "+destDir+"/api.txt", func(line string) { lines = append(lines, line) })+ assert.Equal(t, []string{"api-data"}, lines)+}++// TestBindsFiles_ReadAndListSeededSource covers read/list of host content+// seeded before session creation.+func TestBindsFiles_ReadAndListSeededSource(t *testing.T) {+ r, id, srcDir, destDir := newBindsSession(t, false)+ require.NoError(t, os.WriteFile(filepath.Join(srcDir, "seed.txt"), []byte("seeded"), 0o644))++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)++ data, err := mv.ReadFile(filepath.Join(destDir, "seed.txt"))+ require.NoError(t, err)+ assert.Equal(t, "seeded", string(data))++ entries, err := mv.ReadDir(destDir)+ require.NoError(t, err)+ names := make([]string, 0, len(entries))+ for _, e := range entries {+ names = append(names, e.Name())+ }+ assert.Contains(t, names, "seed.txt")++ // Shell agrees with the files API.+ var lines []string+ runInSession(t, r, id, "ls "+destDir, func(line string) { lines = append(lines, line) })+ assert.Contains(t, lines, "seed.txt")+}++// TestBindsFiles_ReadOnlyBind: ro binds are readable but every files-API+// mutation is denied, matching --ro-bind inside the namespace.+func TestBindsFiles_ReadOnlyBind(t *testing.T) {+ r, id, srcDir, destDir := newBindsSession(t, true)+ require.NoError(t, os.WriteFile(filepath.Join(srcDir, "ro.txt"), []byte("readonly"), 0o644))++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)++ data, err := mv.ReadFile(filepath.Join(destDir, "ro.txt"))+ require.NoError(t, err)+ assert.Equal(t, "readonly", string(data))++ err = mv.WriteFile(filepath.Join(destDir, "denied.txt"), []byte("x"), 0o644)+ require.Error(t, err, "files-API write to a read-only bind must be denied")+ assert.Contains(t, err.Error(), "read-only")++ // Shell cannot write either; the two views stay consistent.+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ err = r.RunInIsolatedSession(ctx, id, "echo x > "+destDir+"/denied.txt", nil, nil)+ require.Error(t, err, "shell write to a read-only bind must fail too")+ _, hostErr := os.Stat(filepath.Join(srcDir, "denied.txt"))+ assert.True(t, os.IsNotExist(hostErr), "ro bind must not gain files from either side")+}++// TestBindsFiles_PathOutsideMountsRejected: paths outside every overlay and+// bind keep failing with ErrPathOutsideOverlays.+func TestBindsFiles_PathOutsideMountsRejected(t *testing.T) {+ r, id, _, _ := newBindsSession(t, false)++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)++ _, err = mv.ReadFile("/etc/passwd")+ require.Error(t, err)+ assert.True(t, errors.Is(err, isolation.ErrPathOutsideOverlays))++ require.Error(t, mv.WriteFile("/etc/evil", []byte("x"), 0o644))+}++// TestBindsFiles_ReplaceAndDelete: content replacement and deletion through+// the bind dest land on the host source, in both views.+func TestBindsFiles_ReplaceAndDelete(t *testing.T) {+ r, id, srcDir, destDir := newBindsSession(t, false)+ require.NoError(t, os.WriteFile(filepath.Join(srcDir, "f.txt"), []byte("hello-world"), 0o644))++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)++ require.NoError(t, mv.ReplaceContent(filepath.Join(destDir, "f.txt"), "world", "files-api"))+ host, err := os.ReadFile(filepath.Join(srcDir, "f.txt"))+ require.NoError(t, err)+ assert.Equal(t, "hello-files-api", string(host))++ require.NoError(t, mv.Remove(filepath.Join(destDir, "f.txt")))+ _, err = os.Stat(filepath.Join(srcDir, "f.txt"))+ assert.True(t, os.IsNotExist(err), "files-API delete must remove the bind source file")+}++// TestBindsFiles_PassthroughSemantics: the bind view mirrors the namespace —+// symlinks resolve on the host and ".wh." names are real files, and search+// results come back in namespace space.+func TestBindsFiles_PassthroughSemantics(t *testing.T) {+ r, id, srcDir, destDir := newBindsSession(t, false)+ require.NoError(t, os.WriteFile(filepath.Join(srcDir, "plain.txt"), []byte("P"), 0o644))+ require.NoError(t, os.WriteFile(filepath.Join(srcDir, ".wh.plain.txt"), []byte(""), 0o644))+ require.NoError(t, os.Symlink(filepath.Join(srcDir, "plain.txt"), filepath.Join(srcDir, "alias.txt")))++ mv, err := r.GetMergedView(id)+ require.NoError(t, err)++ // The namespace follows the symlink; so must the files API.+ var lines []string+ runInSession(t, r, id, "cat "+destDir+"/alias.txt", func(line string) { lines = append(lines, line) })+ require.Equal(t, []string{"P"}, lines)+ data, err := mv.ReadFile(filepath.Join(destDir, "alias.txt"))+ require.NoError(t, err)+ assert.Equal(t, "P", string(data))++ // ".wh."-prefixed names are plain files through both views.+ runInSession(t, r, id, "cat "+destDir+"/.wh.plain.txt", nil)+ _, err = mv.ReadFile(filepath.Join(destDir, ".wh.plain.txt"))+ require.NoError(t, err)++ // Search rebases results onto the dest so follow-up stats route back.+ results, err := mv.Search(destDir, "**.txt")+ require.NoError(t, err)+ assert.Contains(t, results, filepath.Join(destDir, "plain.txt"))+ for _, p := range results {+ _, err := mv.Stat(p)+ require.NoError(t, err, "rebased search result %s must stat", p)+ }+}++// TestBindsFiles_OverlappingMountsRejected: create-time validation keeps the+// files view and the namespace in agreement for configs the router cannot+// represent.+func TestBindsFiles_OverlappingMountsRejected(t *testing.T) {+ r := newRunner(t)++ srcDir := t.TempDir()+ destDir := t.TempDir()+ wsDir := t.TempDir()+ _ = destDir++ t.Run("duplicate_bind_dests", func(t *testing.T) {+ _, err := r.CreateIsolatedSession(&runtime.IsolatedSessionOptions{+ Profile: "balanced",+ WorkspacePath: wsDir,+ WorkspaceMode: "rw",+ Binds: []isolation.BindMount{+ {Source: srcDir, Dest: "/mnt/x"},+ {Source: t.TempDir(), Dest: "/mnt/x"},+ },+ })+ require.Error(t, err)+ assert.Contains(t, err.Error(), "duplicate bind destination")+ })++ t.Run("bind_ancestor_of_workspace_rejected", func(t *testing.T) {+ _, err := r.CreateIsolatedSession(&runtime.IsolatedSessionOptions{+ Profile: "balanced",+ WorkspacePath: "/tmp/bwrap-ancestor-ws",+ WorkspaceMode: "rw",+ Binds: []isolation.BindMount{{Source: srcDir, Dest: "/tmp"}},+ })+ require.Error(t, err)+ assert.Contains(t, err.Error(), "shadows mount")+ })++ t.Run("bind_under_trusted_base_rejected", func(t *testing.T) {+ _, err := r.CreateIsolatedSession(&runtime.IsolatedSessionOptions{+ Profile: "balanced",+ WorkspacePath: wsDir,+ WorkspaceMode: "rw",+ Binds: []isolation.BindMount{{Source: srcDir, Dest: "/run/secrets"}},+ })+ require.Error(t, err)+ assert.Contains(t, err.Error(), "trusted base mount")+ })+}diff --git a/components/execd/pkg/runtime/isolated_session_binds_view_test.go b/components/execd/pkg/runtime/isolated_session_binds_view_test.gonew file mode 100644index 000000000..a334f1bc2--- /dev/null+++ b/components/execd/pkg/runtime/isolated_session_binds_view_test.go@@ -0,0 +1,414 @@+// Copyright 2026 The OpenSandbox Authors++//go:build !windows++// 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.++package runtime++import (+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/alibaba/opensandbox/execd/pkg/isolation"+)++// newBindsViewSession builds a synthetic session the way+// CreateIsolatedSession leaves one behind: resolved overlays (with upper+// directories for persisted overlay mode) and symlink-resolved bind sources.+func newBindsViewSession(+ t *testing.T,+ overlays []IsolatedOverlayOptions,+ uppers map[int]string,+ binds []isolation.BindMount,+) *isolatedSession {+ t.Helper()+ s := newIsolatedSession("binds-view", &IsolatedSessionOptions{+ Overlays: overlays,+ Binds: binds,+ }, newStubIsolator(), nil)+ for i, upper := range uppers {+ s.overlays[i].upperDir = upper+ }+ return s+}++func TestNewMergedView_BindRouting(t *testing.T) {+ // Resolve symlinks: MergedView rejects symlinked roots, and t.TempDir()+ // sits under a symlink on macOS.+ base, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ wsLower := filepath.Join(base, "ws")+ wsUpper := filepath.Join(base, "upper-ws")+ rwSrc := filepath.Join(base, "bind-src")+ roSrc := filepath.Join(base, "bind-ro-src")+ for _, dir := range []string{wsLower, wsUpper, rwSrc, roSrc} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ if err := os.WriteFile(filepath.Join(rwSrc, "seed.txt"), []byte("seed"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(roSrc, "ro.txt"), []byte("ro-value"), 0o644); err != nil {+ t.Fatal(err)+ }++ persist := true+ s := newBindsViewSession(t,+ []IsolatedOverlayOptions{{Path: wsLower, Mode: "overlay", Persist: &persist}},+ map[int]string{0: wsUpper},+ []isolation.BindMount{+ {Source: rwSrc, Dest: "/data"},+ {Source: roSrc, Dest: "/configs", ReadOnly: true},+ },+ )+ view := newMergedView(s)++ t.Run("read_via_dest_serves_source", func(t *testing.T) {+ data, err := view.ReadFile("/data/seed.txt")+ if err != nil || string(data) != "seed" {+ t.Fatalf("ReadFile /data/seed.txt = %q, %v", data, err)+ }+ })++ t.Run("write_via_dest_lands_in_source", func(t *testing.T) {+ if err := view.WriteFile("/data/api.txt", []byte("api"), 0o644); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(filepath.Join(rwSrc, "api.txt"))+ if err != nil || string(got) != "api" {+ t.Fatalf("bind write did not reach the host source: %v, %q", err, got)+ }+ })++ t.Run("readdir_via_dest_lists_source", func(t *testing.T) {+ entries, err := view.ReadDir("/data")+ if err != nil {+ t.Fatal(err)+ }+ names := make([]string, 0, len(entries))+ for _, e := range entries {+ names = append(names, e.Name())+ }+ for _, want := range []string{"seed.txt", "api.txt"} {+ found := false+ for _, n := range names {+ if n == want {+ found = true+ }+ }+ if !found {+ t.Fatalf("ReadDir /data missing %q, got %v", want, names)+ }+ }+ })++ t.Run("readonly_bind_rejects_writes", func(t *testing.T) {+ data, err := view.ReadFile("/configs/ro.txt")+ if err != nil || string(data) != "ro-value" {+ t.Fatalf("ReadFile /configs/ro.txt = %q, %v", data, err)+ }+ err = view.WriteFile("/configs/new.txt", []byte("x"), 0o644)+ if err == nil || !strings.Contains(err.Error(), "read-only") {+ t.Fatalf("write to ro bind = %v, want read-only denial", err)+ }+ })++ t.Run("path_outside_all_mounts_rejected", func(t *testing.T) {+ if _, err := view.Stat("/etc/hostname"); !errors.Is(err, isolation.ErrPathOutsideOverlays) {+ t.Fatalf("Stat /etc/hostname = %v, want ErrPathOutsideOverlays", err)+ }+ })++ t.Run("relative_paths_still_resolve_against_workspace", func(t *testing.T) {+ if err := view.WriteFile("relative.txt", []byte("rel"), 0o600); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(wsUpper, "relative.txt")); err != nil {+ t.Fatalf("relative write did not resolve against the workspace overlay: %v", err)+ }+ })++ t.Run("rename_within_bind_moves_source", func(t *testing.T) {+ if err := view.Rename("/data/seed.txt", "/data/renamed.txt"); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(rwSrc, "renamed.txt")); err != nil {+ t.Fatalf("renamed file missing in source: %v", err)+ }+ })++ t.Run("rename_across_mounts_rejected", func(t *testing.T) {+ err := view.Rename("/data/api.txt", filepath.Join(wsLower, "stolen.txt"))+ if err == nil || !strings.Contains(err.Error(), "rename across mounts") {+ t.Fatalf("rename bind→overlay = %v, want cross-mount rejection", err)+ }+ })+}++// TestNewMergedView_BindShadowsOverlayOnSameDest mirrors bwrap: binds are+// appended after overlay segments, so a bind sharing an overlay's dest+// shadows it inside the namespace — the files view must agree.+func TestNewMergedView_BindShadowsOverlayOnSameDest(t *testing.T) {+ base, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ shared := filepath.Join(base, "shared")+ upper := filepath.Join(base, "upper-shared")+ bindSrc := filepath.Join(base, "bind-src")+ for _, dir := range []string{shared, upper, bindSrc} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }++ s := newBindsViewSession(t,+ []IsolatedOverlayOptions{{Path: shared, Mode: "rw"}},+ nil,+ []isolation.BindMount{{Source: bindSrc, Dest: shared}},+ )+ view := newMergedView(s)++ if err := view.WriteFile(filepath.Join(shared, "who.txt"), []byte("bind"), 0o644); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(bindSrc, "who.txt")); err != nil {+ t.Fatalf("write went to the overlay instead of the shadowing bind: %v", err)+ }+ if _, err := os.Stat(filepath.Join(shared, "who.txt")); !os.IsNotExist(err) {+ t.Fatalf("write leaked into the overlay path: %v", err)+ }+}++// TestNewMergedView_BindDestDefaultsToSource covers the bwrap parity rule+// that an empty Dest binds source onto itself, and the files view follows.+func TestNewMergedView_BindDestDefaultsToSource(t *testing.T) {+ base, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ rwSrc := filepath.Join(base, "rw-src")+ wsLower := filepath.Join(base, "ws")+ for _, dir := range []string{rwSrc, wsLower} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }++ s := newBindsViewSession(t,+ []IsolatedOverlayOptions{{Path: wsLower, Mode: "rw"}},+ nil,+ []isolation.BindMount{{Source: rwSrc}},+ )+ view := newMergedView(s)++ if err := view.WriteFile(filepath.Join(rwSrc, "same.txt"), []byte("same"), 0o644); err != nil {+ t.Fatal(err)+ }+ got, err := os.ReadFile(filepath.Join(rwSrc, "same.txt"))+ if err != nil || string(got) != "same" {+ t.Fatalf("source==dest bind write broken: %v, %q", err, got)+ }+}++// TestNewMergedView_BindViewPassthroughSemantics pins the no-overlay+// semantics of bind views: symlinks resolve like the namespace, ".wh."+// names stay real files, and search results are rebased onto the dest.+func TestNewMergedView_BindViewPassthroughSemantics(t *testing.T) {+ base, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ wsLower := filepath.Join(base, "ws")+ rwSrc := filepath.Join(base, "bind-src")+ for _, dir := range []string{wsLower, rwSrc} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ }+ if err := os.WriteFile(filepath.Join(rwSrc, "plain.txt"), []byte("P"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(rwSrc, ".wh.plain.txt"), []byte(""), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(filepath.Join(rwSrc, "plain.txt"), filepath.Join(rwSrc, "alias.txt")); err != nil {+ t.Fatal(err)+ }++ persist := true+ s := newBindsViewSession(t,+ []IsolatedOverlayOptions{{Path: wsLower, Mode: "overlay", Persist: &persist}},+ nil,+ []isolation.BindMount{{Source: rwSrc, Dest: "/data"}},+ )+ view := newMergedView(s)++ // Symlinked entries read through, like `cat` inside the namespace.+ got, err := view.ReadFile("/data/alias.txt")+ if err != nil || string(got) != "P" {+ t.Fatalf("ReadFile through bind symlink = %q, %v", got, err)+ }++ // ".wh."-prefixed names are real files in a bind, not whiteouts.+ if got, err = view.ReadFile("/data/.wh.plain.txt"); err != nil {+ t.Fatalf("whiteout-style file must stay readable in a bind: %v", err)+ }+ if len(got) != 0 {+ t.Fatalf("unexpected content in .wh. file: %q", got)+ }++ // Search results must come back in namespace space so follow-up Stats+ // (as the SearchFiles handler performs) route to the bind, not the+ // workspace relative base.+ results, err := view.Search("/data", "**.txt")+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, p := range results {+ if p == "/data/plain.txt" {+ found = true+ }+ if _, err := view.Stat(p); err != nil {+ t.Fatalf("search result %s does not stat: %v", p, err)+ }+ }+ if !found {+ t.Fatalf("search results missing rebased /data/plain.txt: %v", results)+ }+}++// TestNewMergedView_BindsWithoutOverlaysDoesNotPanic guards the defensive+// branch: the RelativeBase index must not go out of range when a session+// somehow carries binds but no overlays (Create rejects this today).+func TestNewMergedView_BindsWithoutOverlaysDoesNotPanic(t *testing.T) {+ base, err := filepath.EvalSymlinks(t.TempDir())+ if err != nil {+ t.Fatal(err)+ }+ src := filepath.Join(base, "src")+ if err := os.MkdirAll(src, 0o755); err != nil {+ t.Fatal(err)+ }++ s := newBindsViewSession(t, nil, nil,+ []isolation.BindMount{{Source: src, Dest: "/data"}},+ )+ view := newMergedView(s)++ if err := view.WriteFile("/data/x.txt", []byte("x"), 0o644); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(src, "x.txt")); err != nil {+ t.Fatalf("bind write missing in source: %v", err)+ }+}++// TestValidateBindMountStack pins the mount-stack collisions the files view+// cannot represent: duplicates, ancestor binds, and trusted-base shadowing.+// Bind == overlay/extra_writable dest is allowed (the later bind shadows in+// both views).+func TestValidateBindMountStack(t *testing.T) {+ cases := []struct {+ name string+ overlays []IsolatedOverlayOptions+ extra []string+ binds []BindMountSpec+ wantFailure string+ }{+ {+ name: "bind equal to overlay dest is allowed",+ overlays: []IsolatedOverlayOptions{{Path: "/data"}},+ binds: []BindMountSpec{{source: "/a", dest: "/data"}},+ },+ {+ name: "bind inside overlay dest is allowed",+ overlays: []IsolatedOverlayOptions{{Path: "/data"}},+ binds: []BindMountSpec{{source: "/a", dest: "/data/proj"}},+ },+ {+ name: "bind equal to extra_writable is allowed",+ extra: []string{"/mnt/scratch"},+ binds: []BindMountSpec{{source: "/a", dest: "/mnt/scratch"}},+ },+ {+ name: "duplicate bind dests rejected",+ binds: []BindMountSpec{{source: "/a", dest: "/mnt/x"}, {source: "/b", dest: "/mnt/x"}},+ wantFailure: "duplicate bind destination",+ },+ {+ name: "bind ancestor of overlay rejected",+ overlays: []IsolatedOverlayOptions{{Path: "/data/proj"}},+ binds: []BindMountSpec{{source: "/a", dest: "/data"}},+ wantFailure: "shadows mount",+ },+ {+ name: "bind ancestor of extra_writable rejected",+ extra: []string{"/mnt/scratch/sub"},+ binds: []BindMountSpec{{source: "/a", dest: "/mnt/scratch"}},+ wantFailure: "shadows mount",+ },+ {+ name: "bind ancestor of another bind rejected",+ binds: []BindMountSpec{{source: "/a", dest: "/data"}, {source: "/b", dest: "/data/proj"}},+ wantFailure: "nested bind destinations",+ },+ {+ name: "bind under /run rejected",+ binds: []BindMountSpec{{source: "/a", dest: "/run/secrets"}},+ wantFailure: "trusted base mount",+ },+ {+ name: "bind at /dev rejected",+ binds: []BindMountSpec{{source: "/a", dest: "/dev"}},+ wantFailure: "trusted base mount",+ },+ {+ name: "unrelated bind and overlay allowed",+ overlays: []IsolatedOverlayOptions{{Path: "/workspace"}},+ binds: []BindMountSpec{{source: "/a", dest: "/mnt/data"}},+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ binds := make([]isolation.BindMount, 0, len(tc.binds))+ for _, b := range tc.binds {+ binds = append(binds, isolation.BindMount{Source: b.source, Dest: b.dest})+ }+ err := validateBindMountStack(tc.overlays, tc.extra, binds)+ if tc.wantFailure == "" {+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ return+ }+ if err == nil || !strings.Contains(err.Error(), tc.wantFailure) {+ t.Fatalf("error %v, want containing %q", err, tc.wantFailure)+ }+ })+ }+}++type BindMountSpec struct {+ source string+ dest string+}diff --git a/components/execd/pkg/runtime/isolated_session_ctrl.go b/components/execd/pkg/runtime/isolated_session_ctrl.goindex ac8a61ff1..8aaf706f1 100644--- a/components/execd/pkg/runtime/isolated_session_ctrl.go+++ b/components/execd/pkg/runtime/isolated_session_ctrl.go@@ -388,8 +388,8 @@ func (r *IsolatedRunner) CreateIsolatedSession(opts *IsolatedSessionOptions) (st// behavior.normalizeIsolatedOptions(opts)- if len(opts.Overlays) == 0 {- return "", fmt.Errorf("at least one overlay is required")+ if err := validateNormalizedCreate(opts); err != nil {+ return "", err}for _, ov := range opts.Overlays {@@ -906,15 +906,32 @@ func newMergedView(s *isolatedSession) vfs.FS {return isolation.NewMergedView(ov.path, upper, ov.mode, uid, gid)}- // Empty overlays yield an empty router rather than a panic.- if len(s.overlays) <= 1 {- if len(s.overlays) == 0 {- return isolation.NewMultiMergedView(nil)+ // bindView serves a bind's namespace dest paths from its host source+ // directory. BindView applies no overlay semantics: a bind is a live+ // 1:1 mount, so the view follows symlinks and keeps ".wh." files real,+ // exactly as the namespace sees them; ro mode rejects writes, matching+ // --ro-bind.+ bindView := func(b isolation.BindMount) isolation.OverlayView {+ dest := b.Dest+ if dest == "" {+ dest = b.Source}- return overlayView(s.overlays[0])+ return isolation.OverlayView{+ Path: dest,+ Root: b.Source,+ FS: isolation.NewBindView(b.Source, b.ReadOnly, uid, gid),+ }+ }++ // Register bind views before overlay views: bwrap applies caller mounts+ // in argv order (overlay segments first, binds last) and a later mount+ // shadows earlier ones sharing a destination, so binds must win+ // equal-prefix ties here too.+ views := make([]isolation.OverlayView, 0, len(s.overlays)+len(s.opts.Binds))+ for _, b := range s.opts.Binds {+ views = append(views, bindView(b))}- views := make([]isolation.OverlayView, 0, len(s.overlays))relativeBase := 0for i, ov := range s.overlays {if ov.path != "/" && s.overlays[relativeBase].path == "/" {@@ -922,12 +939,30 @@ func newMergedView(s *isolatedSession) vfs.FS {relativeBase = i}views = append(views, isolation.OverlayView{- Path: ov.path,- FS: overlayView(ov),- RelativeBase: false,+ Path: ov.path,+ FS: overlayView(ov),})}- views[relativeBase].RelativeBase = true++ // Without binds, preserve the historical view shapes (a bare MergedView+ // for the single-overlay session).+ if len(s.opts.Binds) == 0 {+ switch len(views) {+ case 0:+ return isolation.NewMultiMergedView(nil)+ case 1:+ return overlayView(s.overlays[0])+ }+ }++ // RelativeBase indexing below requires at least one overlay; Create+ // enforces that, but newMergedView must not panic if that invariant+ // ever changes.+ if len(s.overlays) == 0 {+ return isolation.NewMultiMergedView(views)+ }++ views[relativeBase+len(s.opts.Binds)].RelativeBase = truereturn isolation.NewMultiMergedView(views)}@@ -1067,6 +1102,102 @@ func (r *IsolatedRunner) pathAllowedResolved(resolved string) bool {return false}+// trustedBaseMounts are the bwrap mounts applied AFTER every caller-+// controlled mount (buildArgvWithLifecycle): a bind whose destination falls+// under one of them is shadowed inside the namespace, so the files view+// must not serve it either.+var trustedBaseMounts = []string{"/run", "/dev", "/proc"}++// validateNormalizedCreate checks the invariants that depend on the+// normalized options shape.+func validateNormalizedCreate(opts *IsolatedSessionOptions) error {+ if len(opts.Overlays) == 0 {+ return fmt.Errorf("at least one overlay is required")+ }+ // Keep the files view and the namespace in agreement: a bind whose+ // destination shadows (or is shadowed by) another caller mount would be+ // served by different host directories through session.run and+ // session.files, so reject the overlap up front.+ return validateBindMountStack(opts.Overlays, opts.ExtraWritable, opts.Binds)+}++// validateBindMountStack rejects bind destinations whose mount-stack+// visibility would disagree with the files view's longest-prefix routing:+//+// - duplicate bind destinations (bwrap exposes the last, the router the+// first),+// - a destination that is a strict ancestor of another mount (bwrap's+// later mount hides the earlier subtree; the router would pick the+// deeper mount),+// - a destination under the trusted base mounts (/run, /dev, /proc),+// which bwrap always mounts last.+//+// A bind destination exactly equal to an overlay or extra_writable path is+// allowed: the bind is applied later and wins in both the namespace and+// the files view.+func validateBindMountStack(+ overlays []IsolatedOverlayOptions,+ extraWritable []string,+ binds []isolation.BindMount,+) error {+ bindDests := make([]string, 0, len(binds))+ for _, b := range binds {+ dest := b.Dest+ if dest == "" {+ dest = b.Source+ }+ bindDests = append(bindDests, filepath.Clean(dest))+ }++ otherMounts := make([]string, 0, len(overlays)+len(extraWritable))+ for _, ov := range overlays {+ otherMounts = append(otherMounts, filepath.Clean(ov.Path))+ }+ for _, p := range extraWritable {+ otherMounts = append(otherMounts, filepath.Clean(p))+ }++ for i, dest := range bindDests {+ for j, other := range bindDests {+ if i == j {+ continue+ }+ if dest == other {+ return fmt.Errorf("binds dest %q: duplicate bind destination", dest)+ }+ if pathIsStrictAncestor(dest, other) {+ return fmt.Errorf(+ "binds dest %q shadows bind mount %q; nested bind destinations are not supported",+ dest, other,+ )+ }+ }+ for _, mount := range otherMounts {+ if pathIsStrictAncestor(dest, mount) {+ return fmt.Errorf(+ "binds dest %q shadows mount %q; ancestor bind destinations are not supported",+ dest, mount,+ )+ }+ }+ for _, base := range trustedBaseMounts {+ if dest == base || strings.HasPrefix(dest, base+"/") {+ return fmt.Errorf(+ "binds dest %q is shadowed by the trusted base mount %q",+ dest, base,+ )+ }+ }+ }+ return nil+}++// pathIsStrictAncestor reports whether ancestor is a proper path prefix of+// descendant (equal paths are not a strict ancestor relation).+func pathIsStrictAncestor(ancestor, descendant string) bool {+ return ancestor != descendant && strings.HasPrefix(descendant, ancestor+"/")+}+// resolveSymlinks returns the real path of p with symlinks resolved. Because p// (or a leading component) may not exist yet, it resolves the longest existing// prefix and re-appends the remaining components, so a symlinked ancestor isdiff --git a/docs/guides/isolation-sessions.md b/docs/guides/isolation-sessions.mdindex bffeab831..f0e353bb1 100644--- a/docs/guides/isolation-sessions.md+++ b/docs/guides/isolation-sessions.md@@ -279,7 +279,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 overlay whose mount path is the longest prefix of the requested path; relative paths resolve against the first overlay.+- 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.- Background runs use the **first** overlay for their log location: it must be `rw`, or `overlay` with `persist: true`; otherwise background runs are rejected.---@@ -302,6 +302,14 @@ A session can carry **several independent overlay mounts** via the `overlays` reEvery `source` is checked against the operator-configured `allowed_writable` allowlist **after** symlink resolution, so symlinks cannot escape it. Default allowlist: `/workspace`, `/mnt`, `/media`, `/data` (subpaths allowed). Empty allowlist rejects all extra binds.+Bind destinations are also served by the session files API: paths under `dest` resolve to the host `source` directory, so `session.files` and `session.run` see the same data in both directions (a bind is a live mount, unlike the overlay-mode upper). The bind view mirrors the namespace exactly: symlinked entries are followed (bubblewrap binds do not redirect symlink traversal) and `.wh.`-prefixed names are ordinary files, not overlay whiteouts. Writes through the files API are rejected for `readonly` binds, matching `--ro-bind` inside the namespace. When a bind shares a `dest` with an overlay or `extra_writable` path, the bind shadows it in both the namespace and the files view.++Destination constraints keep the two views in agreement; session creation rejects otherwise-valid-looking configs:++- **No duplicate `dest`** across `binds` entries (bwrap would expose only the last).+- **A `dest` must not be a strict ancestor** of another mount destination (`binds`, `overlays`, or `extra_writable`) — the later parent mount would hide that subtree in the namespace while the files API would still route into it.+- **A `dest` must not be `/run`, `/dev`, or `/proc`** (or nested under them) — the trusted base mounts are applied after every caller mount and always win.+---## Profiles and Defaults@@ -332,7 +340,7 @@ Private Sessions are not recoverable across an execd restart. Deployments that e## Filesystem Proxy-Reads and writes the session's **merged** workspace view from outside the namespace — this is how SDKs `upload`, `download`, and `list` without spawning a shell. 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. All paths are per session under `/v1/isolated/session/{id}/`:| Method | Path ||---|---|@@ -348,7 +356,7 @@ Reads and writes the session's **merged** workspace view from outside the namesp| `POST` | `directories` || `DELETE` | `directories?path=...` |-Writes on a `ro` workspace fail; writes on `overlay` land in the upper dir and vanish on `DELETE`.+Writes on a `ro` workspace fail; writes on `overlay` land in the upper dir and vanish on `DELETE`; writes on a `readonly` bind fail.---diff --git a/sdks/sandbox/javascript/src/api/execd.ts b/sdks/sandbox/javascript/src/api/execd.tsindex decee1bb9..a25147c07 100644--- a/sdks/sandbox/javascript/src/api/execd.ts+++ b/sdks/sandbox/javascript/src/api/execd.ts@@ -1641,7 +1641,7 @@ export interface components {/** @description 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 nested overlay (for example `/workspace` on top of a `/` root overlay) shadows its ancestors within its own subtree. Paths must be absolute, unique, and clean (no trailing slash, `.` or `..` segments); at most 16 mounts per session (including the legacy `workspace`). */overlays?: components["schemas"]["IsolatedOverlaySpec"][];extra_writable?: string[];- /** @description Additional host paths bind-mounted into the namespace with an explicit source-to-destination mapping. Unlike extra_writable (which mounts source==destination read-write), each entry may map a distinct destination path and be mounted read-only. The source path of every entry must fall within the configured writable allowlist. */+ /** @description Additional host paths bind-mounted into the namespace with an explicit source-to-destination mapping. Unlike extra_writable (which mounts source==destination read-write), each entry may map a distinct destination path and be mounted read-only. The source path of every entry must fall within the configured writable allowlist. The session files API also serves paths under each dest from the host source directory: reads and writes are live in both directions, symlinked entries are followed like the namespace view, and writes are rejected for readonly binds. Destinations must be unique across entries and must not be a strict ancestor of another mount destination (binds, overlays, extra_writable) or fall under /run, /dev, or /proc; such overlapping configurations are rejected at session creation. */binds?: components["schemas"]["BindMount"][];share_net?: boolean;env_passthrough?: components["schemas"]["EnvPassthroughSpec"];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.pyindex 55311f772..f6c1eee0e 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@@ -54,7 +54,11 @@ class CreateIsolatedSessionRequest:binds (list[BindMount] | Unset): Additional host paths bind-mounted into the namespace with an explicit source-to-destination mapping. Unlike extra_writable (which mounts source==destination read-write), each entry may mapa distinct destination path and be mounted read-only. The source path of every entry must fall within the- configured writable allowlist.+ configured writable allowlist. The session files API also serves paths under each dest from the host source+ directory: reads and writes are live in both directions, symlinked entries are followed like the namespace view,+ and writes are rejected for readonly binds. Destinations must be unique across entries and must not be a strict+ ancestor of another mount destination (binds, overlays, extra_writable) or fall under /run, /dev, or /proc; such+ overlapping configurations are rejected at session creation.share_net (bool | Unset):env_passthrough (EnvPassthroughSpec | Unset):uid (int | Unset):diff --git a/specs/execd-api.yaml b/specs/execd-api.yamlindex 8cd3a3ce6..ccdbca114 100644--- a/specs/execd-api.yaml+++ b/specs/execd-api.yaml@@ -2978,7 +2978,14 @@ components:(which mounts source==destination read-write), each entry may mapa distinct destination path and be mounted read-only. The sourcepath of every entry must fall within the configured writable- allowlist.+ allowlist. The session files API also serves paths under each+ dest from the host source directory: reads and writes are live+ in both directions, symlinked entries are followed like the+ namespace view, and writes are rejected for readonly binds.+ Destinations must be unique across entries and must not be a+ strict ancestor of another mount destination (binds, overlays,+ extra_writable) or fall under /run, /dev, or /proc; such+ overlapping configurations are rejected at session creation.items:$ref: "#/components/schemas/BindMount"share_net:diff --git a/tests/python/tests/test_isolated_session_e2e.py b/tests/python/tests/test_isolated_session_e2e.pyindex ee6e7f6b8..81ce9880c 100644--- a/tests/python/tests/test_isolated_session_e2e.py+++ b/tests/python/tests/test_isolated_session_e2e.py@@ -767,6 +767,96 @@ class TestIsolatedSessionE2E:await session.delete()await self.sandbox.commands.run(f"rm -rf {src_dir}")+ # ── Bind mount + files API tests (session.files on bind dests) ──────++ async def test_bind_files_api_read_write_roundtrip(self):+ """session.files reads/writes bind dests and stays consistent with+ session.run in both directions: the files API serves the same mounts+ the run namespace exposes."""+ ts = int(time.time() * 1000)+ src_dir = f"/data/bind_files_{ts}"+ dest = "/mnt/bind_files"++ await self.sandbox.commands.run(f"mkdir -p {src_dir} {dest}")++ session = await self.sandbox.isolation.create(+ CreateIsolatedSessionRequest(+ workspace=IsolatedWorkspaceSpec(path="/tmp", mode="rw"),+ binds=[BindMount(source=src_dir, dest=dest)],+ )+ )+ try:+ # files-API write → visible to run and on the host source.+ api_path = f"{dest}/from_files_api.txt"+ await session.files.write_files([+ WriteEntry(path=api_path, data="via-files-api", mode=644)+ ])+ via_run = await session.run(f"cat {api_path}")+ assert "via-files-api" in via_run.text+ host_check = await self.sandbox.commands.run(+ f"cat {src_dir}/from_files_api.txt"+ )+ assert "via-files-api" in host_check.text++ # run write → visible to the files API at the bind dest.+ await session.run(f"echo -n via-run > {dest}/from_run.txt")+ content = await session.files.read_file(+ f"{dest}/from_run.txt", encoding="utf-8"+ )+ assert content == "via-run"++ # host-side seed → readable through both views.+ await self.sandbox.commands.run(f"echo -n seeded > {src_dir}/seeded.txt")+ assert (+ await session.files.read_file(f"{dest}/seeded.txt", encoding="utf-8")+ == "seeded"+ )+ listed = await session.files.list_directory(+ DirectoryListEntry(path=dest, depth=1)+ )+ names = [e.path for e in listed]+ assert any("seeded.txt" in n for n in names)+ finally:+ await session.delete()+ await self.sandbox.commands.run(f"rm -rf {src_dir}")++ async def test_bind_files_api_readonly_write_rejected(self):+ """files-API writes to a readonly bind are rejected; reads work,+ matching --ro-bind inside the namespace."""+ ts = int(time.time() * 1000)+ src_dir = f"/data/bind_ro_files_{ts}"+ dest = "/mnt/bind_ro_files"++ await self.sandbox.commands.run(+ f"mkdir -p {src_dir} {dest} && echo -n ro-content > {src_dir}/host.txt"+ )++ session = await self.sandbox.isolation.create(+ CreateIsolatedSessionRequest(+ workspace=IsolatedWorkspaceSpec(path="/tmp", mode="rw"),+ binds=[BindMount(source=src_dir, dest=dest, readonly=True)],+ )+ )+ try:+ content = await session.files.read_file(+ f"{dest}/host.txt", encoding="utf-8"+ )+ assert content == "ro-content"++ with pytest.raises(SandboxApiException):+ await session.files.write_files([+ WriteEntry(path=f"{dest}/denied.txt", data="x", mode=644)+ ])++ # The namespace view must not have gained the file either.+ check = await self.sandbox.commands.run(+ f"test -e {src_dir}/denied.txt && echo EXISTS || echo ABSENT"+ )+ assert "ABSENT" in check.text+ finally:+ await session.delete()+ await self.sandbox.commands.run(f"rm -rf {src_dir}")+# ── Background run tests ─────────────────────────────────────────async def _wait_for_background_run(