Secure, Fast, and Extensible Sandbox runtime for AI agents.
fix(execd): probe private-net capability and fail fast share_net=false sessions (#2333)
ephad8a10505880f
diff --git a/components/execd/pkg/isolation/bwrap_linux.go b/components/execd/pkg/isolation/bwrap_linux.goindex 405c28bba..8fac576c4 100644--- a/components/execd/pkg/isolation/bwrap_linux.go+++ b/components/execd/pkg/isolation/bwrap_linux.go@@ -121,12 +121,19 @@ func (b *bwrapImpl) Available() bool {func (b *bwrapImpl) Capabilities() Capabilities {return Capabilities{+ // Available reuses the live check so the capabilities report can+ // never disagree with the create path's probed() gate: Available()+ // also validates the session gate file, which the probe alone does+ // not cover.Available: b.Available(),Isolator: b.probe.Isolator,Version: b.probe.Version,+ Message: b.probe.Message,SetprivAvailable: b.probe.SetprivAvailable,SetprivSwitchAvailable: b.probe.SetprivSwitchAvailable,+ SetprivNetAvailable: b.probe.SetprivNetAvailable,UsernsAvailable: b.probe.UsernsAvailable,+ UsernsNetAvailable: b.probe.UsernsNetAvailable,Profiles: []Profile{ProfileStrict, ProfileBalanced},ShareNetOverridable: true,CommitSupported: false, // Phase 2diff --git a/components/execd/pkg/isolation/isolator.go b/components/execd/pkg/isolation/isolator.goindex 518e4da0e..9579a7cec 100644--- a/components/execd/pkg/isolation/isolator.go+++ b/components/execd/pkg/isolation/isolator.go@@ -121,11 +121,19 @@ type Capabilities struct {Available boolIsolator stringVersion string+ Message stringSetprivAvailable bool// SetprivSwitchAvailable is used internally to reject a setpriv// request that selects IDs different from execd's own before side effects.SetprivSwitchAvailable boolUsernsAvailable bool+ // SetprivNetAvailable / UsernsNetAvailable report whether the uid mode+ // can also create the private network namespace required by share_net=+ // false (bwrap --unshare-net; its loopback setup needs CAP_NET_ADMIN in+ // the setpriv mode). Runtime rejects such requests with a named error+ // before starting bwrap when the mode's flag is false.+ SetprivNetAvailable bool+ UsernsNetAvailable boolProfiles []ProfileAllowedWorkspaces []stringAllowedExtraWritable []stringdiff --git a/components/execd/pkg/isolation/probe.go b/components/execd/pkg/isolation/probe.goindex e7d3f2f9b..30acbc4dd 100644--- a/components/execd/pkg/isolation/probe.go+++ b/components/execd/pkg/isolation/probe.go@@ -16,6 +16,7 @@ package isolationimport ("bytes"+ "context""fmt""os""os/exec"@@ -23,25 +24,38 @@ import ("regexp""strconv""strings"+ "time""github.com/alibaba/opensandbox/execd/pkg/log")+// bwrapSmokeTimeout bounds each smoke-test child so a bwrap wedged behind a+// restrictive LSM/seccomp policy cannot stall execd startup indefinitely.+const bwrapSmokeTimeout = 10 * time.Second+// ProbeResult holds the result of startup isolation probing.type ProbeResult struct {Available boolIsolator stringVersion string- Message string // diagnostic message when unavailable+ Message string // diagnostic message when unavailable or degradedSetprivAvailable bool // default setpriv uid mode can create the required namespaces// SetprivSwitchAvailable is an internal preflight capability for// requests that choose IDs different from the execd process IDs. The public// setpriv_available flag intentionally describes the default identity path.SetprivSwitchAvailable boolUsernsAvailable bool // userns uid mode can create the required namespaces- CommitSupported bool // Phase 2- DiffSupported bool // Phase 2- PersistAvailable bool // Phase 2 — requires emptyDir+ // SetprivNetAvailable / UsernsNetAvailable extend the uid-mode probes with+ // a private network namespace: share_net=false sessions run bwrap with+ // --unshare-net, whose loopback setup needs CAP_NET_ADMIN in the execd+ // container (setpriv) or succeeds inside the mode-owned user namespace+ // (userns). Sessions must fail fast on these instead of dying inside bwrap+ // with an opaque gate EOF.+ SetprivNetAvailable bool+ UsernsNetAvailable bool+ CommitSupported bool // Phase 2+ DiffSupported bool // Phase 2+ PersistAvailable bool // Phase 2 — requires emptyDir}// ProbeConfig controls Probe behaviour.@@ -76,21 +90,56 @@ func Probe(cfg ProbeConfig) ProbeResult {// Probe each uid mode independently. Some environments allow an// unprivileged user namespace but do not grant the capabilities required// by setpriv mode (or vice versa), so one failing mode must not disable the- // other.+ // other. Each mode is probed twice: once for the base namespaces and once+ // with the private network namespace added (share_net=false), because the+ // loopback setup has its own capability requirement.setprivErr := probeBwrapSetprivSmoke()setprivIdentitySwitchErr := setprivErrif setprivErr == nil {setprivIdentitySwitchErr = probeBwrapSetprivIdentitySwitchSmoke()}+ setprivNetErr := fmt.Errorf("setpriv uid mode unavailable entirely: %w", setprivErr)+ if setprivErr == nil {+ setprivNetErr = probeBwrapSetprivNetSmoke()+ }usernsErr := probeBwrapUsernsSmoke()- setBwrapModeAvailability(&result, setprivErr, setprivIdentitySwitchErr, usernsErr)+ usernsNetErr := fmt.Errorf("userns uid mode unavailable entirely: %w", usernsErr)+ if usernsErr == nil {+ usernsNetErr = probeBwrapUsernsNetSmoke()+ }+ setBwrapModeAvailability(+ &result,+ setprivErr,+ setprivIdentitySwitchErr,+ setprivNetErr,+ usernsErr,+ usernsNetErr,+ )if setprivErr != nil {log.Warn("isolation probe: setpriv uid mode unavailable: %v", setprivErr)} else if setprivIdentitySwitchErr != nil {log.Warn("isolation probe: setpriv uid mode cannot switch to arbitrary uid/gid: %v", setprivIdentitySwitchErr)}+ if setprivNetErr != nil && setprivErr == nil {+ log.Warn("isolation probe: setpriv uid mode cannot create a private network namespace (share_net=false): %v", setprivNetErr)+ }if usernsErr != nil {log.Warn("isolation probe: userns uid mode unavailable: %v", usernsErr)+ } else if usernsNetErr != nil {+ log.Warn("isolation probe: userns uid mode cannot create a private network namespace (share_net=false): %v", usernsNetErr)+ }+ // Isolation is up but private networking is broken in every mode: share_net=true+ // sessions still work, but the standard private-network session posture cannot+ // run here. Surface the reason so capabilities consumers and create failures+ // explain themselves instead of dying inside bwrap. The result.Available guard+ // keeps this degraded message from masking a total failure, which the+ // !result.Available branch below owns.+ if result.Available && !result.SetprivNetAvailable && !result.UsernsNetAvailable {+ result.Message = fmt.Sprintf(+ "private network namespace (share_net=false) is unavailable in every uid mode: setpriv: %v; userns: %v",+ setprivNetErr, usernsNetErr,+ )+ log.Warn("isolation probe: %s", result.Message)}if !result.Available {result.Message = fmt.Sprintf(@@ -109,10 +158,15 @@ func Probe(cfg ProbeConfig) ProbeResult {return result}-func setBwrapModeAvailability(result *ProbeResult, setprivErr, setprivIdentitySwitchErr, usernsErr error) {+func setBwrapModeAvailability(+ result *ProbeResult,+ setprivErr, setprivIdentitySwitchErr, setprivNetErr, usernsErr, usernsNetErr error,+) {result.SetprivAvailable = setprivErr == nilresult.SetprivSwitchAvailable = setprivErr == nil && setprivIdentitySwitchErr == nil+ result.SetprivNetAvailable = setprivErr == nil && setprivNetErr == nilresult.UsernsAvailable = usernsErr == nil+ result.UsernsNetAvailable = usernsErr == nil && usernsNetErr == nilresult.Available = result.SetprivAvailable || result.UsernsAvailable}@@ -150,7 +204,7 @@ func parseBwrapVersion(out string) string {// setpriv with its current IDs.func probeBwrapSetprivSmoke() error {uid, gid := currentProcessIDs()- return probeBwrapSmoke(UidModeSetpriv, uid, gid)+ return probeBwrapSmoke(UidModeSetpriv, false, uid, gid)}// probeBwrapSetprivIdentitySwitchSmoke verifies that setpriv can switch to IDs@@ -160,31 +214,69 @@ func probeBwrapSetprivSmoke() error {func probeBwrapSetprivIdentitySwitchSmoke() error {uid, gid := currentProcessIDs()uid, gid = setprivSmokeTargetIDs(uid, gid)- return probeBwrapSmoke(UidModeSetpriv, uid, gid)+ return probeBwrapSmoke(UidModeSetpriv, false, uid, gid)}// probeBwrapUsernsSmoke verifies bwrap can create the user namespace and apply// the uid/gid mapping used by the userns uid mode.func probeBwrapUsernsSmoke() error {uid, gid := currentProcessIDs()- return probeBwrapSmoke(UidModeUserns, uid, gid)+ return probeBwrapSmoke(UidModeUserns, false, uid, gid)}-func probeBwrapSmoke(mode UidMode, uid, gid uint32) error {+// probeBwrapSetprivNetSmoke verifies the setpriv path can also create the+// private network namespace required by share_net=false. bwrap's loopback+// setup needs CAP_NET_ADMIN in the execd container for this mode, so the+// probe keeps it separate from the base smoke: one failing must not hide the+// other.+func probeBwrapSetprivNetSmoke() error {+ uid, gid := currentProcessIDs()+ return probeBwrapSmoke(UidModeSetpriv, true, uid, gid)+}++// probeBwrapUsernsNetSmoke verifies the userns path can create the private+// network namespace. Inside a mode-owned user namespace the loopback setup+// uses the namespace's own capabilities, so this usually tracks+// probeBwrapUsernsSmoke; probing keeps the reported capability honest.+func probeBwrapUsernsNetSmoke() error {+ uid, gid := currentProcessIDs()+ return probeBwrapSmoke(UidModeUserns, true, uid, gid)+}++func probeBwrapSmoke(mode UidMode, privateNet bool, uid, gid uint32) error {p := findBwrap()if p == "" {return fmt.Errorf("bwrap not found")}- cmd := exec.Command(p, bwrapSmokeArgs(mode, isSetuidBinary(p), uid, gid)...)+ ctx, cancel := context.WithTimeout(context.Background(), bwrapSmokeTimeout)+ defer cancel()+ cmd := exec.CommandContext(ctx, p, bwrapSmokeArgs(mode, isSetuidBinary(p), privateNet, uid, gid)...)var stderr bytes.Buffercmd.Stderr = &stderrif err := cmd.Run(); err != nil {- return fmt.Errorf("bwrap %s smoke test failed: %w (stderr: %s)", mode, err, strings.TrimSpace(stderr.String()))+ err = fmt.Errorf("bwrap %s smoke test failed: %w (stderr: %s)", smokeLabel(mode, privateNet), err, strings.TrimSpace(stderr.String()))+ // bwrap dies on "loopback: Failed RTM_NEWADDR" when it cannot+ // configure 127.0.0.1 inside the new network namespace; name the+ // missing capability instead of leaving the raw stderr. Only the+ // setpriv mode needs CAP_NET_ADMIN in the execd container — in+ // userns mode the loopback setup runs with the namespace's own+ // capabilities, so this remediation would be wrong there.+ if mode == UidModeSetpriv && strings.Contains(stderr.String(), "loopback") {+ err = fmt.Errorf("%w (loopback setup requires CAP_NET_ADMIN in the execd container)", err)+ }+ return err}return nil}+func smokeLabel(mode UidMode, privateNet bool) string {+ if privateNet {+ return string(mode) + "+private-net"+ }+ return string(mode)+}+// setprivSmokeTargetIDs returns non-zero IDs different from the process IDs.// That makes the smoke test exercise the CAP_SETUID/CAP_SETGID path required// for arbitrary uid/gid requests instead of merely re-applying the current@@ -201,7 +293,10 @@ func setprivSmokeTargetIDs(currentUID, currentGID uint32) (uint32, uint32) {return targetUID, targetGID}-func bwrapSmokeArgs(mode UidMode, setuidBwrap bool, uid, gid uint32) []string {+// bwrapSmokeArgs mirrors the argv segments that real sessions emit for the+// given mode. privateNet adds --unshare-net, whose loopback setup is the+// capability most often missing in restricted containers (CAP_NET_ADMIN).+func bwrapSmokeArgs(mode UidMode, setuidBwrap, privateNet bool, uid, gid uint32) []string {var args []stringif mode == UidModeUserns {args = append(args, "--unshare-user")@@ -212,6 +307,9 @@ func bwrapSmokeArgs(mode UidMode, setuidBwrap bool, uid, gid uint32) []string {args = append(args,"--unshare-pid", "--unshare-uts", "--unshare-ipc", "--unshare-cgroup",)+ if privateNet {+ args = append(args, "--unshare-net")+ }if mode == UidModeUserns {args = append(args,"--uid", strconv.FormatUint(uint64(uid), 10),diff --git a/components/execd/pkg/isolation/probe_test.go b/components/execd/pkg/isolation/probe_test.goindex b17661c1c..071d790fb 100644--- a/components/execd/pkg/isolation/probe_test.go+++ b/components/execd/pkg/isolation/probe_test.go@@ -46,23 +46,61 @@ func TestSetBwrapModeAvailability(t *testing.T) {name stringsetprivErr erroridentityErr error+ setprivNetErr errorusernsErr error+ usernsNetErr errorwantAvailable boolwantSetpriv boolwantIdentity bool+ wantSetprivN boolwantUserns bool+ wantUsernsN bool}{- {name: "both available", wantAvailable: true, wantSetpriv: true, wantIdentity: true, wantUserns: true},- {name: "setpriv only", usernsErr: probeErr, wantAvailable: true, wantSetpriv: true, wantIdentity: true},- {name: "setpriv default only", identityErr: probeErr, usernsErr: probeErr, wantAvailable: true, wantSetpriv: true},- {name: "userns only", setprivErr: probeErr, wantAvailable: true, wantUserns: true},- {name: "neither available", setprivErr: probeErr, usernsErr: probeErr},+ {+ name: "all available",+ wantAvailable: true, wantSetpriv: true, wantIdentity: true,+ wantSetprivN: true, wantUserns: true, wantUsernsN: true,+ },+ {+ name: "setpriv only",+ usernsErr: probeErr, usernsNetErr: probeErr,+ wantAvailable: true, wantSetpriv: true, wantIdentity: true, wantSetprivN: true,+ },+ {+ name: "setpriv default only",+ identityErr: probeErr, usernsErr: probeErr, usernsNetErr: probeErr,+ // The identity-switch failure does not gate the independent+ // private-net smoke for the base setpriv path.+ wantAvailable: true, wantSetpriv: true, wantSetprivN: true,+ },+ {+ name: "userns only",+ setprivErr: probeErr, setprivNetErr: probeErr,+ wantAvailable: true, wantUserns: true, wantUsernsN: true,+ },+ {+ name: "neither available",+ setprivErr: probeErr, setprivNetErr: probeErr,+ usernsErr: probeErr, usernsNetErr: probeErr,+ },+ {+ name: "modes available without private net",+ setprivNetErr: probeErr, usernsNetErr: probeErr,+ wantAvailable: true, wantSetpriv: true, wantIdentity: true, wantUserns: true,+ },}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {result := ProbeResult{}- setBwrapModeAvailability(&result, tt.setprivErr, tt.identityErr, tt.usernsErr)+ setBwrapModeAvailability(+ &result,+ tt.setprivErr,+ tt.identityErr,+ tt.setprivNetErr,+ tt.usernsErr,+ tt.usernsNetErr,+ )if result.Available != tt.wantAvailable {t.Errorf("Available = %v, want %v", result.Available, tt.wantAvailable)}@@ -72,13 +110,37 @@ func TestSetBwrapModeAvailability(t *testing.T) {if result.SetprivSwitchAvailable != tt.wantIdentity {t.Errorf("SetprivSwitchAvailable = %v, want %v", result.SetprivSwitchAvailable, tt.wantIdentity)}+ if result.SetprivNetAvailable != tt.wantSetprivN {+ t.Errorf("SetprivNetAvailable = %v, want %v", result.SetprivNetAvailable, tt.wantSetprivN)+ }if result.UsernsAvailable != tt.wantUserns {t.Errorf("UsernsAvailable = %v, want %v", result.UsernsAvailable, tt.wantUserns)}+ if result.UsernsNetAvailable != tt.wantUsernsN {+ t.Errorf("UsernsNetAvailable = %v, want %v", result.UsernsNetAvailable, tt.wantUsernsN)+ }})}}+func TestSmokeLabel(t *testing.T) {+ tests := []struct {+ mode UidMode+ privateNet bool+ want string+ }{+ {UidModeSetpriv, false, "setpriv"},+ {UidModeSetpriv, true, "setpriv+private-net"},+ {UidModeUserns, false, "userns"},+ {UidModeUserns, true, "userns+private-net"},+ }+ for _, tt := range tests {+ if got := smokeLabel(tt.mode, tt.privateNet); got != tt.want {+ t.Errorf("smokeLabel(%q, %v) = %q, want %q", tt.mode, tt.privateNet, got, tt.want)+ }+ }+}+func TestSetprivSmokeTargetIDs(t *testing.T) {uid, gid := setprivSmokeTargetIDs(65534, 65534)if uid == 0 || uid == 65534 || gid == 0 || gid == 65534 {@@ -87,12 +149,12 @@ func TestSetprivSmokeTargetIDs(t *testing.T) {}func TestBwrapSmokeArgs(t *testing.T) {- rootSetprivArgs := bwrapSmokeArgs(UidModeSetpriv, false, 0, 0)+ rootSetprivArgs := bwrapSmokeArgs(UidModeSetpriv, false, false, 0, 0)if slices.Contains(rootSetprivArgs, "setpriv") {t.Errorf("root setpriv smoke args unexpectedly contain setpriv: %v", rootSetprivArgs)}- setprivArgs := bwrapSmokeArgs(UidModeSetpriv, false, 65534, 65533)+ setprivArgs := bwrapSmokeArgs(UidModeSetpriv, false, false, 65534, 65533)if slices.Contains(setprivArgs, "--unshare-user") {t.Errorf("setpriv smoke args unexpectedly contain --unshare-user: %v", setprivArgs)}@@ -102,7 +164,12 @@ func TestBwrapSmokeArgs(t *testing.T) {}}- usernsArgs := bwrapSmokeArgs(UidModeUserns, false, 1000, 1001)+ setprivNetArgs := bwrapSmokeArgs(UidModeSetpriv, false, true, 0, 0)+ if !slices.Contains(setprivNetArgs, "--unshare-net") {+ t.Errorf("setpriv private-net smoke args do not contain --unshare-net: %v", setprivNetArgs)+ }++ usernsArgs := bwrapSmokeArgs(UidModeUserns, false, false, 1000, 1001)for _, want := range []string{"--unshare-user", "--disable-userns", "--uid", "1000", "--gid", "1001"} {if !slices.Contains(usernsArgs, want) {t.Errorf("userns smoke args do not contain %q: %v", want, usernsArgs)@@ -112,7 +179,12 @@ func TestBwrapSmokeArgs(t *testing.T) {t.Errorf("userns smoke args unexpectedly contain setpriv: %v", usernsArgs)}- setuidUsernsArgs := bwrapSmokeArgs(UidModeUserns, true, 1000, 1001)+ usernsNetArgs := bwrapSmokeArgs(UidModeUserns, false, true, 1000, 1001)+ if !slices.Contains(usernsNetArgs, "--unshare-net") {+ t.Errorf("userns private-net smoke args do not contain --unshare-net: %v", usernsNetArgs)+ }++ setuidUsernsArgs := bwrapSmokeArgs(UidModeUserns, true, false, 1000, 1001)if slices.Contains(setuidUsernsArgs, "--disable-userns") {t.Errorf("setuid bwrap smoke args unexpectedly contain --disable-userns: %v", setuidUsernsArgs)}diff --git a/components/execd/pkg/runtime/errors.go b/components/execd/pkg/runtime/errors.goindex 375ab6500..adee078b5 100644--- a/components/execd/pkg/runtime/errors.go+++ b/components/execd/pkg/runtime/errors.go@@ -22,6 +22,14 @@ var ErrContextNotFound = errors.New("context not found")// not pass the startup capability probe in the current environment.var ErrUidModeUnavailable = errors.New("requested uid mode is unavailable")+// ErrSessionPrivateNetUnavailable indicates that a share_net=false request+// could not be served because the requested uid mode cannot create the+// private network namespace (bwrap --unshare-net, whose loopback setup needs+// CAP_NET_ADMIN in the execd container). Create rejects such requests before+// starting bwrap so callers get a named error instead of an opaque workload+// gate failure.+var ErrSessionPrivateNetUnavailable = errors.New("requested private network namespace is unavailable")+// ErrSessionTeardownTimeout indicates that a session workload could not be// reaped within the bounded teardown window. The caller must retain ownership// and retry cleanup rather than treating deletion as successful.diff --git a/components/execd/pkg/runtime/isolated_session.go b/components/execd/pkg/runtime/isolated_session.goindex 6c278e0e7..f927b4f64 100644--- a/components/execd/pkg/runtime/isolated_session.go+++ b/components/execd/pkg/runtime/isolated_session.go@@ -23,10 +23,12 @@ import ("io""os""os/exec"+ "strings""sync""sync/atomic""syscall""time"+ "unicode/utf8""github.com/alibaba/opensandbox/execd/pkg/isolation""github.com/alibaba/opensandbox/execd/pkg/log"@@ -145,6 +147,16 @@ type isolatedSession struct {const isolatedSessionStartupTimeout = 10 * time.Second+const (+ // Startup evidence bounds: bwrap's stderr is merged into the session+ // stdout pipe and its exit code lands in the JSON status stream, but both+ // are otherwise lost when a failed startup tears the session down. The+ // limits keep failed-create handling fast and the reported evidence small.+ startupStderrTailBytes = 2 * 1024+ startupStderrReadTimeout = 250 * time.Millisecond+ startupEvidenceDrainTimeout = time.Second+)+var (isolatedSessionStopTimeout = 5 * time.SecondsignalSessionProcessGroup = func(pid int, signal syscall.Signal) error {@@ -676,12 +688,89 @@ func (s *isolatedSession) waitForOperations(timeout time.Duration) error {}func (s *isolatedSession) failStartup(startErr error) error {+ startErr = s.attachStartupEvidence(startErr)+ log.Error("isolated session startup failed: %v", startErr)if cleanupErr := s.stop(); cleanupErr != nil {return errors.Join(startErr, fmt.Errorf("clean up failed session startup: %w", cleanupErr))}return startErr}+// attachStartupEvidence augments a startup failure with bubblewrap's exit+// code and the stderr tail buffered in the session output pipe. bwrap writes+// its setup failures (loopback setup, mount and overlay errors, execvp+// failures) to stderr, which start() merges into the session stdout pipe;+// without this, teardown closes the pipe and aborts the status drain before+// anyone reads them, leaving workload-gate EOFs without root-cause evidence.+func (s *isolatedSession) attachStartupEvidence(startErr error) error {+ if s.cmd == nil || s.cmd.Process == nil {+ return startErr+ }+ var evidence []error+ if code, ok := s.workloadExitCode(); ok {+ evidence = append(evidence, fmt.Errorf("bwrap exit code %d", code))+ }+ if tail := s.readStartupStderrTail(); tail != "" {+ evidence = append(evidence, fmt.Errorf("session output tail (bwrap stderr merged): %s", tail))+ }+ if len(evidence) == 0 {+ return startErr+ }+ return errors.Join(append([]error{startErr}, evidence...)...)+}++// workloadExitCode waits briefly for bubblewrap's JSON status stream to+// finish and returns its reported exit code. Setup-stage deaths end the+// stream without an exit-code document, in which case ok is false; the stderr+// tail is the surviving evidence for those.+func (s *isolatedSession) workloadExitCode() (int, bool) {+ if s.lifecycle == nil {+ return 0, false+ }+ timer := time.NewTimer(startupEvidenceDrainTimeout)+ defer timer.Stop()+ select {+ case <-s.lifecycle.DrainDone():+ case <-timer.C:+ return 0, false+ }+ return s.lifecycle.ExitCode()+}++// readStartupStderrTail returns the buffered session output tail (bwrap's+// stderr is merged into it), bounded by a short read deadline so a still-+// writing child cannot stall startup failure handling.+func (s *isolatedSession) readStartupStderrTail() string {+ file, ok := s.stdout.(*os.File)+ if !ok {+ return ""+ }+ // Never leave a still-open session pipe with an expired deadline.+ defer func() { _ = file.SetReadDeadline(time.Time{}) }()+ if err := file.SetReadDeadline(time.Now().Add(startupStderrReadTimeout)); err != nil {+ return ""+ }+ var collected []byte+ buf := make([]byte, 512)+ for {+ n, err := file.Read(buf)+ collected = append(collected, buf[:n]...)+ // Keep only the tail so early output cannot evict the root-cause+ // lines at the end of the stream. Advance the head cut to a rune+ // boundary so truncation cannot split a multi-byte character.+ if excess := len(collected) - startupStderrTailBytes; excess > 0 {+ for excess < len(collected) && !utf8.RuneStart(collected[excess]) {+ excess+++ }+ collected = collected[excess:]+ }+ if err != nil {+ break+ }+ }+ return strings.TrimSpace(string(collected))+}+func closeCommandExtraFiles(cmd *exec.Cmd) {for _, file := range cmd.ExtraFiles {if file != nil {diff --git a/components/execd/pkg/runtime/isolated_session_ctrl.go b/components/execd/pkg/runtime/isolated_session_ctrl.goindex 18611dfc2..87ca637bf 100644--- a/components/execd/pkg/runtime/isolated_session_ctrl.go+++ b/components/execd/pkg/runtime/isolated_session_ctrl.go@@ -385,6 +385,13 @@ func (r *IsolatedRunner) CreateIsolatedSession(opts *IsolatedSessionOptions) (streturn "", err}+ // Reject private-network requests the environment cannot serve before any+ // side effect (workspace directories, upper allocation, bwrap start), so+ // callers see a named error instead of an opaque gate EOF.+ if err := r.validateShareNetAvailable(opts); err != nil {+ return "", err+ }+// Normalize empty/omitted fields to the effective config execd will// actually apply. GetIsolatedSession echoes s.opts on attach so a// stateless client can rebuild a handle from just the sessionId;@@ -409,30 +416,8 @@ func (r *IsolatedRunner) CreateIsolatedSession(opts *IsolatedSessionOptions) (stid := uuid.New().String()session := newIsolatedSession(id, opts, r.isolator, r.namespacePinner)- // Persist overlays get host upper/work pairs; ephemeral overlays use- // the bwrap tmpfs upper and need no allocation.- persistCount := 0- for _, ov := range session.overlays {- if ov.mode == isolation.WorkspaceOverlay && ov.persist {- persistCount++- }- }- if persistCount > 0 {- upperID, pairs, err := r.upperMgr.AllocateN(persistCount)- if err != nil {- return "", fmt.Errorf("allocate upper: %w", err)- }- session.upperID = upperID- next := 0- for i := range session.overlays {- ov := &session.overlays[i]- if ov.mode != isolation.WorkspaceOverlay || !ov.persist {- continue- }- ov.upperDir = pairs[next].UpperDir- ov.workDir = pairs[next].WorkDir- next++- }+ if err := r.allocateSessionUppers(session); err != nil {+ return "", err}if err := session.start(); err != nil {@@ -467,6 +452,37 @@ func (r *IsolatedRunner) CreateIsolatedSession(opts *IsolatedSessionOptions) (streturn id, nil}+// allocateSessionUppers assigns host upper/work pairs to a session's+// persistent overlays. Ephemeral overlays use the bwrap tmpfs upper and need+// no allocation.+func (r *IsolatedRunner) allocateSessionUppers(session *isolatedSession) error {+ persistCount := 0+ for _, ov := range session.overlays {+ if ov.mode == isolation.WorkspaceOverlay && ov.persist {+ persistCount+++ }+ }+ if persistCount == 0 {+ return nil+ }+ upperID, pairs, err := r.upperMgr.AllocateN(persistCount)+ if err != nil {+ return fmt.Errorf("allocate upper: %w", err)+ }+ session.upperID = upperID+ next := 0+ for i := range session.overlays {+ ov := &session.overlays[i]+ if ov.mode != isolation.WorkspaceOverlay || !ov.persist {+ continue+ }+ ov.upperDir = pairs[next].UpperDir+ ov.workDir = pairs[next].WorkDir+ next+++ }+ return nil+}+// overlaySummary renders resolved overlays for log lines.func overlaySummary(overlays []sessionOverlay) string {parts := make([]string, 0, len(overlays))@@ -1083,6 +1099,48 @@ func setprivIdentitySwitchRequired(opts *IsolatedSessionOptions, currentUID, curreturn targetUID != currentUID || targetGID != currentGID}+// validateShareNetAvailable rejects share_net=false requests whose uid mode+// cannot create the private network namespace. The probe runs the exact+// --unshare-net smoke per mode: in setpriv mode bwrap's loopback setup needs+// CAP_NET_ADMIN in the execd container, and without this gate such requests+// died inside bwrap with an opaque "workload gate EOF" after upper-directory+// allocation had already run. share_net=true and omitted share_net (legacy+// shared default) are not affected.+func (r *IsolatedRunner) validateShareNetAvailable(opts *IsolatedSessionOptions) error {+ if opts == nil || opts.ShareNet == nil || *opts.ShareNet {+ return nil+ }++ mode := isolation.UidModeSetpriv+ if opts.UidMode != "" {+ mode = isolation.UidMode(opts.UidMode)+ }++ var available bool+ switch mode {+ case isolation.UidModeSetpriv:+ available = r.isolator.Capabilities().SetprivNetAvailable+ case isolation.UidModeUserns:+ available = r.isolator.Capabilities().UsernsNetAvailable+ default:+ // Unknown modes keep start()'s existing rejection path.+ return nil+ }+ if available {+ return nil+ }++ err := fmt.Errorf(+ "%w: uid mode %s cannot create the private network namespace required by share_net=false",+ ErrSessionPrivateNetUnavailable,+ mode,+ )+ if message := r.isolator.Capabilities().Message; message != "" {+ err = fmt.Errorf("%w: %s", err, message)+ }+ return err+}+func (r *IsolatedRunner) lookup(id string) *isolatedSession {v, ok := r.ctrl.isolatedSessionMap.Load(id)if !ok {diff --git a/components/execd/pkg/runtime/isolated_session_lifecycle_test.go b/components/execd/pkg/runtime/isolated_session_lifecycle_test.goindex e153c487d..5eee1028b 100644--- a/components/execd/pkg/runtime/isolated_session_lifecycle_test.go+++ b/components/execd/pkg/runtime/isolated_session_lifecycle_test.go@@ -165,7 +165,9 @@ func (*lifecycleHarnessIsolator) Capabilities() isolation.Capabilities {Available: true,SetprivAvailable: true,SetprivSwitchAvailable: true,+ SetprivNetAvailable: true,UsernsAvailable: true,+ UsernsNetAvailable: true,}}diff --git a/components/execd/pkg/runtime/isolated_session_namespace_linux_integration_test.go b/components/execd/pkg/runtime/isolated_session_namespace_linux_integration_test.goindex a6caf489f..d9d799bcd 100644--- a/components/execd/pkg/runtime/isolated_session_namespace_linux_integration_test.go+++ b/components/execd/pkg/runtime/isolated_session_namespace_linux_integration_test.go@@ -68,10 +68,16 @@ func testPrivateSessionPinsNamespacesBeforeMarkReady(if !capabilities.SetprivAvailable {t.Skip("bwrap setpriv mode is unavailable")}+ if !capabilities.SetprivNetAvailable {+ t.Skip("bwrap setpriv mode cannot create a private network namespace")+ }case isolation.UidModeUserns:if !capabilities.UsernsAvailable {t.Skip("bwrap user namespace mode is unavailable")}+ if !capabilities.UsernsNetAvailable {+ t.Skip("bwrap userns mode cannot create a private network namespace")+ }default:t.Fatalf("unexpected uid mode %q", uidMode)}diff --git a/components/execd/pkg/runtime/isolated_session_private_net_test.go b/components/execd/pkg/runtime/isolated_session_private_net_test.gonew file mode 100644index 000000000..f547a1773--- /dev/null+++ b/components/execd/pkg/runtime/isolated_session_private_net_test.go@@ -0,0 +1,259 @@+// 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 !windows++package runtime++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "strings"+ "testing"++ "github.com/alibaba/opensandbox/execd/pkg/isolation"+)++func TestValidateShareNetAvailable(t *testing.T) {+ privateNet := false+ tests := []struct {+ name string+ opts *IsolatedSessionOptions+ caps isolation.Capabilities+ wantErr error+ }{+ {+ name: "shared net is never gated",+ opts: &IsolatedSessionOptions{},+ caps: isolation.Capabilities{},+ },+ {+ name: "omitted share_net keeps the legacy shared default",+ opts: &IsolatedSessionOptions{ShareNet: nil},+ caps: isolation.Capabilities{},+ },+ {+ name: "private net with capable setpriv mode",+ opts: &IsolatedSessionOptions{ShareNet: &privateNet},+ caps: isolation.Capabilities{SetprivNetAvailable: true},+ },+ {+ name: "private net with capable userns mode",+ opts: &IsolatedSessionOptions{ShareNet: &privateNet, UidMode: "userns"},+ caps: isolation.Capabilities{UsernsNetAvailable: true},+ },+ {+ name: "private net with default setpriv mode unavailable",+ opts: &IsolatedSessionOptions{ShareNet: &privateNet},+ caps: isolation.Capabilities{UsernsNetAvailable: true},+ wantErr: ErrSessionPrivateNetUnavailable,+ },+ {+ name: "private net with unavailable userns mode",+ opts: &IsolatedSessionOptions{ShareNet: &privateNet, UidMode: "userns"},+ caps: isolation.Capabilities{SetprivNetAvailable: true},+ wantErr: ErrSessionPrivateNetUnavailable,+ },+ {+ name: "unknown uid mode is deferred to start",+ opts: &IsolatedSessionOptions{ShareNet: &privateNet, UidMode: "bogus"},+ caps: isolation.Capabilities{},+ wantErr: nil,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ runner := &IsolatedRunner{isolator: &stubIsolator{caps: tt.caps}}+ err := runner.validateShareNetAvailable(tt.opts)+ if !errors.Is(err, tt.wantErr) {+ t.Fatalf("validateShareNetAvailable() error = %v, want %v", err, tt.wantErr)+ }+ if tt.wantErr != nil && !strings.Contains(err.Error(), "share_net=false") {+ t.Errorf("error %q does not explain the share_net=false requirement", err)+ }+ })+ }+}++// closedLifecycleStub is a WorkloadLifecycle whose status stream already+// reached its terminal state, optionally carrying an exit code.+type closedLifecycleStub struct {+ done chan struct{}+ code int+ hasCode bool+}++func newClosedLifecycleStub(code int, hasCode bool) *closedLifecycleStub {+ done := make(chan struct{})+ close(done)+ return &closedLifecycleStub{done: done, code: code, hasCode: hasCode}+}++func (*closedLifecycleStub) WaitForIdentity(+ context.Context,+) (isolation.WorkloadIdentity, error) {+ return isolation.WorkloadIdentity{}, errors.New("not implemented")+}++func (*closedLifecycleStub) MarkReady() error { return errors.New("not implemented") }+func (*closedLifecycleStub) Abort() {}+func (s *closedLifecycleStub) DrainDone() <-chan struct{} {+ return s.done+}+func (*closedLifecycleStub) DrainError() error { return nil }+func (s *closedLifecycleStub) ExitCode() (int, bool) {+ return s.code, s.hasCode+}+func (*closedLifecycleStub) Close() error { return nil }++// newEvidenceTestSession builds a session whose process already started and+// whose output pipe carries the given bytes (bwrap's stderr is merged into+// the session output). The channel state mirrors a reaped workload so+// failStartup teardown does not wait.+func newEvidenceTestSession(+ t *testing.T,+ pipeData []byte,+ closeWriter bool,+ lifecycle isolation.WorkloadLifecycle,+) *isolatedSession {+ t.Helper()++ cmd := exec.Command("true")+ if err := cmd.Start(); err != nil {+ t.Fatalf("start evidence probe process: %v", err)+ }+ t.Cleanup(func() { _ = cmd.Wait() })++ stdoutR, stdoutW, err := os.Pipe()+ if err != nil {+ t.Fatalf("create output pipe: %v", err)+ }+ t.Cleanup(func() { _ = stdoutR.Close() })+ if len(pipeData) > 0 {+ if _, err := stdoutW.Write(pipeData); err != nil {+ t.Fatalf("write evidence bytes: %v", err)+ }+ }+ if closeWriter {+ if err := stdoutW.Close(); err != nil {+ t.Fatalf("close output writer: %v", err)+ }+ } else {+ t.Cleanup(func() { _ = stdoutW.Close() })+ }++ processWaited := make(chan struct{})+ close(processWaited)+ doneCh := make(chan struct{})+ close(doneCh)+ return &isolatedSession{+ cmd: cmd,+ stdout: stdoutR,+ lifecycle: lifecycle,+ processWaited: processWaited,+ processExited: true,+ doneCh: doneCh,+ }+}++func TestFailStartupAttachesBwrapEvidence(t *testing.T) {+ lifecycle := newClosedLifecycleStub(1, true)+ session := newEvidenceTestSession(+ t,+ []byte("bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\n"),+ true,+ lifecycle,+ )++ startErr := errors.New(+ "start bwrap: wait for isolated workload identity: read native workload gate: EOF",+ )+ err := session.failStartup(startErr)++ if !errors.Is(err, startErr) {+ t.Fatalf("failStartup error %v does not wrap the original error", err)+ }+ if !strings.Contains(err.Error(), "bwrap exit code 1") {+ t.Errorf("error %q does not carry the bwrap exit code", err)+ }+ if !strings.Contains(err.Error(), "session output tail (bwrap stderr merged): bwrap: loopback: Failed RTM_NEWADDR") {+ t.Errorf("error %q does not carry the bwrap stderr tail", err)+ }+}++func TestFailStartupWithoutExitCodeKeepsStderrEvidence(t *testing.T) {+ // Setup-stage bwrap deaths end the status stream without an exit-code+ // document; the stderr tail must still be attached.+ lifecycle := newClosedLifecycleStub(0, false)+ session := newEvidenceTestSession(+ t,+ []byte("bwrap: Can't mount proc at /proc: Operation not permitted\n"),+ true,+ lifecycle,+ )++ startErr := errors.New(+ "start bwrap: wait for isolated workload identity: read native workload gate: EOF",+ )+ err := session.failStartup(startErr)++ if !errors.Is(err, startErr) {+ t.Fatalf("failStartup error %v does not wrap the original error", err)+ }+ if strings.Contains(err.Error(), "bwrap exit code") {+ t.Errorf("error %q unexpectedly carries an exit code", err)+ }+ if !strings.Contains(err.Error(), "session output tail (bwrap stderr merged): bwrap: Can't mount proc") {+ t.Errorf("error %q does not carry the bwrap stderr tail", err)+ }+}++func TestFailStartupKeepsOutputTailWhenLarge(t *testing.T) {+ // A gate-released workload may write more than the tail window before+ // dying; the evidence must keep the END of the stream (the root cause)+ // and drop the head instead of stopping at the first few kilobytes.+ lifecycle := newClosedLifecycleStub(0, false)+ headMarker := "first-line-must-be-dropped\n"+ rootCause := "bwrap: loopback: Failed RTM_NEWADDR: Operation not permitted\n"+ session := newEvidenceTestSession(t, []byte(headMarker+strings.Repeat("A", 4000)+"\n"+rootCause), true, lifecycle)++ err := session.failStartup(errors.New("start bwrap: wait for isolated workload identity: EOF"))++ if !strings.Contains(err.Error(), "session output tail (bwrap stderr merged)") {+ t.Errorf("error %q does not carry the session output tail", err)+ }+ if !strings.Contains(err.Error(), strings.TrimSpace(rootCause)) {+ t.Errorf("error %q does not keep the end of the output stream", err)+ }+ if strings.Contains(err.Error(), "first-line-must-be-dropped") {+ t.Errorf("error %q kept evicted head output instead of the tail", err)+ }+}++func TestFailStartupWithoutEvidenceReturnsOriginalError(t *testing.T) {+ lifecycle := newClosedLifecycleStub(0, false)+ // The writer stays open: the read must honor its short deadline and the+ // original error must pass through unchanged.+ session := newEvidenceTestSession(t, nil, false, lifecycle)++ startErr := errors.New("start bwrap: bwrap: binary not found")+ err := session.failStartup(startErr)++ if err.Error() != startErr.Error() {+ t.Fatalf("failStartup error = %q, want unchanged %q", err, startErr)+ }+}diff --git a/components/execd/pkg/runtime/isolated_session_test.go b/components/execd/pkg/runtime/isolated_session_test.goindex 7f0d6564d..b3823187e 100644--- a/components/execd/pkg/runtime/isolated_session_test.go+++ b/components/execd/pkg/runtime/isolated_session_test.go@@ -90,7 +90,9 @@ func newStubIsolator() *stubIsolator {Isolator: "stub",SetprivAvailable: true,SetprivSwitchAvailable: true,+ SetprivNetAvailable: true,UsernsAvailable: true,+ UsernsNetAvailable: true,CommitSupported: false,DiffSupported: false,},diff --git a/components/execd/pkg/web/controller/isolated_session.go b/components/execd/pkg/web/controller/isolated_session.goindex bf127a837..82f4be8ef 100644--- a/components/execd/pkg/web/controller/isolated_session.go+++ b/components/execd/pkg/web/controller/isolated_session.go@@ -125,7 +125,8 @@ func (c *IsolatedSessionController) Create() {}func classifyIsolatedCreateError(err error) (int, model.ErrorCode) {- if errors.Is(err, runtime.ErrUidModeUnavailable) {+ if errors.Is(err, runtime.ErrUidModeUnavailable) ||+ errors.Is(err, runtime.ErrSessionPrivateNetUnavailable) {return http.StatusServiceUnavailable, model.ErrorCodeNotSupported}if errors.Is(err, runtime.ErrSessionNamespaceUnavailable) ||@@ -522,21 +523,26 @@ func (c *IsolatedSessionController) Capabilities() {resp.Message = isolatedProbeResult.Messageresp.SetprivAvailable = isolatedProbeResult.SetprivAvailableresp.UsernsAvailable = isolatedProbeResult.UsernsAvailable+ resp.SetprivNetAvailable = isolatedProbeResult.SetprivNetAvailable+ resp.UsernsNetAvailable = isolatedProbeResult.UsernsNetAvailable}c.RespondSuccess(resp)return}caps := isolatedRunner.Capabilities()resp := model.CapabilitiesResponse{- Available: caps.Available,- Isolator: caps.Isolator,- Version: caps.Version,- SetprivAvailable: caps.SetprivAvailable,- UsernsAvailable: caps.UsernsAvailable,- CommitSupported: caps.CommitSupported,- DiffSupported: caps.DiffSupported,- Hardening: hardening,- RuntimeInit: runtimeInit,+ Available: caps.Available,+ Isolator: caps.Isolator,+ Version: caps.Version,+ Message: caps.Message,+ SetprivAvailable: caps.SetprivAvailable,+ UsernsAvailable: caps.UsernsAvailable,+ SetprivNetAvailable: caps.SetprivNetAvailable,+ UsernsNetAvailable: caps.UsernsNetAvailable,+ CommitSupported: caps.CommitSupported,+ DiffSupported: caps.DiffSupported,+ Hardening: hardening,+ RuntimeInit: runtimeInit,}// Probe results indicate overlay capability, not diff/commit implementation.// Diff and commit are Phase 2; do not advertise them as supported.diff --git a/components/execd/pkg/web/controller/isolated_session_controller_test.go b/components/execd/pkg/web/controller/isolated_session_controller_test.goindex 940a1a68a..3965318ea 100644--- a/components/execd/pkg/web/controller/isolated_session_controller_test.go+++ b/components/execd/pkg/web/controller/isolated_session_controller_test.go@@ -46,6 +46,21 @@ func TestClassifyIsolatedCreateError_UidModeUnavailable(t *testing.T) {}}+func TestClassifyIsolatedCreateError_PrivateNetUnavailable(t *testing.T) {+ status, code := classifyIsolatedCreateError(+ fmt.Errorf(+ "create session: %w: uid mode setpriv cannot create the private network namespace",+ runtime.ErrSessionPrivateNetUnavailable,+ ),+ )+ if status != http.StatusServiceUnavailable {+ t.Errorf("status = %d, want %d", status, http.StatusServiceUnavailable)+ }+ if code != model.ErrorCodeNotSupported {+ t.Errorf("code = %q, want %q", code, model.ErrorCodeNotSupported)+ }+}+func TestClassifyIsolatedCreateError_ServiceUnavailable(t *testing.T) {for _, target := range []error{runtime.ErrSessionNamespaceUnavailable,diff --git a/components/execd/pkg/web/model/isolated_session.go b/components/execd/pkg/web/model/isolated_session.goindex 819891060..885d31b6a 100644--- a/components/execd/pkg/web/model/isolated_session.go+++ b/components/execd/pkg/web/model/isolated_session.go@@ -258,14 +258,19 @@ type ListIsolatedSessionsResponse struct {// Capabilitiestype CapabilitiesResponse struct {- Available bool `json:"available"`- Isolator string `json:"isolator,omitempty"`- Version string `json:"version,omitempty"`- Message string `json:"message,omitempty"`- SetprivAvailable bool `json:"setpriv_available"`- UsernsAvailable bool `json:"userns_available"`- CommitSupported bool `json:"commit_supported"`- DiffSupported bool `json:"diff_supported"`- Hardening *HardeningStatus `json:"hardening,omitempty"`- RuntimeInit *RuntimeInitStatus `json:"runtimeInit,omitempty"`+ Available bool `json:"available"`+ Isolator string `json:"isolator,omitempty"`+ Version string `json:"version,omitempty"`+ Message string `json:"message,omitempty"`+ SetprivAvailable bool `json:"setpriv_available"`+ UsernsAvailable bool `json:"userns_available"`+ // Per-mode private network namespace availability (share_net=false).+ // execd rejects such create requests with a named error when the+ // requested mode's flag is false.+ SetprivNetAvailable bool `json:"setpriv_net_available"`+ UsernsNetAvailable bool `json:"userns_net_available"`+ CommitSupported bool `json:"commit_supported"`+ DiffSupported bool `json:"diff_supported"`+ Hardening *HardeningStatus `json:"hardening,omitempty"`+ RuntimeInit *RuntimeInitStatus `json:"runtimeInit,omitempty"`}diff --git a/docs/guides/isolation-sessions.md b/docs/guides/isolation-sessions.mdindex 10213fb88..573e1eb18 100644--- a/docs/guides/isolation-sessions.md+++ b/docs/guides/isolation-sessions.md@@ -338,7 +338,7 @@ The `profile` field currently controls only how `/tmp` is exposed inside the nam- **`env_passthrough`** — `mode: "allow"` + `keys` whitelists host env vars; default `deny`. Per-run overrides go in `IsolatedRunRequest.envs`.- **`uid` / `gid`** with **`uid_mode: "setpriv"`** (default, real setuid/setgid drop) or **`"userns"`** (user namespace remap). Check `setpriv_available` / `userns_available` from [`/capabilities`](#capabilities-and-probing) before requesting a mode.- **`share_net: true`** shares the sandbox's network namespace. Sandbox-level egress and Credential Vault policies still apply.-- **`share_net: false`** creates a private network namespace. Before releasing the workload startup gate, execd opens the authenticated NetNS, obtains its real owning UserNS with `NS_GET_USERNS`, and bind-pins both below `/run/execd/namespaces/<opaque-id>/`. Any validation or pin failure aborts Session creation. Execd attempts pin cleanup on failed startup, process exit, explicit delete, idle collection, and runner shutdown; retryable failures retain Session ownership and are retried while execd remains alive. This applies to both UID modes; hardened network backends will require `uid_mode: "userns"`.+- **`share_net: false`** creates a private network namespace. Check `setpriv_net_available` / `userns_net_available` from [`/capabilities`](#capabilities-and-probing) for the requested uid mode: execd rejects unsupported combinations up front with `503 NOT_SUPPORTED` instead of failing inside bubblewrap. Before releasing the workload startup gate, execd opens the authenticated NetNS, obtains its real owning UserNS with `NS_GET_USERNS`, and bind-pins both below `/run/execd/namespaces/<opaque-id>/`. Any validation or pin failure aborts Session creation. Execd attempts pin cleanup on failed startup, process exit, explicit delete, idle collection, and runner shutdown; retryable failures retain Session ownership and are retried while execd remains alive. This applies to both UID modes; hardened network backends will require `uid_mode: "userns"`.The legacy default remains unchanged in this phase: omitting `share_net` continues to share the sandbox network namespace. Namespace pinning alone does not enable Session egress or ingress.@@ -381,6 +381,8 @@ curl -s http://localhost:44772/v1/isolated/capabilities"version": "0.9.0","setpriv_available": true,"userns_available": false,+ "setpriv_net_available": true,+ "userns_net_available": false,"commit_supported": false,"diff_supported": false}@@ -388,6 +390,7 @@ curl -s http://localhost:44772/v1/isolated/capabilities- `available: false` — the trusted native workload gate is missing or untrusted, bubblewrap is missing, or the host can't create the required namespaces (missing `CAP_SYS_ADMIN`, restricted user-ns sysctl, etc.).- `setpriv_available` / `userns_available` — whether sessions with `uid_mode: "setpriv"` or `"userns"` can be created. `setpriv_available` reflects only execd's **default** UID/GID; a session that requests a different UID/GID may still return `503 NOT_SUPPORTED` when identity switching is unavailable.+- `setpriv_net_available` / `userns_net_available` — whether the uid mode can also create the private network namespace required by `share_net: false`. In setpriv mode bwrap's loopback setup needs `CAP_NET_ADMIN` in the execd container; userns mode owns its network namespace and usually tracks `userns_available`. When a request asks for `share_net: false` in a mode whose flag is false, execd rejects it up front with `503 NOT_SUPPORTED` and a diagnostic message instead of failing inside bubblewrap with an opaque workload-gate error.- `commit_supported` / `diff_supported` — Phase 2 stubs, currently return `503`.---@@ -420,7 +423,7 @@ Example: `components/execd/configs/isolation.example.toml`.Deleting an overlay session can restore admission once its cleanup succeeds and total usage falls below the threshold. Deletion discards that session's private upper data, so preserve any data you need before deleting it.-**Host requirements:** `bwrap` and the trusted native workload gate in the execd image; `CAP_SYS_ADMIN` (and `kernel.unprivileged_userns_clone=1` for `uid_mode: "userns"`); `overlayfs` in the kernel for `overlay` workspaces. The published image installs the gate automatically. Linux source builds must run `make build-session-gate` and then `sudo make install-session-gate` from `components/execd` before starting execd.+**Host requirements:** `bwrap` and the trusted native workload gate in the execd image; `CAP_SYS_ADMIN` (and `kernel.unprivileged_userns_clone=1` for `uid_mode: "userns"`); `CAP_NET_ADMIN` for `share_net: false` in `uid_mode: "setpriv"` (bwrap's loopback setup configures 127.0.0.1 inside the new network namespace); `overlayfs` in the kernel for `overlay` workspaces. The published image installs the gate automatically. Linux source builds must run `make build-session-gate` and then `sudo make install-session-gate` from `components/execd` before starting execd.Note: `/capabilities` reports `available: false` when the native workload gate cannot be opened as a trusted executable or when bwrap itself cannot be started (missing binary or missing namespace capabilities). A missing `overlayfs` does **not** flip `available` — the overlay probe only influences Phase 2 `commit`/`diff` support, and default overlay-mode session creation can still fail at runtime on such hosts. If you rely on `workspace.mode: "overlay"`, verify `overlayfs` support directly on the host.diff --git a/sdks/sandbox/javascript/src/api/execd.ts b/sdks/sandbox/javascript/src/api/execd.tsindex 549f2ac89..9a2d28fea 100644--- a/sdks/sandbox/javascript/src/api/execd.ts+++ b/sdks/sandbox/javascript/src/api/execd.ts@@ -1853,12 +1853,16 @@ export interface components {available?: boolean;isolator?: string;version?: string;- /** @description Diagnostic message when isolation is unavailable */+ /** @description Diagnostic message when isolation is unavailable or degraded (for example, share_net=true sessions work but no uid mode can create the private network namespace required by share_net=false) */message?: string;/** @description Whether sessions using uid_mode setpriv can be created with execd's default UID/GID. Requests that select different UID/GID values may still return 503 NOT_SUPPORTED when identity switching is unavailable. */setpriv_available?: boolean;/** @description Whether sessions using uid_mode userns can be created */userns_available?: boolean;+ /** @description Whether sessions using uid_mode setpriv can also create the private network namespace required by share_net=false (bwrap --unshare-net; its loopback setup needs CAP_NET_ADMIN in the execd container). Create rejects share_net=false requests with 503 NOT_SUPPORTED when the requested mode's flag is false. */+ setpriv_net_available?: boolean;+ /** @description Whether sessions using uid_mode userns can also create the private network namespace required by share_net=false. */+ userns_net_available?: boolean;commit_supported?: boolean;diff_supported?: boolean;/** @description execd init-mode and workload-hardening state (OSEP-0018): whether execd is the sandbox init and which of its controls are in effect. Not an isolation capability; reported here so operators see enforcement state in one place. */diff --git a/sdks/sandbox/python/src/opensandbox/api/execd/models/capabilities_response.py b/sdks/sandbox/python/src/opensandbox/api/execd/models/capabilities_response.pyindex 202b5590e..c969c02e6 100644--- a/sdks/sandbox/python/src/opensandbox/api/execd/models/capabilities_response.py+++ b/sdks/sandbox/python/src/opensandbox/api/execd/models/capabilities_response.py@@ -38,11 +38,18 @@ class CapabilitiesResponse:available (bool | Unset):isolator (str | Unset):version (str | Unset):- message (str | Unset): Diagnostic message when isolation is unavailable+ message (str | Unset): Diagnostic message when isolation is unavailable or degraded (for example, share_net=true+ sessions work but no uid mode can create the private network namespace required by share_net=false)setpriv_available (bool | Unset): Whether sessions using uid_mode setpriv can be created with execd's defaultUID/GID. Requests that select different UID/GID values may still return 503 NOT_SUPPORTED when identityswitching is unavailable.userns_available (bool | Unset): Whether sessions using uid_mode userns can be created+ setpriv_net_available (bool | Unset): Whether sessions using uid_mode setpriv can also create the private+ network namespace required by share_net=false (bwrap --unshare-net; its loopback setup needs CAP_NET_ADMIN in+ the execd container). Create rejects share_net=false requests with 503 NOT_SUPPORTED when the requested mode's+ flag is false.+ userns_net_available (bool | Unset): Whether sessions using uid_mode userns can also create the private network+ namespace required by share_net=false.commit_supported (bool | Unset):diff_supported (bool | Unset):hardening (CapabilitiesResponseHardening | Unset): execd init-mode and workload-hardening state (OSEP-0018):@@ -56,6 +63,8 @@ class CapabilitiesResponse:message: str | Unset = UNSETsetpriv_available: bool | Unset = UNSETuserns_available: bool | Unset = UNSET+ setpriv_net_available: bool | Unset = UNSET+ userns_net_available: bool | Unset = UNSETcommit_supported: bool | Unset = UNSETdiff_supported: bool | Unset = UNSEThardening: CapabilitiesResponseHardening | Unset = UNSET@@ -74,6 +83,10 @@ class CapabilitiesResponse:userns_available = self.userns_available+ setpriv_net_available = self.setpriv_net_available++ userns_net_available = self.userns_net_available+commit_supported = self.commit_supporteddiff_supported = self.diff_supported@@ -97,6 +110,10 @@ class CapabilitiesResponse:field_dict["setpriv_available"] = setpriv_availableif userns_available is not UNSET:field_dict["userns_available"] = userns_available+ if setpriv_net_available is not UNSET:+ field_dict["setpriv_net_available"] = setpriv_net_available+ if userns_net_available is not UNSET:+ field_dict["userns_net_available"] = userns_net_availableif commit_supported is not UNSET:field_dict["commit_supported"] = commit_supportedif diff_supported is not UNSET:@@ -123,6 +140,10 @@ class CapabilitiesResponse:userns_available = d.pop("userns_available", UNSET)+ setpriv_net_available = d.pop("setpriv_net_available", UNSET)++ userns_net_available = d.pop("userns_net_available", UNSET)+commit_supported = d.pop("commit_supported", UNSET)diff_supported = d.pop("diff_supported", UNSET)@@ -141,6 +162,8 @@ class CapabilitiesResponse:message=message,setpriv_available=setpriv_available,userns_available=userns_available,+ setpriv_net_available=setpriv_net_available,+ userns_net_available=userns_net_available,commit_supported=commit_supported,diff_supported=diff_supported,hardening=hardening,diff --git a/specs/execd-api.yaml b/specs/execd-api.yamlindex b2cd8d610..f2236750a 100644--- a/specs/execd-api.yaml+++ b/specs/execd-api.yaml@@ -3341,7 +3341,10 @@ components:type: stringmessage:type: string- description: Diagnostic message when isolation is unavailable+ description: >-+ Diagnostic message when isolation is unavailable or degraded (for+ example, share_net=true sessions work but no uid mode can create+ the private network namespace required by share_net=false)setpriv_available:type: booleandescription: >-@@ -3352,6 +3355,19 @@ components:userns_available:type: booleandescription: Whether sessions using uid_mode userns can be created+ setpriv_net_available:+ type: boolean+ description: >-+ Whether sessions using uid_mode setpriv can also create the private+ network namespace required by share_net=false (bwrap --unshare-net;+ its loopback setup needs CAP_NET_ADMIN in the execd container).+ Create rejects share_net=false requests with 503 NOT_SUPPORTED when+ the requested mode's flag is false.+ userns_net_available:+ type: boolean+ description: >-+ Whether sessions using uid_mode userns can also create the private+ network namespace required by share_net=false.commit_supported:type: booleandiff_supported: