Skip to content

An open-source, faster Devin alternative

TypeScript

feat(sandbox): enforce public-only network policy

Igor Zalutski7fad91943f0f
diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.go
index d72fbf8b..7dad2d0b 100644
--- a/internal/api/internal_sandbox.go
+++ b/internal/api/internal_sandbox.go
@@ -113,6 +113,9 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
// networkEnabled=false (the zero value) into sandbox_sessions.config_json,
// so forks of that sandbox inherited a no-network config.
cfg.EnsureNetworkEnabledDefault()
+ if err := cfg.NetworkPolicy.Validate(); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
+ }
// Validate inline webhook specs up-front, exactly as the public createSandbox
// handler does at its entry. Without this the edge→CP create path skips
@@ -186,7 +189,7 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
c.SetParamValues(checkpointID.String())
// Forward user-supplied envs + secret store + metadata so they're
// applied at fork time. Same semantics as the public path.
- result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)
+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB, cfg.NetworkPolicy)
if cpErr != nil {
return c.JSON(status, map[string]string{"error": cpErr.Error()})
}
diff --git a/internal/api/sandbox.go b/internal/api/sandbox.go
index 33a4a504..5f098594 100644
--- a/internal/api/sandbox.go
+++ b/internal/api/sandbox.go
@@ -63,6 +63,9 @@ func (s *Server) createSandbox(c echo.Context) error {
// Default networkEnabled=true when caller omits it, so the value persisted
// to sandbox_sessions.config_json is explicit and forks inherit it correctly.
cfg.EnsureNetworkEnabledDefault()
+ if err := cfg.NetworkPolicy.Validate(); err != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
+ }
// Validate CPU/memory against allowed tiers.
// Self-serve tiers (memoryMB → vCPU): 1024→1, 4096→1, 8192→2, 16384→4.
@@ -209,7 +212,7 @@ func (s *Server) createSandbox(c echo.Context) error {
// on the fork. User envs override checkpoint's stored envs.
// Secret store: if checkpoint has none, user can attach one at fork time.
// If checkpoint already has one, user cannot override it.
- result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)
+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB, cfg.NetworkPolicy)
if cpErr != nil {
return c.JSON(status, map[string]string{"error": cpErr.Error()})
}
@@ -397,7 +400,7 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgID
c.SetParamNames("checkpointId")
c.SetParamValues(checkpointID.String())
- result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)
+ result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB, cfg.NetworkPolicy)
if cpErr != nil {
emit("error", map[string]string{"error": cpErr.Error()})
return nil
@@ -557,6 +560,96 @@ func cfgForPersistence(cfg types.SandboxConfig) types.SandboxConfig {
return cfg
}
+func effectiveForkNetworkPolicy(inherited, requested types.NetworkPolicy) (types.NetworkPolicy, error) {
+ if err := inherited.Validate(); err != nil {
+ return types.NetworkPolicyNone, fmt.Errorf("checkpoint has invalid network policy: %w", err)
+ }
+ if err := requested.Validate(); err != nil {
+ return types.NetworkPolicyNone, err
+ }
+ // A fork may tighten an unrestricted checkpoint, but it cannot weaken a
+ // public-only checkpoint. With the v1 none/public lattice, public wins.
+ if inherited == types.NetworkPolicyPublic || requested == types.NetworkPolicyPublic {
+ return types.NetworkPolicyPublic, nil
+ }
+ return types.NetworkPolicyNone, nil
+}
+
+// effectiveRestoreSessionConfig computes the monotonic network policy for an
+// in-place checkpoint restore and returns the API-visible session config that
+// must be persisted before dispatching the restore. QEMU independently applies
+// the same public-wins rule from the live VM and checkpoint metadata. Keeping
+// the session row in lockstep is load-bearing: preview URL admission reads this
+// config, so a stale unrestricted value could otherwise re-enable ingress for
+// a VM that the worker strengthened to public-only during restore.
+func effectiveRestoreSessionConfig(sessionConfig, checkpointConfig json.RawMessage) (json.RawMessage, bool, error) {
+ decode := func(label string, raw json.RawMessage) (types.SandboxConfig, map[string]json.RawMessage, error) {
+ if len(raw) == 0 {
+ raw = json.RawMessage(`{}`)
+ }
+ var cfg types.SandboxConfig
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return types.SandboxConfig{}, nil, fmt.Errorf("cannot verify %s network policy: %w", label, err)
+ }
+ if err := cfg.NetworkPolicy.Validate(); err != nil {
+ return types.SandboxConfig{}, nil, fmt.Errorf("cannot verify %s network policy: %w", label, err)
+ }
+ var object map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &object); err != nil {
+ return types.SandboxConfig{}, nil, fmt.Errorf("cannot preserve %s config: %w", label, err)
+ }
+ if object == nil {
+ object = make(map[string]json.RawMessage)
+ }
+ return cfg, object, nil
+ }
+
+ sessionCfg, sessionObject, err := decode("sandbox", sessionConfig)
+ if err != nil {
+ return nil, false, err
+ }
+ checkpointCfg, _, err := decode("checkpoint", checkpointConfig)
+ if err != nil {
+ return nil, false, err
+ }
+
+ effective := sessionCfg.NetworkPolicy
+ if checkpointCfg.NetworkPolicy == types.NetworkPolicyPublic {
+ effective = types.NetworkPolicyPublic
+ }
+ if effective == sessionCfg.NetworkPolicy {
+ return sessionConfig, false, nil
+ }
+
+ encodedPolicy, err := json.Marshal(effective)
+ if err != nil {
+ return nil, false, fmt.Errorf("encode effective network policy: %w", err)
+ }
+ sessionObject["networkPolicy"] = encodedPolicy
+ updated, err := json.Marshal(sessionObject)
+ if err != nil {
+ return nil, false, fmt.Errorf("encode restored sandbox config: %w", err)
+ }
+ return updated, true, nil
+}
+
+func validatePreviewNetworkPolicy(config json.RawMessage) error {
+ if len(config) == 0 {
+ return nil
+ }
+ var cfg types.SandboxConfig
+ if err := json.Unmarshal(config, &cfg); err != nil {
+ return fmt.Errorf("cannot verify sandbox network policy: %w", err)
+ }
+ if err := cfg.NetworkPolicy.Validate(); err != nil {
+ return fmt.Errorf("cannot verify sandbox network policy: %w", err)
+ }
+ if cfg.NetworkPolicy == types.NetworkPolicyPublic {
+ return fmt.Errorf("preview URLs are disabled for networkPolicy=%q sandboxes", types.NetworkPolicyPublic)
+ }
+ return nil
+}
+
// flattenSecretAllowedHosts converts the internal per-secret allowed-hosts map
// (env var → host slice) into the proto wire shape (env var → comma-joined string).
// Mirror of parseSecretAllowedHosts in internal/worker/grpc_server.go.
@@ -720,6 +813,7 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg ty
Timeout: int32(cfg.Timeout),
Envs: cfg.Envs,
NetworkEnabled: cfg.IsNetworkEnabled(),
+ NetworkPolicy: string(cfg.NetworkPolicy),
Port: int32(cfg.Port),
TemplateRootfsKey: templateRootfsKey,
TemplateWorkspaceKey: templateWorkspaceKey,
@@ -1791,6 +1885,7 @@ func (s *Server) migrateForScale(ctx context.Context, sandboxID string, session
EgressAllowlist: preCopyResp.EgressAllowlist,
TokenHosts: preCopyResp.TokenHosts,
SealedNames: preCopyResp.SealedNames,
+ NetworkPolicy: preCopyResp.NetworkPolicy,
})
if err != nil {
log.Printf("scale-migrate %s: prepare target failed: %v", sandboxID, err)
@@ -2684,6 +2779,7 @@ func (s *Server) promoteCheckpointToFull(ctx context.Context, checkpointID, prom
MemoryMb: int32(cfg.MemoryMB),
CpuCount: int32(cfg.CpuCount),
NetworkEnabled: cfg.IsNetworkEnabled(),
+ NetworkPolicy: string(cfg.NetworkPolicy),
Port: int32(cfg.Port),
TemplateRootfsKey: rootfsKey,
TemplateWorkspaceKey: workspaceKey,
@@ -2814,6 +2910,22 @@ func (s *Server) restoreCheckpoint(c echo.Context) error {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "checkpoint is not ready (status: " + cp.Status + ")"})
}
+ // A restore can only preserve or tighten the sandbox's network boundary.
+ // Persist the effective value before the asynchronous worker call so every
+ // API surface (especially preview URL creation) observes the same policy the
+ // worker will enforce. If persistence fails, do not begin a restore that
+ // could leave the worker and API disagreeing about ingress eligibility.
+ restoredConfig, policyChanged, policyErr := effectiveRestoreSessionConfig(session.Config, cp.SandboxConfig)
+ if policyErr != nil {
+ return c.JSON(http.StatusConflict, map[string]string{"error": policyErr.Error()})
+ }
+ if policyChanged {
+ if err := s.store.UpdateSandboxSessionConfig(ctx, session.ID, restoredConfig); err != nil {
+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to persist restored sandbox network policy: " + err.Error()})
+ }
+ session.Config = restoredConfig
+ }
+
// Dispatch restore in background — return immediately.
// Commands will block until restore completes (via pendingCreates + waitForReady).
pending := &pendingCreate{ready: make(chan struct{})}
@@ -2877,13 +2989,14 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {
// (caller wins) so callers can stamp identifiers like agent_id without
// losing whatever the snapshot author originally set.
var body struct {
- Envs map[string]string `json:"envs"`
- SecretStore string `json:"secretStore"`
- Metadata map[string]string `json:"metadata"`
- MemoryMB int `json:"memoryMB"`
+ Envs map[string]string `json:"envs"`
+ SecretStore string `json:"secretStore"`
+ Metadata map[string]string `json:"metadata"`
+ MemoryMB int `json:"memoryMB"`
+ NetworkPolicy types.NetworkPolicy `json:"networkPolicy"`
}
_ = c.Bind(&body)
- result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata, body.MemoryMB)
+ result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata, body.MemoryMB, body.NetworkPolicy)
if err != nil {
return c.JSON(httpStatus, map[string]string{"error": err.Error()})
}
@@ -2909,7 +3022,7 @@ func (s *Server) createFromCheckpoint(c echo.Context) error {
// metadata before the sandbox session row is recorded — so callers can
// stamp request-time identifiers (e.g. agent_id) without losing whatever
// the snapshot author baked in.
-func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string, userMetadata map[string]string, userMemoryMB int) (map[string]interface{}, int, error) {
+func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string, userMetadata map[string]string, userMemoryMB int, userNetworkPolicy types.NetworkPolicy) (map[string]interface{}, int, error) {
checkpointIDStr := c.Param("checkpointId")
ctx := c.Request().Context()
@@ -2996,6 +3109,15 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
// Parse the original sandbox config to reuse settings
var originalCfg types.SandboxConfig
_ = json.Unmarshal(cp.SandboxConfig, &originalCfg)
+ effectivePolicy, policyErr := effectiveForkNetworkPolicy(originalCfg.NetworkPolicy, userNetworkPolicy)
+ if policyErr != nil {
+ status := http.StatusBadRequest
+ if originalCfg.NetworkPolicy.Validate() != nil {
+ status = http.StatusConflict
+ }
+ return nil, status, policyErr
+ }
+ originalCfg.NetworkPolicy = effectivePolicy
// Older checkpoints predate the networkEnabled default-to-true normalization
// and persisted no value (or false from the old non-pointer bool). Forks
// should still come up with networking on.
@@ -3184,6 +3306,7 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st
MemoryMb: int32(originalCfg.MemoryMB),
CpuCount: int32(originalCfg.CpuCount),
NetworkEnabled: originalCfg.IsNetworkEnabled(),
+ NetworkPolicy: string(originalCfg.NetworkPolicy),
Port: int32(originalCfg.Port),
TemplateRootfsKey: forkRootfsKey,
TemplateWorkspaceKey: forkWorkspaceKey,
@@ -3690,6 +3813,15 @@ func (s *Server) createPreviewURL(c echo.Context) error {
"error": "org context required",
})
}
+ session, sessionErr := s.store.GetSandboxSessionInOrg(ctx, orgID, sandboxID)
+ if sessionErr != nil {
+ return c.JSON(http.StatusBadRequest, map[string]string{
+ "error": "sandbox is not running or not found",
+ })
+ }
+ if err := validatePreviewNetworkPolicy(session.Config); err != nil {
+ return c.JSON(http.StatusConflict, map[string]string{"error": err.Error()})
+ }
// Parse request body — port is required
var req struct {
@@ -3718,9 +3850,8 @@ func (s *Server) createPreviewURL(c echo.Context) error {
sandboxRunning = true
}
}
- if !sandboxRunning && s.store != nil {
- session, err := s.store.GetSandboxSession(ctx, sandboxID)
- if err == nil && session.Status == "running" && session.OrgID == orgID {
+ if !sandboxRunning {
+ if session.Status == "running" {
sandboxRunning = true
}
}
diff --git a/internal/api/sandbox_test.go b/internal/api/sandbox_test.go
index b6ca3162..22022213 100644
--- a/internal/api/sandbox_test.go
+++ b/internal/api/sandbox_test.go
@@ -9,6 +9,7 @@ import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
"github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/pkg/types"
)
func TestHealthEndpoint(t *testing.T) {
@@ -117,3 +118,123 @@ func TestPatchOpsStayOwnerOnly(t *testing.T) {
t.Fatal("owner must be allowed patch/delete ops on own public checkpoint")
}
}
+
+func TestEffectiveForkNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ inherited types.NetworkPolicy
+ requested types.NetworkPolicy
+ want types.NetworkPolicy
+ wantErr bool
+ }{
+ {name: "unrestricted inherited", inherited: types.NetworkPolicyNone, requested: types.NetworkPolicyNone, want: types.NetworkPolicyNone},
+ {name: "named snapshot can tighten", inherited: types.NetworkPolicyNone, requested: types.NetworkPolicyPublic, want: types.NetworkPolicyPublic},
+ {name: "direct fork inherits public", inherited: types.NetworkPolicyPublic, requested: types.NetworkPolicyNone, want: types.NetworkPolicyPublic},
+ {name: "public remains public", inherited: types.NetworkPolicyPublic, requested: types.NetworkPolicyPublic, want: types.NetworkPolicyPublic},
+ {name: "invalid request", inherited: types.NetworkPolicyNone, requested: types.NetworkPolicy("private"), wantErr: true},
+ {name: "invalid checkpoint", inherited: types.NetworkPolicy("private"), requested: types.NetworkPolicyPublic, wantErr: true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := effectiveForkNetworkPolicy(tc.inherited, tc.requested)
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("error = %v, wantErr %v", err, tc.wantErr)
+ }
+ if !tc.wantErr && got != tc.want {
+ t.Fatalf("policy = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestNetworkPolicySurvivesPersistence(t *testing.T) {
+ t.Parallel()
+
+ persisted := cfgForPersistence(types.SandboxConfig{NetworkPolicy: types.NetworkPolicyPublic})
+ data, err := json.Marshal(persisted)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var roundTrip types.SandboxConfig
+ if err := json.Unmarshal(data, &roundTrip); err != nil {
+ t.Fatal(err)
+ }
+ if roundTrip.NetworkPolicy != types.NetworkPolicyPublic {
+ t.Fatalf("network policy after persistence = %q, want public", roundTrip.NetworkPolicy)
+ }
+}
+
+func TestEffectiveRestoreSessionConfig(t *testing.T) {
+ t.Parallel()
+
+ t.Run("checkpoint can tighten and unknown fields survive", func(t *testing.T) {
+ current := json.RawMessage(`{"alias":"builder","future":{"keep":true}}`)
+ checkpoint := json.RawMessage(`{"networkPolicy":"public"}`)
+ updated, changed, err := effectiveRestoreSessionConfig(current, checkpoint)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !changed {
+ t.Fatal("public checkpoint did not tighten unrestricted session")
+ }
+ var got map[string]json.RawMessage
+ if err := json.Unmarshal(updated, &got); err != nil {
+ t.Fatal(err)
+ }
+ if string(got["networkPolicy"]) != `"public"` || string(got["future"]) != `{"keep":true}` {
+ t.Fatalf("updated config lost policy or fields: %s", updated)
+ }
+ if err := validatePreviewNetworkPolicy(updated); err == nil {
+ t.Fatal("tightened persisted config still permits preview ingress")
+ }
+ })
+
+ for _, tc := range []struct {
+ name string
+ current json.RawMessage
+ checkpoint json.RawMessage
+ wantErr bool
+ }{
+ {name: "public session cannot weaken", current: json.RawMessage(`{"networkPolicy":"public"}`), checkpoint: json.RawMessage(`{}`)},
+ {name: "legacy unrestricted stays unrestricted", current: nil, checkpoint: nil},
+ {name: "invalid session fails closed", current: json.RawMessage(`{"networkPolicy":"private"}`), checkpoint: json.RawMessage(`{}`), wantErr: true},
+ {name: "invalid checkpoint fails closed", current: json.RawMessage(`{}`), checkpoint: json.RawMessage(`{"networkPolicy":"private"}`), wantErr: true},
+ {name: "malformed checkpoint fails closed", current: json.RawMessage(`{}`), checkpoint: json.RawMessage(`{`), wantErr: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ _, changed, err := effectiveRestoreSessionConfig(tc.current, tc.checkpoint)
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("error = %v, wantErr %v", err, tc.wantErr)
+ }
+ if !tc.wantErr && changed {
+ t.Fatal("unchanged policy reported a config mutation")
+ }
+ })
+ }
+}
+
+func TestPreviewNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ config json.RawMessage
+ wantErr bool
+ }{
+ {name: "legacy empty config", config: nil},
+ {name: "unrestricted", config: json.RawMessage(`{}`)},
+ {name: "public is egress only", config: json.RawMessage(`{"networkPolicy":"public"}`), wantErr: true},
+ {name: "unknown fails closed", config: json.RawMessage(`{"networkPolicy":"private"}`), wantErr: true},
+ {name: "malformed fails closed", config: json.RawMessage(`{`), wantErr: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ err := validatePreviewNetworkPolicy(tc.config)
+ if (err != nil) != tc.wantErr {
+ t.Fatalf("error = %v, wantErr %v", err, tc.wantErr)
+ }
+ })
+ }
+}
diff --git a/internal/controlplane/scaler.go b/internal/controlplane/scaler.go
index f4858d9b..2cf107cc 100644
--- a/internal/controlplane/scaler.go
+++ b/internal/controlplane/scaler.go
@@ -20,9 +20,9 @@ import (
)
const (
- scaleUpThreshold = 0.50 // Scale up when utilization > 50% (gives ~3 min runway for new worker to boot)
- scaleDownThreshold = 0.20 // Scale down when utilization < 20%
- maxWorkersPerRegion = 10 // Hard cap to prevent runaway launches
+ scaleUpThreshold = 0.50 // Scale up when utilization > 50% (gives ~3 min runway for new worker to boot)
+ scaleDownThreshold = 0.20 // Scale down when utilization < 20%
+ maxWorkersPerRegion = 10 // Hard cap to prevent runaway launches
pendingWorkerTTL = 10 * time.Minute // How long to wait for a launched worker to register
// Resource-based scaling thresholds (applied per-worker, trigger on ANY worker exceeding)
@@ -40,8 +40,8 @@ const (
emergencyCPUThreshold = 95.0
emergencyMemThreshold = 95.0
emergencyDiskThreshold = 90.0
- evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
- evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
+ evacuationBatchSize = 3 // sandboxes to migrate per eval cycle per worker
+ evacuationCooldown = 60 * time.Second // per-worker cooldown between evacuation batches
// drainTimeout caps total wall-clock time for a single drain. With
// per-target serialization (one in-flight migration per target), a
// drain bottlenecked on a single target processes sandboxes serially
@@ -51,7 +51,7 @@ const (
// of a full drain. Bumping to 6h leaves headroom for large workloads;
// genuine stuck drains are caught by per-migration timeouts + the
// natural-expiry fallback in drainWorker.
- drainTimeout = 6 * time.Hour
+ drainTimeout = 6 * time.Hour
creationFailureThreshold = 3 // consecutive failures before exponential backoff
creationBackoffMin = 1 * time.Minute // initial backoff after threshold hit
@@ -85,14 +85,14 @@ type OrphanCleaner interface {
type ScalerConfig struct {
Pool compute.Pool
Registry ScalerRegistry
- Store *db.Store // for updating session worker_id after migration
+ Store *db.Store // for updating session worker_id after migration
StateStore ScalerStateStore // optional: persists scaler state to Redis (nil = in-memory)
WorkerImage string
Cooldown time.Duration // minimum time between scale-up actions per region
Interval time.Duration // how often to evaluate scaling (0 = default 30s)
- MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.
- MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.
- IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.
+ MinWorkers int // minimum total workers per region (0 = default 1). Always kept running.
+ MaxWorkers int // maximum workers per region (0 = default 10). Hard cap to prevent runaway launches.
+ IdleReserve int // target idle (0 sandbox) workers for burst absorption (0 = default 1). Separate from MinWorkers.
// Event emit for D1 sandboxes_index sync. After a scaler-triggered
// migration succeeds (rolling replace, evacuation), XADD a "migrated"
@@ -132,17 +132,17 @@ type Scaler struct {
image string
cooldown time.Duration
interval time.Duration
- minWorkers int
- maxWorkers int
- idleReserve int
+ minWorkers int
+ maxWorkers int
+ idleReserve int
- rdb *redis.Client
- cellID string
+ rdb *redis.Client
+ cellID string
- mu sync.Mutex // protects stop/cancel
- cancel context.CancelFunc
- wg sync.WaitGroup
- running bool
+ mu sync.Mutex // protects stop/cancel
+ cancel context.CancelFunc
+ wg sync.WaitGroup
+ running bool
machineSizes []string // ranked list of provider-specific sizes for scale-up fallback
@@ -1946,6 +1946,7 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorker
SealedTokens: preCopyResp.SealedTokens,
EgressAllowlist: preCopyResp.EgressAllowlist,
TokenHosts: preCopyResp.TokenHosts,
+ NetworkPolicy: preCopyResp.NetworkPolicy,
// Paused-tier move: target registers Status=paused so the usage ticker
// never bills it while the RAM streams in.
ArrivePaused: keepPaused,
diff --git a/internal/controlplane/server.go b/internal/controlplane/server.go
index 2e107e14..7320912a 100644
--- a/internal/controlplane/server.go
+++ b/internal/controlplane/server.go
@@ -96,15 +96,16 @@ func (s *Server) Close() error {
func (s *Server) createSandbox(c echo.Context) error {
var req struct {
- TemplateID string `json:"templateID"`
- Timeout int `json:"timeout"`
- Region string `json:"region"`
- Envs map[string]string `json:"envs"`
- MemoryMB int `json:"memoryMB"`
- CpuCount int `json:"cpuCount"`
- Metadata map[string]string `json:"metadata"`
- NetworkEnabled *bool `json:"networkEnabled"`
- SecretStore string `json:"secretStore"` // secret store name — resolves secrets + egress config
+ TemplateID string `json:"templateID"`
+ Timeout int `json:"timeout"`
+ Region string `json:"region"`
+ Envs map[string]string `json:"envs"`
+ MemoryMB int `json:"memoryMB"`
+ CpuCount int `json:"cpuCount"`
+ Metadata map[string]string `json:"metadata"`
+ NetworkEnabled *bool `json:"networkEnabled"`
+ NetworkPolicy string `json:"networkPolicy"`
+ SecretStore string `json:"secretStore"` // secret store name — resolves secrets + egress config
}
if err := c.Bind(&req); err != nil {
return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request: " + err.Error()})
@@ -209,6 +210,7 @@ func (s *Server) createSandbox(c echo.Context) error {
MemoryMb: int32(req.MemoryMB),
CpuCount: int32(req.CpuCount),
NetworkEnabled: *req.NetworkEnabled,
+ NetworkPolicy: req.NetworkPolicy,
EgressAllowlist: egressAllowlist,
SecretAllowedHosts: secretAllowedHosts,
})
diff --git a/internal/db/store.go b/internal/db/store.go
index 8921a20a..85c0724b 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -852,6 +852,28 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statu
return s.updateSandboxSessionStatus(ctx, sandboxID, status, errorMsg, "")
}
+// UpdateSandboxSessionConfig replaces the persisted config for one active
+// session. It is intentionally keyed by the session UUID rather than the
+// caller-supplied sandbox ID so a restore cannot mutate another tenant's row
+// if sandbox IDs collide. The restore path uses this for monotonic policy
+// tightening before the worker changes the live VM's network boundary.
+func (s *Store) UpdateSandboxSessionConfig(ctx context.Context, sessionID uuid.UUID, config json.RawMessage) error {
+ tag, err := s.pool.Exec(ctx,
+ `UPDATE sandbox_sessions
+ SET config = $1
+ WHERE id = $2
+ AND status = 'running'`,
+ config, sessionID,
+ )
+ if err != nil {
+ return fmt.Errorf("update sandbox session config: %w", err)
+ }
+ if tag.RowsAffected() == 0 {
+ return fmt.Errorf("running sandbox session %s not found", sessionID)
+ }
+ return nil
+}
+
// UpdateSandboxSessionStatusReason is UpdateSandboxSessionStatus with an explicit
// sandbox.stopped reason (one of user_requested | expired | crash). Use it where
// the reason is known — e.g. "expired" for an idle-timeout kill. An empty reason
diff --git a/internal/qemu/manager.go b/internal/qemu/manager.go
index 588d0ec1..6f4f5703 100644
--- a/internal/qemu/manager.go
+++ b/internal/qemu/manager.go
@@ -248,6 +248,9 @@ type VMInstance struct {
MemoryMB int
HostPort int
GuestPort int
+ // NetworkPolicy is the host-enforced network boundary that must survive
+ // wake, restore, fork, power-cycle, and live migration.
+ NetworkPolicy types.NetworkPolicy
// VM internals
pid int
@@ -291,11 +294,12 @@ type VMInstance struct {
// SandboxMeta is persisted to sandbox-meta.json for recovery after hard kills.
type SandboxMeta struct {
- SandboxID string `json:"sandboxId"`
- Template string `json:"template"`
- CpuCount int `json:"cpuCount"`
- MemoryMB int `json:"memoryMB"`
- GuestPort int `json:"guestPort"`
+ SandboxID string `json:"sandboxId"`
+ Template string `json:"template"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ GuestPort int `json:"guestPort"`
+ NetworkPolicy types.NetworkPolicy `json:"networkPolicy,omitempty"`
}
// SecretsProxyIntegration provides the interface for the secrets proxy to integrate
@@ -905,7 +909,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {
if err != nil {
return fmt.Errorf("allocate golden subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, types.NetworkPolicyNone); err != nil {
m.subnets.Release(netCfg.TAPName)
return fmt.Errorf("create golden TAP: %w", err)
}
@@ -1192,7 +1196,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, cfg.NetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("create TAP: %w", err)
@@ -1202,21 +1206,12 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
if guestPort == 0 {
guestPort = m.cfg.DefaultPort
}
- hostPort, err := FindFreePort()
+ hostPort, err := configureIngress(netCfg, cfg.NetworkPolicy, guestPort)
if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = guestPort
-
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("add DNAT: %w", err)
+ return nil, fmt.Errorf("configure ingress: %w", err)
}
// Add metadata service DNAT (169.254.169.254:80 → host:8888)
@@ -1332,6 +1327,7 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
baseMemoryMB: memMB,
HostPort: hostPort,
GuestPort: guestPort,
+ NetworkPolicy: cfg.NetworkPolicy,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
@@ -1450,11 +1446,12 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,
}
sbMeta := SandboxMeta{
- SandboxID: id,
- Template: template,
- CpuCount: cpus,
- MemoryMB: memMB,
- GuestPort: guestPort,
+ SandboxID: id,
+ Template: template,
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ GuestPort: guestPort,
+ NetworkPolicy: cfg.NetworkPolicy,
}
if metaJSON, err := json.Marshal(sbMeta); err == nil {
if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {
@@ -1760,7 +1757,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, cfg.NetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("create TAP: %w", err)
@@ -1770,21 +1767,12 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type
if guestPort == 0 {
guestPort = m.cfg.DefaultPort
}
- hostPort, err := FindFreePort()
+ hostPort, err := configureIngress(netCfg, cfg.NetworkPolicy, guestPort)
if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = guestPort
-
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("add DNAT: %w", err)
+ return nil, fmt.Errorf("configure ingress: %w", err)
}
// Add metadata service DNAT (169.254.169.254:80 → host:8888)
@@ -1866,6 +1854,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type
baseMemoryMB: memMB,
HostPort: hostPort,
GuestPort: guestPort,
+ NetworkPolicy: cfg.NetworkPolicy,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
@@ -1917,11 +1906,12 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type
}
sbMeta := SandboxMeta{
- SandboxID: id,
- Template: template,
- CpuCount: cpus,
- MemoryMB: memMB,
- GuestPort: guestPort,
+ SandboxID: id,
+ Template: template,
+ CpuCount: cpus,
+ MemoryMB: memMB,
+ GuestPort: guestPort,
+ NetworkPolicy: cfg.NetworkPolicy,
}
if metaJSON, err := json.Marshal(sbMeta); err == nil {
if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {
@@ -3270,6 +3260,7 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointID
BaseMemoryMB: vm.baseMemoryMB,
Template: vm.Template,
GuestPort: vm.GuestPort,
+ NetworkPolicy: vm.NetworkPolicy,
GoldenVersion: vm.goldenVersion,
SnapshotedAt: time.Now(),
}
@@ -3471,6 +3462,7 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, check
BaseMemoryMB: vm.baseMemoryMB,
Template: vm.Template,
GuestPort: vm.GuestPort,
+ NetworkPolicy: vm.NetworkPolicy,
GoldenVersion: vm.goldenVersion,
SnapshotedAt: time.Now(),
}
@@ -3586,6 +3578,12 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
if metaData, err := os.ReadFile(filepath.Join(cacheDir, "snapshot", "snapshot-meta.json")); err == nil {
json.Unmarshal(metaData, &cpMeta)
}
+ restoreNetworkPolicy := cpMeta.NetworkPolicy
+ if restoreNetworkPolicy == types.NetworkPolicyNone {
+ // Checkpoints created before networkPolicy was persisted have an empty
+ // value. Never silently weaken a currently restricted sandbox on restore.
+ restoreNetworkPolicy = vm.NetworkPolicy
+ }
// Determine restore mode: prefer migration-based (-incoming) over savevm (loadvm).
// CreateCheckpoint uses QEMU migrate which produces a standalone mem dump file.
@@ -3629,22 +3627,19 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
if err != nil {
return fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, restoreNetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
return fmt.Errorf("create TAP: %w", err)
}
- hostPort, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return fmt.Errorf("find free port: %w", err)
+ guestPort := vm.GuestPort
+ if guestPort == 0 {
+ guestPort = m.cfg.DefaultPort
}
- netCfg.HostPort = hostPort
- netCfg.GuestPort = vm.GuestPort
- if err := AddDNAT(netCfg); err != nil {
+ hostPort, err := configureIngress(netCfg, restoreNetworkPolicy, guestPort)
+ if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
- return fmt.Errorf("add DNAT: %w", err)
+ return fmt.Errorf("configure ingress: %w", err)
}
if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
log.Printf("qemu: RestoreFromCheckpoint %s: metadata DNAT failed: %v", sandboxID, err)
@@ -3811,6 +3806,8 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoi
vm.agent = agentClient
vm.network = netCfg
vm.HostPort = hostPort
+ vm.GuestPort = guestPort
+ vm.NetworkPolicy = restoreNetworkPolicy
vm.qmpSockPath = qmpSockPath
vm.agentSockPath = agentSockPath
vm.guestMAC = guestMAC
@@ -3863,6 +3860,10 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
if data, err := os.ReadFile(metaPath); err == nil {
json.Unmarshal(data, &meta)
}
+ forkNetworkPolicy := cfg.NetworkPolicy
+ if forkNetworkPolicy == types.NetworkPolicyNone {
+ forkNetworkPolicy = meta.NetworkPolicy
+ }
id := cfg.SandboxID
if id == "" {
@@ -3895,7 +3896,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, forkNetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
return nil, fmt.Errorf("create TAP: %w", err)
@@ -3905,20 +3906,12 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
if guestPort == 0 {
guestPort = m.cfg.DefaultPort
}
- hostPort, err := FindFreePort()
+ hostPort, err := configureIngress(netCfg, forkNetworkPolicy, guestPort)
if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = guestPort
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- os.RemoveAll(sandboxDir)
- return nil, fmt.Errorf("add DNAT: %w", err)
+ return nil, fmt.Errorf("configure ingress: %w", err)
}
// Add metadata service DNAT (169.254.169.254:80 → host:8888)
@@ -4214,6 +4207,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, c
virtioMemRequestedMB: virtioMemAddedMB,
HostPort: hostPort,
GuestPort: guestPort,
+ NetworkPolicy: forkNetworkPolicy,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
@@ -4449,7 +4443,7 @@ func (m *Manager) CleanupOrphanedProcesses() {
}
tapName := strings.TrimSuffix(fields[1], ":")
if strings.HasPrefix(tapName, "qm-") {
- _ = exec.Command("ip", "link", "del", tapName).Run()
+ DeleteTAP(tapName)
log.Printf("qemu: cleaned up orphaned TAP %s", tapName)
}
}
@@ -4491,11 +4485,12 @@ func (m *Manager) RecoverLocalSandboxes() []LocalRecovery {
SandboxID: sandboxID,
HasSnapshot: true,
Meta: SandboxMeta{
- SandboxID: sandboxID,
- Template: snapMeta.Template,
- CpuCount: snapMeta.CpuCount,
- MemoryMB: snapMeta.MemoryMB,
- GuestPort: snapMeta.GuestPort,
+ SandboxID: sandboxID,
+ Template: snapMeta.Template,
+ CpuCount: snapMeta.CpuCount,
+ MemoryMB: snapMeta.MemoryMB,
+ GuestPort: snapMeta.GuestPort,
+ NetworkPolicy: snapMeta.NetworkPolicy,
},
})
continue
diff --git a/internal/qemu/migration.go b/internal/qemu/migration.go
index a380e260..a47e0fbe 100644
--- a/internal/qemu/migration.go
+++ b/internal/qemu/migration.go
@@ -362,7 +362,7 @@ func (mc *MigrationCoordinator) LiveMigrate(ctx context.Context, sandboxID, inco
// PrepareIncomingMigration sets up QEMU on the target worker to receive a live migration.
// Returns the TCP address for the source to connect to.
-func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error) {
+func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string, networkPolicy types.NetworkPolicy) (incomingAddr string, hostPort int, err error) {
sandboxDir := filepath.Join(m.cfg.DataDir, "sandboxes", sandboxID)
if err := os.MkdirAll(sandboxDir, 0755); err != nil {
return "", 0, fmt.Errorf("mkdir: %w", err)
@@ -395,27 +395,19 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf
if err != nil {
return "", 0, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, networkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
return "", 0, fmt.Errorf("create TAP: %w", err)
}
- hp, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return "", 0, fmt.Errorf("find free port: %w", err)
+ if guestPort == 0 {
+ guestPort = 80
}
- netCfg.HostPort = hp
- netCfg.GuestPort = guestPort
- if netCfg.GuestPort == 0 {
- netCfg.GuestPort = 80
- }
-
- if err := AddDNAT(netCfg); err != nil {
+ hp, err := configureIngress(netCfg, networkPolicy, guestPort)
+ if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
- return "", 0, fmt.Errorf("add DNAT: %w", err)
+ return "", 0, fmt.Errorf("configure ingress: %w", err)
}
if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
log.Printf("qemu: warning: metadata DNAT failed: %v", err)
@@ -517,6 +509,7 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootf
baseMemoryMB: memMB,
HostPort: hp,
GuestPort: netCfg.GuestPort,
+ NetworkPolicy: networkPolicy,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
@@ -660,6 +653,7 @@ func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpoin
baseCPU = vm.CpuCount
baseMem = vm.baseMemoryMB
pid = vm.pid
+ secrets.NetworkPolicy = string(vm.NetworkPolicy)
if vm.network != nil {
guestIP = vm.network.GuestIP
}
@@ -784,7 +778,7 @@ func (m *Manager) PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID,
return "", 0, r.err
}
- incomingAddr, hostPort, err = m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)
+ incomingAddr, hostPort, err = m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template, types.NetworkPolicy(secrets.NetworkPolicy))
if err != nil {
return "", 0, err
}
diff --git a/internal/qemu/network.go b/internal/qemu/network.go
index 4d59c491..bf4542b7 100644
--- a/internal/qemu/network.go
+++ b/internal/qemu/network.go
@@ -6,6 +6,8 @@ import (
"os/exec"
"strings"
"sync"
+
+ "github.com/opensandbox/opensandbox/pkg/types"
)
// NetworkConfig holds the networking state for a single VM.
@@ -117,8 +119,9 @@ func (a *SubnetAllocator) Release(tapName string) {
delete(a.used, block)
}
-// CreateTAP creates a TAP device and configures it with the host IP.
-func CreateTAP(cfg *NetworkConfig) error {
+// CreateTAP creates a TAP device, configures it with the host IP, and applies
+// any host-enforced network policy before the guest can start.
+func CreateTAP(cfg *NetworkConfig, policy types.NetworkPolicy) error {
if err := run("ip", "tuntap", "add", "dev", cfg.TAPName, "mode", "tap"); err != nil {
return fmt.Errorf("create tap %s: %w", cfg.TAPName, err)
}
@@ -142,6 +145,11 @@ func CreateTAP(cfg *NetworkConfig) error {
// link speed while still bounding aggregate worker NIC pressure.
applyRateLimit(cfg.TAPName)
+ if err := applyNetworkPolicy(cfg, policy); err != nil {
+ DeleteTAP(cfg.TAPName)
+ return fmt.Errorf("apply network policy %q to %s: %w", policy, cfg.TAPName, err)
+ }
+
return nil
}
@@ -154,12 +162,180 @@ func applyRateLimit(tapName string) {
"rate", "500mbit", "burst", "10mb", "latency", "50ms")
}
-// DeleteTAP removes a TAP device and its tc qdisc.
+// DeleteTAP removes a TAP device, its tc qdisc, and any per-TAP firewall
+// policy. Firewall cleanup is unconditional so a recycled TAP name cannot
+// inherit rules from an interrupted sandbox lifecycle.
func DeleteTAP(tapName string) {
+ cleanupNetworkPolicy(tapName)
_ = run("tc", "qdisc", "del", "dev", tapName, "root")
_ = run("ip", "link", "del", tapName)
}
+type networkCommand struct {
+ name string
+ args []string
+}
+
+type networkCommandRunner func(name string, args ...string) error
+
+var publicBlockedIPv4CIDRs = []string{
+ "0.0.0.0/8",
+ "10.0.0.0/8",
+ "100.64.0.0/10",
+ "127.0.0.0/8",
+ "169.254.0.0/16",
+ "172.16.0.0/12",
+ "192.0.0.0/24",
+ "192.0.2.0/24",
+ "192.88.99.0/24",
+ "192.168.0.0/16",
+ "198.18.0.0/15",
+ "198.51.100.0/24",
+ "203.0.113.0/24",
+ "224.0.0.0/4",
+ "240.0.0.0/4",
+}
+
+func networkPolicyChainNames(tapName string) (input4, egress4, ingress4, input6, egress6, ingress6 string) {
+ return "OCPI-" + tapName, "OCPE-" + tapName, "OCPN-" + tapName,
+ "OC6I-" + tapName, "OC6E-" + tapName, "OC6N-" + tapName
+}
+
+func validateTAPName(tapName string) error {
+ if tapName == "" || len(tapName) > 15 {
+ return fmt.Errorf("invalid TAP name %q", tapName)
+ }
+ for _, r := range tapName {
+ if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == '.' {
+ continue
+ }
+ return fmt.Errorf("invalid TAP name %q", tapName)
+ }
+ return nil
+}
+
+// publicNetworkPolicyCommands returns the fail-closed firewall program for a
+// public-only sandbox. The per-TAP jumps are inserted ahead of the worker's
+// broad 172.16/16 forwarding rules. INPUT denies guest-to-worker access,
+// including the metadata DNAT target. The egress chain rejects spoofed source
+// addresses and non-public IPv4 destinations before permitting ordinary public
+// IPv4. The separate ingress chain permits established replies but rejects new
+// connections from forwarded and host-originated traffic (including a stale
+// local DNAT rule). IPv6 is denied because the worker does not currently
+// provide a public-IPv6 route with an equivalent allow contract.
+func publicNetworkPolicyCommands(cfg *NetworkConfig) []networkCommand {
+ tapName := cfg.TAPName
+ input4, egress4, ingress4, input6, egress6, ingress6 := networkPolicyChainNames(tapName)
+ commands := []networkCommand{
+ {name: "iptables", args: []string{"-N", input4}},
+ {name: "iptables", args: []string{"-A", input4, "-j", "DROP"}},
+ {name: "iptables", args: []string{"-N", egress4}},
+ {name: "iptables", args: []string{"-A", egress4, "!", "-s", cfg.GuestIP + "/32", "-j", "DROP"}},
+ }
+ for _, cidr := range publicBlockedIPv4CIDRs {
+ commands = append(commands, networkCommand{
+ name: "iptables",
+ args: []string{"-A", egress4, "-d", cidr, "-j", "DROP"},
+ })
+ }
+ commands = append(commands,
+ networkCommand{name: "iptables", args: []string{"-A", egress4, "-j", "ACCEPT"}},
+ networkCommand{name: "iptables", args: []string{"-N", ingress4}},
+ networkCommand{name: "iptables", args: []string{"-A", ingress4, "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-j", "ACCEPT"}},
+ networkCommand{name: "iptables", args: []string{"-A", ingress4, "-j", "DROP"}},
+ networkCommand{name: "ip6tables", args: []string{"-N", input6}},
+ networkCommand{name: "ip6tables", args: []string{"-A", input6, "-j", "DROP"}},
+ networkCommand{name: "ip6tables", args: []string{"-N", egress6}},
+ networkCommand{name: "ip6tables", args: []string{"-A", egress6, "-j", "DROP"}},
+ networkCommand{name: "ip6tables", args: []string{"-N", ingress6}},
+ networkCommand{name: "ip6tables", args: []string{"-A", ingress6, "-j", "DROP"}},
+ // Install jumps only after every chain has been populated. CreateTAP
+ // fails and deletes the TAP if any command above or below fails.
+ networkCommand{name: "iptables", args: []string{"-I", "INPUT", "1", "-i", tapName, "-j", input4}},
+ networkCommand{name: "iptables", args: []string{"-I", "FORWARD", "1", "-i", tapName, "-j", egress4}},
+ networkCommand{name: "iptables", args: []string{"-I", "FORWARD", "1", "-o", tapName, "-j", ingress4}},
+ networkCommand{name: "iptables", args: []string{"-I", "OUTPUT", "1", "-o", tapName, "-j", ingress4}},
+ networkCommand{name: "ip6tables", args: []string{"-I", "INPUT", "1", "-i", tapName, "-j", input6}},
+ networkCommand{name: "ip6tables", args: []string{"-I", "FORWARD", "1", "-i", tapName, "-j", egress6}},
+ networkCommand{name: "ip6tables", args: []string{"-I", "FORWARD", "1", "-o", tapName, "-j", ingress6}},
+ networkCommand{name: "ip6tables", args: []string{"-I", "OUTPUT", "1", "-o", tapName, "-j", ingress6}},
+ )
+ return commands
+}
+
+func networkPolicyCleanupCommands(tapName string) []networkCommand {
+ input4, egress4, ingress4, input6, egress6, ingress6 := networkPolicyChainNames(tapName)
+ return []networkCommand{
+ {name: "iptables", args: []string{"-D", "INPUT", "-i", tapName, "-j", input4}},
+ {name: "iptables", args: []string{"-D", "FORWARD", "-i", tapName, "-j", egress4}},
+ {name: "iptables", args: []string{"-D", "FORWARD", "-o", tapName, "-j", ingress4}},
+ {name: "iptables", args: []string{"-D", "OUTPUT", "-o", tapName, "-j", ingress4}},
+ {name: "iptables", args: []string{"-F", input4}},
+ {name: "iptables", args: []string{"-X", input4}},
+ {name: "iptables", args: []string{"-F", egress4}},
+ {name: "iptables", args: []string{"-X", egress4}},
+ {name: "iptables", args: []string{"-F", ingress4}},
+ {name: "iptables", args: []string{"-X", ingress4}},
+ {name: "ip6tables", args: []string{"-D", "INPUT", "-i", tapName, "-j", input6}},
+ {name: "ip6tables", args: []string{"-D", "FORWARD", "-i", tapName, "-j", egress6}},
+ {name: "ip6tables", args: []string{"-D", "FORWARD", "-o", tapName, "-j", ingress6}},
+ {name: "ip6tables", args: []string{"-D", "OUTPUT", "-o", tapName, "-j", ingress6}},
+ {name: "ip6tables", args: []string{"-F", input6}},
+ {name: "ip6tables", args: []string{"-X", input6}},
+ {name: "ip6tables", args: []string{"-F", egress6}},
+ {name: "ip6tables", args: []string{"-X", egress6}},
+ {name: "ip6tables", args: []string{"-F", ingress6}},
+ {name: "ip6tables", args: []string{"-X", ingress6}},
+ }
+}
+
+func applyNetworkPolicy(cfg *NetworkConfig, policy types.NetworkPolicy) error {
+ return applyNetworkPolicyWithRunner(cfg, policy, run)
+}
+
+func applyNetworkPolicyWithRunner(cfg *NetworkConfig, policy types.NetworkPolicy, runner networkCommandRunner) error {
+ if cfg == nil {
+ return fmt.Errorf("network config is required")
+ }
+ if err := validateTAPName(cfg.TAPName); err != nil {
+ return err
+ }
+ if err := policy.Validate(); err != nil {
+ return err
+ }
+ if policy == types.NetworkPolicyNone {
+ return nil
+ }
+ if ip := net.ParseIP(cfg.GuestIP); ip == nil || ip.To4() == nil {
+ return fmt.Errorf("invalid guest IPv4 address %q", cfg.GuestIP)
+ }
+
+ // An interrupted prior lifecycle may have left per-TAP chains behind. Best
+ // effort cleanup makes setup idempotent; any residue that cannot be removed
+ // makes a subsequent -N/-I command fail and the sandbox creation fails closed.
+ cleanupNetworkPolicyWithRunner(cfg.TAPName, runner)
+ for _, command := range publicNetworkPolicyCommands(cfg) {
+ if err := runner(command.name, command.args...); err != nil {
+ cleanupNetworkPolicyWithRunner(cfg.TAPName, runner)
+ return fmt.Errorf("%s %s: %w", command.name, strings.Join(command.args, " "), err)
+ }
+ }
+ return nil
+}
+
+func cleanupNetworkPolicy(tapName string) {
+ if validateTAPName(tapName) != nil {
+ return
+ }
+ cleanupNetworkPolicyWithRunner(tapName, run)
+}
+
+func cleanupNetworkPolicyWithRunner(tapName string, runner networkCommandRunner) {
+ for _, command := range networkPolicyCleanupCommands(tapName) {
+ _ = runner(command.name, command.args...)
+ }
+}
+
// AddDNAT adds an iptables DNAT rule: hostPort → guestIP:guestPort.
func AddDNAT(cfg *NetworkConfig) error {
if cfg.HostPort == 0 || cfg.GuestPort == 0 {
@@ -205,6 +381,31 @@ func RemoveDNAT(cfg *NetworkConfig) {
fmt.Sprintf("%s:%d", cfg.GuestIP, cfg.GuestPort))
}
+// configureIngress exposes the guest port for unrestricted sandboxes. A
+// public-only sandbox is intentionally egress-only: it gets neither a host
+// port allocation nor DNAT rules, and its FORWARD policy independently drops
+// new traffic headed to the TAP as defense in depth.
+func configureIngress(cfg *NetworkConfig, policy types.NetworkPolicy, guestPort int) (int, error) {
+ if err := policy.Validate(); err != nil {
+ return 0, err
+ }
+ cfg.GuestPort = guestPort
+ if policy == types.NetworkPolicyPublic {
+ cfg.HostPort = 0
+ return 0, nil
+ }
+
+ hostPort, err := FindFreePort()
+ if err != nil {
+ return 0, fmt.Errorf("find free port: %w", err)
+ }
+ cfg.HostPort = hostPort
+ if err := AddDNAT(cfg); err != nil {
+ return 0, err
+ }
+ return hostPort, nil
+}
+
// AddMetadataDNAT adds an iptables rule to redirect 169.254.169.254:80 from a VM's TAP
// to the host metadata server on port 8888.
func AddMetadataDNAT(tapName, hostIP string) error {
diff --git a/internal/qemu/network_policy_test.go b/internal/qemu/network_policy_test.go
new file mode 100644
index 00000000..707b8534
--- /dev/null
+++ b/internal/qemu/network_policy_test.go
@@ -0,0 +1,203 @@
+package qemu
+
+import (
+ "errors"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/opensandbox/opensandbox/pkg/types"
+)
+
+func commandString(command networkCommand) string {
+ return command.name + " " + strings.Join(command.args, " ")
+}
+
+func TestPublicNetworkPolicyCommands(t *testing.T) {
+ t.Parallel()
+
+ tapName := "qm-tap0000042"
+ cfg := &NetworkConfig{TAPName: tapName, GuestIP: "172.16.0.170"}
+ commands := publicNetworkPolicyCommands(cfg)
+ commandStrings := make([]string, len(commands))
+ for i, command := range commands {
+ commandStrings[i] = commandString(command)
+ }
+
+ input4, egress4, ingress4, input6, egress6, ingress6 := networkPolicyChainNames(tapName)
+ for _, want := range []string{
+ "iptables -I INPUT 1 -i " + tapName + " -j " + input4,
+ "iptables -A " + input4 + " -j DROP",
+ "iptables -I FORWARD 1 -i " + tapName + " -j " + egress4,
+ "iptables -A " + egress4 + " ! -s 172.16.0.170/32 -j DROP",
+ "iptables -A " + egress4 + " -j ACCEPT",
+ "iptables -I FORWARD 1 -o " + tapName + " -j " + ingress4,
+ "iptables -I OUTPUT 1 -o " + tapName + " -j " + ingress4,
+ "iptables -A " + ingress4 + " -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT",
+ "iptables -A " + ingress4 + " -j DROP",
+ "ip6tables -I INPUT 1 -i " + tapName + " -j " + input6,
+ "ip6tables -A " + input6 + " -j DROP",
+ "ip6tables -I FORWARD 1 -i " + tapName + " -j " + egress6,
+ "ip6tables -A " + egress6 + " -j DROP",
+ "ip6tables -I FORWARD 1 -o " + tapName + " -j " + ingress6,
+ "ip6tables -I OUTPUT 1 -o " + tapName + " -j " + ingress6,
+ "ip6tables -A " + ingress6 + " -j DROP",
+ } {
+ if !slices.Contains(commandStrings, want) {
+ t.Errorf("missing firewall command %q", want)
+ }
+ }
+
+ antiSpoof := slices.Index(commandStrings, "iptables -A "+egress4+" ! -s 172.16.0.170/32 -j DROP")
+ publicAccept := slices.Index(commandStrings, "iptables -A "+egress4+" -j ACCEPT")
+ if antiSpoof < 0 || publicAccept < 0 || antiSpoof >= publicAccept {
+ t.Fatalf("anti-spoof rule must precede the public allow rule: %v", commandStrings)
+ }
+ established := slices.Index(commandStrings, "iptables -A "+ingress4+" -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT")
+ inboundDrop := slices.Index(commandStrings, "iptables -A "+ingress4+" -j DROP")
+ if established < 0 || inboundDrop < 0 || established >= inboundDrop {
+ t.Fatalf("established replies must precede the new-inbound drop: %v", commandStrings)
+ }
+ for _, cidr := range publicBlockedIPv4CIDRs {
+ blocked := slices.Index(commandStrings, "iptables -A "+egress4+" -d "+cidr+" -j DROP")
+ if blocked < 0 {
+ t.Errorf("missing blocked destination %s", cidr)
+ } else if blocked <= antiSpoof || blocked >= publicAccept {
+ t.Errorf("blocked destination %s is not between anti-spoof and public allow rules", cidr)
+ }
+ }
+
+ firstJump := len(commands)
+ lastChainRule := -1
+ for i, command := range commands {
+ if len(command.args) < 1 {
+ continue
+ }
+ switch command.args[0] {
+ case "-I":
+ if i < firstJump {
+ firstJump = i
+ }
+ case "-N", "-A":
+ lastChainRule = i
+ }
+ }
+ if lastChainRule < 0 || firstJump == len(commands) || lastChainRule >= firstJump {
+ t.Fatalf("all fail-closed chains must be populated before jumps are installed: %v", commandStrings)
+ }
+
+ cleanupStrings := make([]string, 0, len(networkPolicyCleanupCommands(tapName)))
+ for _, command := range networkPolicyCleanupCommands(tapName) {
+ cleanupStrings = append(cleanupStrings, commandString(command))
+ }
+ for _, want := range []string{
+ "iptables -D INPUT -i " + tapName + " -j " + input4,
+ "iptables -D FORWARD -i " + tapName + " -j " + egress4,
+ "iptables -D FORWARD -o " + tapName + " -j " + ingress4,
+ "iptables -D OUTPUT -o " + tapName + " -j " + ingress4,
+ "ip6tables -D INPUT -i " + tapName + " -j " + input6,
+ "ip6tables -D FORWARD -i " + tapName + " -j " + egress6,
+ "ip6tables -D FORWARD -o " + tapName + " -j " + ingress6,
+ "ip6tables -D OUTPUT -o " + tapName + " -j " + ingress6,
+ "iptables -X " + input4,
+ "iptables -X " + egress4,
+ "iptables -X " + ingress4,
+ "ip6tables -X " + input6,
+ "ip6tables -X " + egress6,
+ "ip6tables -X " + ingress6,
+ } {
+ if !slices.Contains(cleanupStrings, want) {
+ t.Errorf("missing cleanup command %q", want)
+ }
+ }
+}
+
+func TestConfigureIngressPublicIsEgressOnly(t *testing.T) {
+ t.Parallel()
+
+ cfg := &NetworkConfig{HostPort: 12345, GuestPort: 80}
+ hostPort, err := configureIngress(cfg, types.NetworkPolicyPublic, 8787)
+ if err != nil {
+ t.Fatalf("configure public-only ingress: %v", err)
+ }
+ if hostPort != 0 || cfg.HostPort != 0 {
+ t.Fatalf("public-only policy exposed host port: returned=%d config=%d", hostPort, cfg.HostPort)
+ }
+ if cfg.GuestPort != 8787 {
+ t.Fatalf("guest port = %d, want 8787", cfg.GuestPort)
+ }
+ if cfg.DNATRuleAdded {
+ t.Fatal("public-only policy installed DNAT")
+ }
+}
+
+func TestApplyNetworkPolicyValidation(t *testing.T) {
+ t.Parallel()
+
+ var calls []string
+ runner := func(name string, args ...string) error {
+ calls = append(calls, name+" "+strings.Join(args, " "))
+ return nil
+ }
+
+ cfg := &NetworkConfig{TAPName: "qm-tap0000001", GuestIP: "172.16.0.2"}
+ if err := applyNetworkPolicyWithRunner(cfg, types.NetworkPolicyNone, runner); err != nil {
+ t.Fatalf("empty policy: %v", err)
+ }
+ if len(calls) != 0 {
+ t.Fatalf("empty policy ran firewall commands: %v", calls)
+ }
+
+ if err := applyNetworkPolicyWithRunner(cfg, types.NetworkPolicy("private"), runner); err == nil {
+ t.Fatal("unsupported policy unexpectedly succeeded")
+ }
+ if len(calls) != 0 {
+ t.Fatalf("invalid policy ran firewall commands: %v", calls)
+ }
+
+ if err := applyNetworkPolicyWithRunner(&NetworkConfig{TAPName: "bad tap/name", GuestIP: "172.16.0.2"}, types.NetworkPolicyPublic, runner); err == nil {
+ t.Fatal("invalid TAP name unexpectedly succeeded")
+ }
+ if len(calls) != 0 {
+ t.Fatalf("invalid TAP name ran firewall commands: %v", calls)
+ }
+
+ if err := applyNetworkPolicyWithRunner(&NetworkConfig{TAPName: "qm-tap0000001", GuestIP: "not-an-ip"}, types.NetworkPolicyPublic, runner); err == nil {
+ t.Fatal("invalid guest IP unexpectedly succeeded")
+ }
+ if len(calls) != 0 {
+ t.Fatalf("invalid guest IP ran firewall commands: %v", calls)
+ }
+}
+
+func TestApplyPublicNetworkPolicyCleansUpOnFailure(t *testing.T) {
+ t.Parallel()
+
+ tapName := "qm-tap0000001"
+ cfg := &NetworkConfig{TAPName: tapName, GuestIP: "172.16.0.2"}
+ _, egress4, _, _, _, _ := networkPolicyChainNames(tapName)
+ failingCommand := "iptables -A " + egress4 + " -d 169.254.0.0/16 -j DROP"
+ var calls []string
+ failureIndex := -1
+ runner := func(name string, args ...string) error {
+ call := name + " " + strings.Join(args, " ")
+ calls = append(calls, call)
+ if call == failingCommand {
+ failureIndex = len(calls) - 1
+ return errors.New("injected failure")
+ }
+ return nil
+ }
+
+ err := applyNetworkPolicyWithRunner(cfg, types.NetworkPolicyPublic, runner)
+ if err == nil || !strings.Contains(err.Error(), "injected failure") {
+ t.Fatalf("expected injected failure, got %v", err)
+ }
+ if failureIndex < 0 {
+ t.Fatalf("failing command was not run: %v", calls)
+ }
+ cleanupAfterFailure := "iptables -X " + egress4
+ if !slices.Contains(calls[failureIndex+1:], cleanupAfterFailure) {
+ t.Fatalf("policy chains were not cleaned up after failure: %v", calls[failureIndex+1:])
+ }
+}
diff --git a/internal/qemu/reset.go b/internal/qemu/reset.go
index d4a0f8ec..d3952ec8 100644
--- a/internal/qemu/reset.go
+++ b/internal/qemu/reset.go
@@ -219,22 +219,15 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (host
if err != nil {
return 0, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, vm.NetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
return 0, fmt.Errorf("create TAP: %w", err)
}
- freshPort, err := FindFreePort()
+ freshPort, err := configureIngress(netCfg, vm.NetworkPolicy, guestPort)
if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
- return 0, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = freshPort
- netCfg.GuestPort = guestPort
- if err := AddDNAT(netCfg); err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return 0, fmt.Errorf("add DNAT: %w", err)
+ return 0, fmt.Errorf("configure ingress: %w", err)
}
if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
log.Printf("qemu: PowerCycleSandbox %s: metadata DNAT failed: %v", sandboxID, err)
diff --git a/internal/qemu/snapshot.go b/internal/qemu/snapshot.go
index b722f7b8..57e5fa04 100644
--- a/internal/qemu/snapshot.go
+++ b/internal/qemu/snapshot.go
@@ -22,27 +22,28 @@ import (
// SnapshotMeta holds metadata persisted alongside snapshot files.
type SnapshotMeta struct {
- SandboxID string `json:"sandboxId"`
- Network *NetworkConfig `json:"network"`
- GuestCID uint32 `json:"guestCID"`
- GuestMAC string `json:"guestMAC"`
- BootArgs string `json:"bootArgs"`
- RootfsPath string `json:"rootfsPath"`
- WorkspacePath string `json:"workspacePath"`
- CpuCount int `json:"cpuCount"`
- MemoryMB int `json:"memoryMB"`
- BaseMemoryMB int `json:"baseMemoryMB,omitempty"`
- Template string `json:"template"`
- GuestPort int `json:"guestPort"`
- GoldenVersion string `json:"goldenVersion,omitempty"`
- SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`
- SealedTokens map[string]string `json:"sealedTokens,omitempty"`
+ SandboxID string `json:"sandboxId"`
+ Network *NetworkConfig `json:"network"`
+ GuestCID uint32 `json:"guestCID"`
+ GuestMAC string `json:"guestMAC"`
+ BootArgs string `json:"bootArgs"`
+ RootfsPath string `json:"rootfsPath"`
+ WorkspacePath string `json:"workspacePath"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ BaseMemoryMB int `json:"baseMemoryMB,omitempty"`
+ Template string `json:"template"`
+ GuestPort int `json:"guestPort"`
+ NetworkPolicy types.NetworkPolicy `json:"networkPolicy,omitempty"`
+ GoldenVersion string `json:"goldenVersion,omitempty"`
+ SnapshotedAt time.Time `json:"snapshotedAt,omitempty"`
+ SealedTokens map[string]string `json:"sealedTokens,omitempty"`
// SealedNames is the env-var-name → sealed-token index. Persisted alongside
// SealedTokens so secret-store refresh-by-name (UpdateSecretValue) keeps
// working after a wake or migration handoff.
- SealedNames map[string]string `json:"sealedNames,omitempty"`
- EgressAllowlist []string `json:"egressAllowlist,omitempty"`
- TokenHosts map[string][]string `json:"tokenHosts,omitempty"`
+ SealedNames map[string]string `json:"sealedNames,omitempty"`
+ EgressAllowlist []string `json:"egressAllowlist,omitempty"`
+ TokenHosts map[string][]string `json:"tokenHosts,omitempty"`
}
// doHibernate pauses a running VM, saves VM state via QMP migrate, and kicks off
@@ -169,6 +170,7 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointSto
BaseMemoryMB: vm.baseMemoryMB,
Template: vm.Template,
GuestPort: vm.GuestPort,
+ NetworkPolicy: vm.NetworkPolicy,
GoldenVersion: vm.goldenVersion,
SnapshotedAt: time.Now(),
}
@@ -439,27 +441,20 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
return nil, fmt.Errorf("allocate subnet: %w", err)
}
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, meta.NetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
return nil, fmt.Errorf("create TAP: %w", err)
}
- hostPort, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("find free port: %w", err)
- }
- netCfg.HostPort = hostPort
- netCfg.GuestPort = meta.GuestPort
- if netCfg.GuestPort == 0 {
- netCfg.GuestPort = 80
+ guestPort := meta.GuestPort
+ if guestPort == 0 {
+ guestPort = 80
}
-
- if err := AddDNAT(netCfg); err != nil {
+ hostPort, err := configureIngress(netCfg, meta.NetworkPolicy, guestPort)
+ if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("add DNAT: %w", err)
+ return nil, fmt.Errorf("configure ingress: %w", err)
}
if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {
log.Printf("qemu: warning: metadata DNAT failed: %v", err)
@@ -644,18 +639,19 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, c
baseMemoryMB: baseMem,
virtioMemRequestedMB: pluggedMB,
HostPort: hostPort,
- GuestPort: netCfg.GuestPort,
- pid: cmd.Process.Pid,
- cmd: cmd,
- network: netCfg,
- sandboxDir: sandboxDir,
- qmpSockPath: qmpSockPath,
- agentSockPath: agentSockPath,
- qmp: qmpClient,
- guestMAC: guestMAC,
- guestCID: guestCID,
- bootArgs: bootArgs,
- goldenVersion: m.goldenVersion, // set on wake — VM runs on the current worker's base
+ GuestPort: netCfg.GuestPort,
+ NetworkPolicy: meta.NetworkPolicy,
+ pid: cmd.Process.Pid,
+ cmd: cmd,
+ network: netCfg,
+ sandboxDir: sandboxDir,
+ qmpSockPath: qmpSockPath,
+ agentSockPath: agentSockPath,
+ qmp: qmpClient,
+ guestMAC: guestMAC,
+ guestCID: guestCID,
+ bootArgs: bootArgs,
+ goldenVersion: m.goldenVersion, // set on wake — VM runs on the current worker's base
}
// Recompute virtio-mem amount from the meta. Without this the field
// stays at zero on wake, which would (a) make grow deltas under-charge
@@ -803,11 +799,12 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
return nil, fmt.Errorf("parse snapshot-meta.json (sandbox-meta.json fallback): %w", err)
}
meta = SandboxMeta{
- SandboxID: sandboxID,
- Template: snap.Template,
- CpuCount: snap.CpuCount,
- MemoryMB: snap.MemoryMB,
- GuestPort: snap.GuestPort,
+ SandboxID: sandboxID,
+ Template: snap.Template,
+ CpuCount: snap.CpuCount,
+ MemoryMB: snap.MemoryMB,
+ GuestPort: snap.GuestPort,
+ NetworkPolicy: snap.NetworkPolicy,
}
log.Printf("qemu: cold-boot-local %s: sandbox-meta.json absent — recovered config from snapshot-meta.json (template=%q, mem=%dMB, cpu=%d)",
sandboxID, meta.Template, meta.MemoryMB, meta.CpuCount)
@@ -838,28 +835,20 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
if err != nil {
return nil, fmt.Errorf("allocate subnet: %w", err)
}
- if err := CreateTAP(netCfg); err != nil {
+ if err := CreateTAP(netCfg, meta.NetworkPolicy); err != nil {
m.subnets.Release(netCfg.TAPName)
return nil, fmt.Errorf("create TAP: %w", err)
}
- hostPort, err := FindFreePort()
- if err != nil {
- DeleteTAP(netCfg.TAPName)
- m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("find free port: %w", err)
- }
guestPort := meta.GuestPort
if guestPort == 0 {
guestPort = 80
}
- netCfg.HostPort = hostPort
- netCfg.GuestPort = guestPort
-
- if err := AddDNAT(netCfg); err != nil {
+ hostPort, err := configureIngress(netCfg, meta.NetworkPolicy, guestPort)
+ if err != nil {
DeleteTAP(netCfg.TAPName)
m.subnets.Release(netCfg.TAPName)
- return nil, fmt.Errorf("add DNAT: %w", err)
+ return nil, fmt.Errorf("configure ingress: %w", err)
}
// Add metadata service DNAT (169.254.169.254:80 → host:8888)
@@ -937,6 +926,7 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, time
baseMemoryMB: memMB,
HostPort: hostPort,
GuestPort: guestPort,
+ NetworkPolicy: meta.NetworkPolicy,
pid: cmd.Process.Pid,
cmd: cmd,
network: netCfg,
diff --git a/internal/sandbox/interface.go b/internal/sandbox/interface.go
index 2e0aaa6c..b835f9d3 100644
--- a/internal/sandbox/interface.go
+++ b/internal/sandbox/interface.go
@@ -29,6 +29,10 @@ type MigrationSecrets struct {
SealedTokens map[string]string
EgressAllowlist []string
TokenHosts map[string][]string
+ // NetworkPolicy is not a secret, but it follows the same source→target
+ // handoff so the destination installs the sandbox's host firewall before
+ // QEMU starts receiving migration state.
+ NetworkPolicy string
// SealedNames is the env-var-name → sealed-token index. Carried across
// migration so refresh-by-name (UpdateSecretValue) keeps working on the
// destination. Without it, post-migration secret-store updates would
@@ -40,10 +44,10 @@ type MigrationSecrets struct {
// Runtime-agnostic interface for sandbox resource stats.
type SandboxStats struct {
CPUPercent float64 `json:"cpuPercent"`
- MemUsage uint64 `json:"memUsage"` // bytes
- MemLimit uint64 `json:"memLimit"` // bytes
- NetInput uint64 `json:"netInput"` // bytes
- NetOutput uint64 `json:"netOutput"`// bytes
+ MemUsage uint64 `json:"memUsage"` // bytes
+ MemLimit uint64 `json:"memLimit"` // bytes
+ NetInput uint64 `json:"netInput"` // bytes
+ NetOutput uint64 `json:"netOutput"` // bytes
PIDs int `json:"pids"`
}
diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.go
index 623d4e13..418a4b47 100644
--- a/internal/worker/grpc_server.go
+++ b/internal/worker/grpc_server.go
@@ -33,7 +33,7 @@ import (
// GRPCServer implements the SandboxWorker gRPC service for control plane communication.
// LiveMigrator is implemented by VM managers that support live migration (e.g. QEMU).
type LiveMigrator interface {
- PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (incomingAddr string, hostPort int, err error)
+ PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string, networkPolicy types.NetworkPolicy) (incomingAddr string, hostPort int, err error)
PrepareIncomingMigrationWithS3(ctx context.Context, sandboxID, rootfsS3Key, workspaceS3Key string, cpus, memMB, guestPort int, template string, checkpointStore *storage.CheckpointStore, overlayMode bool, sourceGoldenVersion string, secrets sandbox.MigrationSecrets) (incomingAddr string, hostPort int, err error)
PreCopyDrives(ctx context.Context, sandboxID string, checkpointStore *storage.CheckpointStore) (rootfsKey, workspaceKey, goldenVersion string, baseCPU, baseMem, actualMem int, secrets sandbox.MigrationSecrets, err error)
CompleteIncomingMigration(ctx context.Context, sandboxID string) error
@@ -211,6 +211,7 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
MemoryMB: int(req.MemoryMb),
CpuCount: int(req.CpuCount),
NetworkEnabled: &req.NetworkEnabled,
+ NetworkPolicy: types.NetworkPolicy(req.NetworkPolicy),
ImageRef: req.ImageRef,
Port: int(req.Port),
SandboxID: req.SandboxId, // use server-assigned ID if provided
@@ -220,6 +221,9 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReq
SecretEnvs: req.SecretEnvs,
DiskMB: int(req.DiskMb),
}
+ if err := cfg.NetworkPolicy.Validate(); err != nil {
+ return nil, fmt.Errorf("invalid sandbox network policy: %w", err)
+ }
// Warm fork: if checkpoint_id is set, fork from the local checkpoint cache.
// ForkFromCheckpoint uses the local cache directly — no S3 needed.
@@ -1403,6 +1407,7 @@ func (s *GRPCServer) PreCopyDrives(ctx context.Context, req *pb.PreCopyDrivesReq
BaseMemoryMb: int32(baseMem),
BaseCpuCount: int32(baseCPU),
ActualMemoryMb: int32(actualMem),
+ NetworkPolicy: secrets.NetworkPolicy,
}
// Marshal the secrets-proxy session into the proto. Skipped silently
// when the sandbox has no secret store registered (empty maps).
@@ -1424,6 +1429,9 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa
if s.migrator == nil {
return nil, fmt.Errorf("live migration not supported on this worker")
}
+ if err := types.NetworkPolicy(req.NetworkPolicy).Validate(); err != nil {
+ return nil, fmt.Errorf("invalid migration network policy: %w", err)
+ }
// Capacity guard — actual-memory-based. The caller passes the source VM's
// current RSS as TargetMemoryMb (i.e., the physical RAM the migration will
@@ -1448,7 +1456,7 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa
// Unmarshal the secrets-proxy session from the request, if any. The
// orchestrator will have copied this from PreCopyDrives. Empty when
// the sandbox has no secret store.
- var secrets sandbox.MigrationSecrets
+ secrets := sandbox.MigrationSecrets{NetworkPolicy: req.NetworkPolicy}
if len(req.SealedTokens) > 0 {
secrets.SealedTokens = req.SealedTokens
secrets.EgressAllowlist = req.EgressAllowlist
@@ -1475,7 +1483,7 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepa
} else {
addr, hostPort, err = s.migrator.PrepareIncomingMigration(ctx,
req.SandboxId, req.RootfsPath, req.WorkspacePath,
- int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template)
+ int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template, types.NetworkPolicy(req.NetworkPolicy))
}
if err != nil {
return nil, fmt.Errorf("prepare incoming migration: %w", err)
diff --git a/internal/worker/network_policy_test.go b/internal/worker/network_policy_test.go
new file mode 100644
index 00000000..ae5d979f
--- /dev/null
+++ b/internal/worker/network_policy_test.go
@@ -0,0 +1,129 @@
+package worker
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/opensandbox/opensandbox/internal/sandbox"
+ "github.com/opensandbox/opensandbox/internal/storage"
+ "github.com/opensandbox/opensandbox/pkg/types"
+ pb "github.com/opensandbox/opensandbox/proto/worker"
+)
+
+type networkPolicyRecordingManager struct {
+ sandbox.Manager
+ created *types.SandboxConfig
+ forked *types.SandboxConfig
+}
+
+type networkPolicyRecordingMigrator struct {
+ LiveMigrator
+ prepared types.NetworkPolicy
+}
+
+func (m *networkPolicyRecordingMigrator) PreCopyDrives(_ context.Context, _ string, _ *storage.CheckpointStore) (string, string, string, int, int, int, sandbox.MigrationSecrets, error) {
+ return "rootfs", "workspace", "golden", 1, 1024, 512, sandbox.MigrationSecrets{NetworkPolicy: "public"}, nil
+}
+
+func (m *networkPolicyRecordingMigrator) PrepareIncomingMigration(_ context.Context, _, _, _ string, _, _, _ int, _ string, policy types.NetworkPolicy) (string, int, error) {
+ m.prepared = policy
+ return "127.0.0.1:1234", 0, nil
+}
+
+func (m *networkPolicyRecordingManager) Create(_ context.Context, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ m.created = &cfg
+ return &types.Sandbox{
+ ID: "sb-test",
+ Status: types.SandboxStatusRunning,
+ StartedAt: time.Now(),
+ MemoryMB: cfg.MemoryMB,
+ }, nil
+}
+
+func (m *networkPolicyRecordingManager) ForkFromCheckpoint(_ context.Context, _ string, cfg types.SandboxConfig) (*types.Sandbox, error) {
+ m.forked = &cfg
+ return &types.Sandbox{
+ ID: "sb-fork",
+ Status: types.SandboxStatusRunning,
+ StartedAt: time.Now(),
+ MemoryMB: cfg.MemoryMB,
+ }, nil
+}
+
+func TestCreateSandboxPropagatesNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ manager := &networkPolicyRecordingManager{}
+ server := &GRPCServer{manager: manager}
+ if _, err := server.CreateSandbox(context.Background(), &pb.CreateSandboxRequest{
+ SandboxId: "sb-test",
+ MemoryMb: 1024,
+ NetworkPolicy: "public",
+ NetworkEnabled: true,
+ }); err != nil {
+ t.Fatalf("CreateSandbox: %v", err)
+ }
+ if manager.created == nil || manager.created.NetworkPolicy != types.NetworkPolicyPublic {
+ t.Fatalf("manager received network policy %#v", manager.created)
+ }
+}
+
+func TestCheckpointCreatePropagatesNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ manager := &networkPolicyRecordingManager{}
+ server := &GRPCServer{manager: manager}
+ if _, err := server.CreateSandbox(context.Background(), &pb.CreateSandboxRequest{
+ SandboxId: "sb-fork",
+ CheckpointId: "cp-test",
+ MemoryMb: 1024,
+ NetworkPolicy: "public",
+ NetworkEnabled: true,
+ }); err != nil {
+ t.Fatalf("CreateSandbox checkpoint path: %v", err)
+ }
+ if manager.forked == nil || manager.forked.NetworkPolicy != types.NetworkPolicyPublic {
+ t.Fatalf("fork manager received network policy %#v", manager.forked)
+ }
+}
+
+func TestCreateSandboxRejectsUnknownNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ manager := &networkPolicyRecordingManager{}
+ server := &GRPCServer{manager: manager}
+ if _, err := server.CreateSandbox(context.Background(), &pb.CreateSandboxRequest{
+ SandboxId: "sb-test",
+ NetworkPolicy: "private",
+ }); err == nil {
+ t.Fatal("CreateSandbox unexpectedly accepted an unknown policy")
+ }
+ if manager.created != nil || manager.forked != nil {
+ t.Fatal("invalid policy reached the sandbox manager")
+ }
+}
+
+func TestMigrationPropagatesNetworkPolicy(t *testing.T) {
+ t.Parallel()
+
+ migrator := &networkPolicyRecordingMigrator{}
+ server := &GRPCServer{migrator: migrator}
+ preCopy, err := server.PreCopyDrives(context.Background(), &pb.PreCopyDrivesRequest{SandboxId: "sb-test"})
+ if err != nil {
+ t.Fatalf("PreCopyDrives: %v", err)
+ }
+ if preCopy.NetworkPolicy != "public" {
+ t.Fatalf("pre-copy network policy = %q, want public", preCopy.NetworkPolicy)
+ }
+
+ if _, err := server.PrepareMigrationIncoming(context.Background(), &pb.PrepareMigrationIncomingRequest{
+ SandboxId: "sb-test",
+ NetworkPolicy: preCopy.NetworkPolicy,
+ }); err != nil {
+ t.Fatalf("PrepareMigrationIncoming: %v", err)
+ }
+ if migrator.prepared != types.NetworkPolicyPublic {
+ t.Fatalf("prepared policy = %q, want public", migrator.prepared)
+ }
+}
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 78b87ec6..eef33085 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -24,23 +24,23 @@ const (
// Sandbox represents a running sandbox instance.
type Sandbox struct {
- ID string `json:"sandboxID"`
- Template string `json:"templateID,omitempty"`
- Alias string `json:"alias,omitempty"`
- ClientID string `json:"clientID,omitempty"`
- Status SandboxStatus `json:"status"`
- StartedAt time.Time `json:"startedAt"`
- EndAt time.Time `json:"endAt"`
- Metadata map[string]string `json:"metadata,omitempty"`
- CpuCount int `json:"cpuCount"`
- MemoryMB int `json:"memoryMB"`
- MachineID string `json:"machineID,omitempty"`
+ ID string `json:"sandboxID"`
+ Template string `json:"templateID,omitempty"`
+ Alias string `json:"alias,omitempty"`
+ ClientID string `json:"clientID,omitempty"`
+ Status SandboxStatus `json:"status"`
+ StartedAt time.Time `json:"startedAt"`
+ EndAt time.Time `json:"endAt"`
+ Metadata map[string]string `json:"metadata,omitempty"`
+ CpuCount int `json:"cpuCount"`
+ MemoryMB int `json:"memoryMB"`
+ MachineID string `json:"machineID,omitempty"`
// ConnectURL and Token are currently unused by SDKs. All data-plane traffic
// flows through the control plane's SandboxAPIProxy, which proxies to workers
// over the internal VPC network. Direct worker access support coming in a future release.
- ConnectURL string `json:"connectURL,omitempty"`
- Token string `json:"token,omitempty"`
- HostPort int `json:"hostPort,omitempty"` // Mapped host port for the sandbox's container port
+ ConnectURL string `json:"connectURL,omitempty"`
+ Token string `json:"token,omitempty"`
+ HostPort int `json:"hostPort,omitempty"` // Mapped host port for the sandbox's container port
// PreviewAuthToken is the plaintext bearer token for the sandbox's
// preview URL, returned exactly once on create when previewAuth was
// requested. Empty otherwise. Mirrors the SDK field by the same name.
@@ -61,7 +61,7 @@ type SandboxPreviewAuth struct {
// Token is "auto" (or omitted) to have the server generate a 256-bit
// random token, or an explicit string of at least 16 chars to bring
// your own. Echoed back as Sandbox.PreviewAuthToken on success.
- Token string `json:"token,omitempty"`
+ Token string `json:"token,omitempty"`
}
// SandboxConfig is the request body for creating a sandbox.
@@ -69,10 +69,10 @@ type SandboxConfig struct {
Template string `json:"templateID,omitempty"`
Alias string `json:"alias,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
- Timeout int `json:"timeout,omitempty"` // seconds, default 300
- CpuCount int `json:"cpuCount,omitempty"` // default 1
- MemoryMB int `json:"memoryMB,omitempty"` // default 256
- DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)
+ Timeout int `json:"timeout,omitempty"` // seconds, default 300
+ CpuCount int `json:"cpuCount,omitempty"` // default 1
+ MemoryMB int `json:"memoryMB,omitempty"` // default 256
+ DiskMB int `json:"diskMB,omitempty"` // workspace disk in MB (default 20480)
Envs map[string]string `json:"envs,omitempty"`
PreviewAuth *SandboxPreviewAuth `json:"previewAuth,omitempty"`
// Webhooks registers sandbox lifecycle webhooks atomically with the
@@ -80,11 +80,18 @@ type SandboxConfig struct {
// separate webhooks.create could know the sandbox id). See
// .agents/work/sandbox-lifecycle-webhooks.md.
Webhooks []SandboxWebhookSpec `json:"webhooks,omitempty"`
- Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)
+ Port int `json:"port,omitempty"` // container port to expose via subdomain (default 80)
// NetworkEnabled is a pointer so we can distinguish "unset" from
// "explicitly false". Unset defaults to true (see IsNetworkEnabled).
- NetworkEnabled *bool `json:"networkEnabled,omitempty"`
- ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates
+ NetworkEnabled *bool `json:"networkEnabled,omitempty"`
+ // NetworkPolicy is an optional host-enforced network boundary. "public"
+ // permits ordinary public IPv4 egress (including DNS), disables inbound
+ // ports, and denies guest access to the worker host, private/service
+ // networks, link-local metadata, CGNAT, multicast, reserved ranges, and
+ // spoofed-source traffic. It is enforced outside the guest and cannot be
+ // disabled by repository code changing proxy environment vars.
+ NetworkPolicy NetworkPolicy `json:"networkPolicy,omitempty"`
+ ImageRef string `json:"imageRef,omitempty"` // resolved ECR URI for custom templates
// Sandbox snapshot template: S3 keys for rootfs and workspace drives.
// When set, the sandbox boots from these drives instead of the standard base image.
TemplateRootfsKey string `json:"templateRootfsKey,omitempty"`
@@ -131,6 +138,22 @@ type SandboxConfig struct {
SecretEnvs map[string]string `json:"-"`
}
+type NetworkPolicy string
+
+const (
+ NetworkPolicyNone NetworkPolicy = ""
+ NetworkPolicyPublic NetworkPolicy = "public"
+)
+
+func (p NetworkPolicy) Validate() error {
+ switch p {
+ case NetworkPolicyNone, NetworkPolicyPublic:
+ return nil
+ default:
+ return fmt.Errorf("networkPolicy must be empty or %q", NetworkPolicyPublic)
+ }
+}
+
// ResourceTier defines an allowed memory/CPU combination.
type ResourceTier struct {
MemoryMB int
diff --git a/pkg/types/sandbox_test.go b/pkg/types/sandbox_test.go
new file mode 100644
index 00000000..a800691b
--- /dev/null
+++ b/pkg/types/sandbox_test.go
@@ -0,0 +1,16 @@
+package types
+
+import "testing"
+
+func TestNetworkPolicyValidate(t *testing.T) {
+ t.Parallel()
+
+ for _, policy := range []NetworkPolicy{NetworkPolicyNone, NetworkPolicyPublic} {
+ if err := policy.Validate(); err != nil {
+ t.Errorf("Validate(%q): %v", policy, err)
+ }
+ }
+ if err := NetworkPolicy("private").Validate(); err == nil {
+ t.Fatal("unsupported network policy unexpectedly validated")
+ }
+}
diff --git a/proto/worker/worker.pb.go b/proto/worker/worker.pb.go
index 47caf9da..49508cee 100644
--- a/proto/worker/worker.pb.go
+++ b/proto/worker/worker.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
-// protoc v7.35.0
+// protoc v5.29.3
// source: proto/worker/worker.proto
package worker
@@ -90,8 +90,12 @@ type CreateSandboxRequest struct {
SecretAllowedHosts map[string]string `protobuf:"bytes,14,rep,name=secret_allowed_hosts,json=secretAllowedHosts,proto3" json:"secret_allowed_hosts,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
// Env vars resolved from a SecretStore. Sealed by the worker's secrets proxy
// before injection into the VM. Disjoint from `envs` (which is plaintext).
- SecretEnvs map[string]string `protobuf:"bytes,15,rep,name=secret_envs,json=secretEnvs,proto3" json:"secret_envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- DiskMb int32 `protobuf:"varint,16,opt,name=disk_mb,json=diskMb,proto3" json:"disk_mb,omitempty"` // workspace disk size in MB (0 = default 20GB)
+ SecretEnvs map[string]string `protobuf:"bytes,15,rep,name=secret_envs,json=secretEnvs,proto3" json:"secret_envs,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ DiskMb int32 `protobuf:"varint,16,opt,name=disk_mb,json=diskMb,proto3" json:"disk_mb,omitempty"` // workspace disk size in MB (0 = default 20GB)
+ // Host-enforced egress-only boundary. Empty preserves normal sandbox
+ // networking; "public" disables inbound ports and blocks guest→host,
+ // private, link-local, metadata, reserved, and spoofed-source traffic.
+ NetworkPolicy string `protobuf:"bytes,17,opt,name=network_policy,json=networkPolicy,proto3" json:"network_policy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -238,6 +242,13 @@ func (x *CreateSandboxRequest) GetDiskMb() int32 {
return 0
}
+func (x *CreateSandboxRequest) GetNetworkPolicy() string {
+ if x != nil {
+ return x.NetworkPolicy
+ }
+ return ""
+}
+
type CreateSandboxResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
SandboxId string `protobuf:"bytes,1,opt,name=sandbox_id,json=sandboxId,proto3" json:"sandbox_id,omitempty"`
@@ -3518,6 +3529,7 @@ type PreCopyDrivesResponse struct {
// migration. Without it, post-migration secret-store updates would silently
// miss because the destination's session has no name → token mapping.
SealedNames map[string]string `protobuf:"bytes,10,rep,name=sealed_names,json=sealedNames,proto3" json:"sealed_names,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ NetworkPolicy string `protobuf:"bytes,11,opt,name=network_policy,json=networkPolicy,proto3" json:"network_policy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -3622,6 +3634,13 @@ func (x *PreCopyDrivesResponse) GetSealedNames() map[string]string {
return nil
}
+func (x *PreCopyDrivesResponse) GetNetworkPolicy() string {
+ if x != nil {
+ return x.NetworkPolicy
+ }
+ return ""
+}
+
// HostList is a wrapper because proto3 maps cannot have a repeated value type.
type HostList struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -3693,7 +3712,8 @@ type PrepareMigrationIncomingRequest struct {
// registers it with Status=paused (so the usage_ticker never bills it) and the
// scaler re-stops + reclaims its RAM via PauseAfterMigration once the transfer
// completes. Used to move a paused box off a draining worker without billing.
- ArrivePaused bool `protobuf:"varint,17,opt,name=arrive_paused,json=arrivePaused,proto3" json:"arrive_paused,omitempty"`
+ ArrivePaused bool `protobuf:"varint,17,opt,name=arrive_paused,json=arrivePaused,proto3" json:"arrive_paused,omitempty"`
+ NetworkPolicy string `protobuf:"bytes,18,opt,name=network_policy,json=networkPolicy,proto3" json:"network_policy,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -3847,6 +3867,13 @@ func (x *PrepareMigrationIncomingRequest) GetArrivePaused() bool {
return false
}
+func (x *PrepareMigrationIncomingRequest) GetNetworkPolicy() string {
+ if x != nil {
+ return x.NetworkPolicy
+ }
+ return ""
+}
+
type PrepareMigrationIncomingResponse struct {
state protoimpl.MessageState `protogen:"open.v1"`
IncomingAddr string `protobuf:"bytes,1,opt,name=incoming_addr,json=incomingAddr,proto3" json:"incoming_addr,omitempty"` // TCP address for source to migrate to (e.g. "10.100.1.7:49152")
@@ -4267,7 +4294,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptor
const file_proto_worker_worker_proto_rawDesc = "" +
"\n" +
- "\x19proto/worker/worker.proto\x12\x06worker\"\x80\a\n" +
+ "\x19proto/worker/worker.proto\x12\x06worker\"\xa7\a\n" +
"\x14CreateSandboxRequest\x12\x1a\n" +
"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +
"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +
@@ -4287,7 +4314,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x14secret_allowed_hosts\x18\x0e \x03(\v24.worker.CreateSandboxRequest.SecretAllowedHostsEntryR\x12secretAllowedHosts\x12M\n" +
"\vsecret_envs\x18\x0f \x03(\v2,.worker.CreateSandboxRequest.SecretEnvsEntryR\n" +
"secretEnvs\x12\x17\n" +
- "\adisk_mb\x18\x10 \x01(\x05R\x06diskMb\x1a7\n" +
+ "\adisk_mb\x18\x10 \x01(\x05R\x06diskMb\x12%\n" +
+ "\x0enetwork_policy\x18\x11 \x01(\tR\rnetworkPolicy\x1a7\n" +
"\tEnvsEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aE\n" +
@@ -4548,7 +4576,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x18SetSandboxLimitsResponse\";\n" +
"\x14PreCopyDrivesRequest\x12\x1d\n" +
"\n" +
- "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xee\x05\n" +
+ "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\x95\x06\n" +
"\x15PreCopyDrivesResponse\x12\x1d\n" +
"\n" +
"rootfs_key\x18\x01 \x01(\tR\trootfsKey\x12#\n" +
@@ -4562,7 +4590,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\vtoken_hosts\x18\t \x03(\v2-.worker.PreCopyDrivesResponse.TokenHostsEntryR\n" +
"tokenHosts\x12Q\n" +
"\fsealed_names\x18\n" +
- " \x03(\v2..worker.PreCopyDrivesResponse.SealedNamesEntryR\vsealedNames\x1a?\n" +
+ " \x03(\v2..worker.PreCopyDrivesResponse.SealedNamesEntryR\vsealedNames\x12%\n" +
+ "\x0enetwork_policy\x18\v \x01(\tR\rnetworkPolicy\x1a?\n" +
"\x11SealedTokensEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aO\n" +
@@ -4573,7 +4602,7 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\" \n" +
"\bHostList\x12\x14\n" +
- "\x05hosts\x18\x01 \x03(\tR\x05hosts\"\x85\b\n" +
+ "\x05hosts\x18\x01 \x03(\tR\x05hosts\"\xac\b\n" +
"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +
"\n" +
"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +
@@ -4596,7 +4625,8 @@ const file_proto_worker_worker_proto_rawDesc = "" +
"\vtoken_hosts\x18\x0f \x03(\v27.worker.PrepareMigrationIncomingRequest.TokenHostsEntryR\n" +
"tokenHosts\x12[\n" +
"\fsealed_names\x18\x10 \x03(\v28.worker.PrepareMigrationIncomingRequest.SealedNamesEntryR\vsealedNames\x12#\n" +
- "\rarrive_paused\x18\x11 \x01(\bR\farrivePaused\x1a?\n" +
+ "\rarrive_paused\x18\x11 \x01(\bR\farrivePaused\x12%\n" +
+ "\x0enetwork_policy\x18\x12 \x01(\tR\rnetworkPolicy\x1a?\n" +
"\x11SealedTokensEntry\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1aO\n" +
diff --git a/proto/worker/worker.proto b/proto/worker/worker.proto
index f2ce3020..deb22b45 100644
--- a/proto/worker/worker.proto
+++ b/proto/worker/worker.proto
@@ -110,6 +110,10 @@ message CreateSandboxRequest {
// before injection into the VM. Disjoint from `envs` (which is plaintext).
map<string, string> secret_envs = 15;
int32 disk_mb = 16; // workspace disk size in MB (0 = default 20GB)
+ // Host-enforced egress-only boundary. Empty preserves normal sandbox
+ // networking; "public" disables inbound ports and blocks guest→host,
+ // private, link-local, metadata, reserved, and spoofed-source traffic.
+ string network_policy = 17;
}
message CreateSandboxResponse {
@@ -469,6 +473,7 @@ message PreCopyDrivesResponse {
// migration. Without it, post-migration secret-store updates would silently
// miss because the destination's session has no name → token mapping.
map<string, string> sealed_names = 10;
+ string network_policy = 11;
}
// HostList is a wrapper because proto3 maps cannot have a repeated value type.
@@ -502,6 +507,7 @@ message PrepareMigrationIncomingRequest {
// scaler re-stops + reclaims its RAM via PauseAfterMigration once the transfer
// completes. Used to move a paused box off a draining worker without billing.
bool arrive_paused = 17;
+ string network_policy = 18;
}
message PrepareMigrationIncomingResponse {
diff --git a/proto/worker/worker_grpc.pb.go b/proto/worker/worker_grpc.pb.go
index 7c258a5e..aed9320c 100644
--- a/proto/worker/worker_grpc.pb.go
+++ b/proto/worker/worker_grpc.pb.go
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.2
-// - protoc v7.35.0
+// - protoc v5.29.3
// source: proto/worker/worker.proto
package worker
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index f3cd7de3..c6c0dfd7 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.12.1",
+ "version": "0.12.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.12.1",
+ "version": "0.12.2",
"license": "MIT",
"devDependencies": {
"@types/node": "^25.3.0",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 4f797612..77b6583b 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.12.1",
+ "version": "0.12.2",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/sandbox.test.ts b/sdks/typescript/src/sandbox.test.ts
index 09672f9e..bbfe997b 100644
--- a/sdks/typescript/src/sandbox.test.ts
+++ b/sdks/typescript/src/sandbox.test.ts
@@ -71,3 +71,65 @@ describe("Sandbox checkpoint requests", () => {
});
});
});
+
+describe("Sandbox public network policy", () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("sends public policy on a fresh create", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify({ sandboxID: "sb_1", status: "running" }), {
+ status: 201,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+
+ await Sandbox.create({
+ apiUrl: "https://api.example.test",
+ apiKey: "osb_test",
+ networkPolicy: "public",
+ });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init?.body as string)).toMatchObject({ networkPolicy: "public" });
+ });
+
+ it("sends public policy through named-snapshot create", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(
+ 'event: result\ndata: {"sandboxID":"sb_2","status":"running"}\n\n',
+ { status: 201, headers: { "content-type": "text/event-stream" } },
+ ),
+ );
+
+ await Sandbox.create({
+ apiUrl: "https://api.example.test",
+ snapshot: "flue-builder",
+ networkPolicy: "public",
+ });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init?.body as string)).toMatchObject({
+ snapshot: "flue-builder",
+ networkPolicy: "public",
+ });
+ });
+
+ it("sends public policy on direct checkpoint create", async () => {
+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response(JSON.stringify({ sandboxID: "sb_3", status: "running" }), {
+ status: 201,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+
+ await Sandbox.createFromCheckpoint("cp_1", {
+ apiUrl: "https://api.example.test",
+ networkPolicy: "public",
+ });
+
+ const [, init] = fetchMock.mock.calls[0];
+ expect(JSON.parse(init?.body as string)).toEqual({ networkPolicy: "public" });
+ });
+});
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 11370ba0..4ddbbaed 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -39,6 +39,13 @@ export interface SandboxOpts {
diskMB?: number;
/** Secret store name — resolves encrypted secrets and egress allowlist. */
secretStore?: string;
+ /**
+ * Host-enforced public-Internet-only, egress-only networking. Blocks inbound
+ * preview/public ports plus guest access to the worker host, private/service
+ * networks, link-local metadata, CGNAT, multicast, and reserved ranges even
+ * if guest code changes proxy settings.
+ */
+ networkPolicy?: "public";
/** Declarative image definition. The server builds and caches it as a checkpoint. */
image?: Image;
/** Name of a pre-built snapshot to create the sandbox from. */
@@ -350,6 +357,7 @@ export class Sandbox {
if (opts.memoryMB != null) body.memoryMB = opts.memoryMB;
if (opts.diskMB != null) body.diskMB = opts.diskMB;
if (opts.secretStore) body.secretStore = opts.secretStore;
+ if (opts.networkPolicy) body.networkPolicy = opts.networkPolicy;
if (opts.image) body.image = opts.image.toJSON();
if (opts.snapshot) body.snapshot = opts.snapshot;
if (opts.webhooks?.length) body.webhooks = opts.webhooks;
@@ -785,7 +793,7 @@ export class Sandbox {
(this as any).pty = new Pty(this.apiUrl, this.apiKey, this.sandboxId, "");
}
- static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout" | "envs" | "secretStore"> = {}): Promise<Sandbox> {
+ static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout" | "envs" | "secretStore" | "networkPolicy"> = {}): Promise<Sandbox> {
const apiUrl = resolveApiUrl(opts.apiUrl ?? process.env.OPENCOMPUTER_API_URL ?? "https://app.opencomputer.dev");
const apiKey = opts.apiKey ?? process.env.OPENCOMPUTER_API_KEY ?? "";
@@ -793,6 +801,7 @@ export class Sandbox {
if (opts.timeout != null) body.timeout = opts.timeout;
if (opts.envs) body.envs = opts.envs;
if (opts.secretStore) body.secretStore = opts.secretStore;
+ if (opts.networkPolicy) body.networkPolicy = opts.networkPolicy;
const resp = await fetch(`${apiUrl}/sandboxes/from-checkpoint/${checkpointId}`, {
method: "POST",