Secure, Fast, and Extensible Sandbox runtime for AI agents.
Merge main into Fast Sandbox subject transition fix
leo peinb69132601549
diff --cc components/egress/fastsandbox_actions.goindex dd1eeccf5,b45cb82f8..5e291766c--- a/components/egress/fastsandbox_actions.go+++ b/components/egress/fastsandbox_actions.go@@@ -153,163 -170,96 +169,191 @@@ func (s *fastSandboxPolicyServer) dispareturn s.applyVaultExport(env)case actionhandler.OperationVaultImport:return s.applyVaultImport(env)+ case actionhandler.OperationPolicyExport:+ return s.applyPolicyExport(env)+ case actionhandler.OperationPolicyImport:+ return s.applyPolicyImport(env)+ case actionhandler.OperationSetBinding:+ if !env.Binding.IsRemoval() {+ input, err := env.Binding.InputString()+ if err != nil {+ return http.StatusBadRequest, err+ }+ pol, err = policy.ParsePolicy(input)+ if err != nil {+ return http.StatusBadRequest, fmt.Errorf("invalid binding input policy: %v", err)+ }+ }+ case actionhandler.OperationLifecycleHook, actionhandler.OperationRemoveBinding:default:- // Unreachable: ParseEnvelope validated the operation.return http.StatusBadRequest, fmt.Errorf("unknown operation %q", env.Operation)}+ release, err := s.acquireAction(ctx)+ if err != nil {+ return http.StatusServiceUnavailable, fmt.Errorf("action canceled: %w", err)+ }+ defer release()+ switch env.Operation {+ case actionhandler.OperationSetBinding:+ return s.applySetBinding(ctx, env, pol)+ case actionhandler.OperationLifecycleHook:+ return s.applyLifecycleHook(env)+ default:+ return s.applyRemoveBinding(env)+ }}-// applySetBinding registers the subject deny-first and stores the binding-// input. The policy is parsed BEFORE any state mutation so a permanently-// invalid input (400) can never leave the subject half-registered.-func (s *fastSandboxPolicyServer) applySetBinding(env *actionhandler.Envelope) (int, error) {+// applySetBinding holds the action gate. The policy has already been parsed;+// same-fence network rejection precedes every effect, including Vault reload.+func (s *fastSandboxPolicyServer) applySetBinding(ctx context.Context, env *actionhandler.Envelope, pol *policy.NetworkPolicy) (int, error) {subj := subject.FromSandboxUID(env.Sandbox.UID)fence := subject.FromRevision(env)att := env.Network()- var pol *policy.NetworkPolicy- if !env.Binding.IsRemoval() {- input, err := env.Binding.InputString()- if err != nil {- return http.StatusBadRequest, err++ // Serialize registration and rebind cleanup with policy and vault commits.++ s.policyCommitMu.Lock()++ defer s.policyCommitMu.Unlock()+ s.mu.Lock()+ // Waiting for an in-progress Vault commit may outlive the request too.+ if err := s.actionCanceled(ctx); err != nil {+ s.mu.Unlock()+ return http.StatusServiceUnavailable, fmt.Errorf("action canceled: %w", err)+ }+ old, registered := s.reg.Fence(subj)+ oldAtt, knownNetwork := s.subjAtt[subj]+ knownNetwork = knownNetwork && oldAtt.IP.IsValid()+ token := s.rebinds[subj]+ // A previous attempt may have purged bookkeeping before old-IP removal+ // failed. Its token still carries the actual old network for comparisons.+ if !knownNetwork && token != nil && registered && token.old.Matches(old) && token.oldNetwork.IP.IsValid() {+ oldAtt, knownNetwork = token.oldNetwork, true+ }+ if token == nil && registered && old.Matches(fence) && !knownNetwork {+ if state, _ := s.reg.Get(subj); state == subject.StateActive {+ // Successful registration always records an attempt before becoming+ // active. Missing metadata here is an internal inconsistency, not a+ // reason to mutate a live subject or acknowledge an uninstalled update.+ s.mu.Unlock()+ return http.StatusInternalServerError, fmt.Errorf("active subject %s has no registered network", subj)}- pol, err = policy.ParsePolicy(input)- if err != nil {- return http.StatusBadRequest, fmt.Errorf("invalid binding input policy: %v", err)+ }+ // A null binding may omit attachment only for its own known identity.+ // Never register a new fence using the previous instance's network.+ if env.Binding.IsRemoval() && env.Attachment == nil {+ if token != nil && token.expectedNew.Matches(fence) && token.newNetwork.IP.IsValid() {+ att = token.newNetwork+ } else if token == nil && registered && old.Matches(fence) {+ att = oldAtt+ } else if registered || token != nil {+ s.mu.Unlock()+ return http.StatusBadRequest, fmt.Errorf("attachment required for registration identity")}}- // The whole mutation holds policyCommitMu — rebind purge, registration,- // and seed/apply are one unit against relay commits and hooks.- // Otherwise a predecessor-identity relay write could straddle the- // fence flip and its reg.ApplyPolicy would activate the successor- // under the predecessor's policy. Lock order: policyCommitMu →- // registry → s.mu.- s.policyCommitMu.Lock()- defer s.policyCommitMu.Unlock()-- // A fence change is a rebind: discard ALL prior per-subject state. The- // registry drops its entry inside RegisterAndEnforce; the vault slice- // and the recorded policy must go too (memory + persisted files), or the- // old instance's credentials and policy would survive into the- // successor's flows.- if old, ok := s.reg.Fence(subj); ok && !old.Matches(fence) {+ if (token != nil && token.expectedNew.Matches(fence) && !sameBindingNetwork(token.newNetwork, att)) ||+ (registered && old.Matches(fence) && knownNetwork && !sameBindingNetwork(oldAtt, att)) {+ s.mu.Unlock()+ return http.StatusConflict, fmt.Errorf("same-fence network change for subject %s", subj)+ }+ if token != nil && !token.expectedNew.Matches(fence) {+ // The latest valid, uncanceled SET supersedes an abandoned intent. Its+ // new token guards a full reset of actual residual state, even when the+ // previous registration failed before publishing any registry entry.+ token = &subjectRebind{old: old, expectedNew: fence, oldNetwork: oldAtt, newNetwork: att, needsReset: true}+ s.rebinds[subj] = token+ } else if token == nil && registered && !old.Matches(fence) {+ token = &subjectRebind{old: old, expectedNew: fence, oldNetwork: oldAtt, newNetwork: att, removeOld: !knownNetwork || oldAtt.IP != att.IP}+ s.rebinds[subj] = token+ }+ needsReset := token != nil && token.needsReset+ s.mu.Unlock()+ defer s.logPendingRebind(subj, token)+ if token != nil {+ if needsReset {+ if err := s.unloadEnforcement(subj); err != nil {+ return http.StatusInternalServerError, fmt.Errorf("superseded registration reset: %w", err)+ }+ s.reg.Unregister(subj)+ s.mu.Lock()+ s.dropSubjectStateLocked(subj) // preserve this exact token through C publication+ token.needsReset = false+ token.oldRemoved = true+ token.purged = true+ s.mu.Unlock()+ }s.mu.Lock()- s.dropVault(subj)- delete(s.policies, subj)- s.purgePolicyFile(subj)+ if !token.purged {+ s.dropSubjectStateLocked(subj)+ token.purged = true+ }+ removeOld := token.removeOld && !token.oldRemoveds.mu.Unlock()- log.Infof("subject %s: rebind (%s -> %s), vault slice and policy record purged", subj, old.RuntimeInstanceID, fence.RuntimeInstanceID)- }- // Egress-restart recovery (OSEP-0022 stage 2): a subject with no live- // vault slice reloads its persisted file here, fenced by the full runtime- // identity. The recorded policy reloads the same way — the committed file- // is authoritative over the replayed binding input. These run BEFORE the- // deny-first install so no interception entry can materialize an empty- // slice ahead of the reload. A removal binding skips the reloads: with no- // policy to revalidate against, the files stay fenced on disk until the- // next registration or terminal purge.+ if removeOld {+ nftCtx, cancel := context.WithTimeout(s.ctx, 30*time.Second)+ err := s.nft.Remove(nftCtx, subj)+ cancel()+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("old network removal: %w", err)+ }+ s.mu.Lock()+ token.oldRemoved = true+ s.mu.Unlock()+ }+ } else if registered && !knownNetwork {+ // Legacy/unknown attempt metadata cannot prove reset will remove old IP+ // dispatch. A conservative Remove is retryable; do not invent a network.+ if err := s.unloadEnforcement(subj); err != nil {+ return http.StatusInternalServerError, fmt.Errorf("unknown network removal: %w", err)+ }+ if err := s.reg.UnsetPolicy(subj); err != nil {+ return http.StatusInternalServerError, err+ }+ }if !env.Binding.IsRemoval() {- s.rehydrateVaultReload(subj, fence, pol)+ // Policy first: its reload result is the validation policy for the+ // vault reload (a template clone's vault hosts are covered by the+ // landed template policy, not by the replayed bootstrap input). A+ // degraded policy record degrades the VAULT with it (fail-closed,+ // file kept) instead of seeding the deny fallback — a deny-seeded+ // vault validation would quarantine a healthy vault.+ seed, policyDegraded := s.rehydratePolicyReload(subj, fence)+ if seed == nil {+ seed = pol+ }+ s.rehydrateVaultReload(subj, fence, seed, policyDegraded)}+ // Record even failed first installs: partial kernel effects otherwise have+ // no network identity for a later same-fence retry or changed-fence rebind.+ s.recordBindingState(subj, att)+ var victims []subject.Subjectstate, err := s.reg.RegisterAndEnforce(subj, subject.SubjectKey{SourceIP: att.IP}, fence, func() error {return s.OnRegistered(subj, att)- }, s.takeoverStaleSubject)+ }, func(stale subject.Subject) error {+ victims = append(victims, stale)+ return s.takeoverStaleSubject(stale)+ })+ // Callback teardown never takes mu. Only purge actual evictions after the+ // registry lock is released, even if successor enforcement failed. The+ // action gate prevents a victim being re-registered before this purge.+ for _, victim := range victims {+ if _, exists := s.reg.Fence(victim); !exists {+ s.dropSubjectState(victim)+ }+ }if err != nil {return http.StatusInternalServerError, fmt.Errorf("deny-first install: %w", err)}- s.recordBindingState(subj, att, fence)++ s.recordRegisteredFence(subj, fence)if env.Binding.IsRemoval() {+ // Binding removed from a still-live sandbox: drop the pending policy+ // (a re-added binding gets a fresh input — never apply the removed+ // binding's policy to a policy-less subject) and purge the recorded+ // policy, so deny-first is also the durable state.s.clearPendingPolicy(subj)+ if err := s.clearPolicyRecordLocked(subj); err != nil {+ // The durable removal did not confirm: fail the action so the+ // Fastlet's retry re-runs the purge/tombstone instead of acking+ // a removal whose file may still carry the removed policy.+ return http.StatusInternalServerError, fmt.Errorf("policy record removal: %w", err)+ }if state == subject.StateActive {if err := s.revertToDenyFirst(subj, att); err != nil {return http.StatusInternalServerError, err@@@ -319,14 -268,12 +363,13 @@@log.Infof("subject %s: binding removed (deny-first)", subj)return http.StatusOK, nil}- if state == subject.StateActive {- if err := s.applyPolicy(subj, pol); err != nil {- return http.StatusInternalServerError, fmt.Errorf("policy apply: %w", err)- }- } else {- s.storePendingPolicy(subj, pol)+ // Install the binding policy (or honor the file-backed record that+ // supersedes it) through the policy commit protocol.+ if err := s.applyBindingPolicyLocked(subj, fence, pol, state == subject.StateActive); err != nil {+ log.Errorf("subject %s: binding policy commit failed: %v", subj, err)+ return http.StatusInternalServerError, fmt.Errorf("binding policy commit: %w", err)}+ s.finishRebind(subj, token)log.Infof("subject %s: SET_BINDING applied (state=%s)", subj, state)return http.StatusOK, nil}@@@ -360,10 -301,30 +403,28 @@@ func (s *fastSandboxPolicyServer) applycase constants.HookRuntimeReady:return http.StatusOK, nilcase constants.HookDataPlaneReady:- // Peek, do not consume: a transient nft failure must leave the- // pending policy in place so the Fastlet's retry of the same Hook- // succeeds instead of 409-ing forever with the subject deny-first.- pol := s.pendingPolicy(subj)+ // Serialized with the policy relay commits (policyCommitMu): a+ // relay write that passed its guards before this hook must either+ // land first (the activation below then applies the relayed+ // pending policy) or after (its apply-time state re-read then sees+ // Active and updates enforcement in place) — it can never land+ // after the activation as a pending-only write that nothing will+ // ever consume.+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()+ // Fence re-validation AND the pending peek under one s.mu hold+ // (policyCommitMu → s.mu, the established order): fenceMatchesLocked- // reads subjFence, which terminal cleanup deletes under s.mu without- // policyCommitMu (dropSubjectState is called under the registry write- // lock from takeover) — an unsynchronized read here would race that- // delete. The pre-lock fence check above cannot see a rebind or++ // reads subjFence, which terminal cleanup deletes under s.mu. An++ // unsynchronized read here would race that delete. The pre-lock fence check above cannot see a rebind or+ // removal that completes while this Hook waits on policyCommitMu —+ // a stale Hook must never activate the successor.+ s.mu.Lock()+ stale := !s.fenceMatchesLocked(subj, fence)+ pol := s.pendingPolicies[subj]+ s.mu.Unlock()+ if stale {+ return http.StatusConflict, fmt.Errorf("stale %s (fence mismatch) for subject %s", env.Hook.Name, subj)+ }if pol == nil {// No pending policy: SET_BINDING has not landed (protocol// ordering violation) or the binding was removed. Fail closed —diff --cc components/egress/fastsandbox_policy.goindex 000000000,6da93af89..b942826d2mode 000000,100644..100644--- a/components/egress/fastsandbox_policy.go+++ b/components/egress/fastsandbox_policy.go@@@ -1,0 -1,402 +1,417 @@@+ // Copyright 2026 The OpenSandbox Authors+ //+ // Licensed under the Apache License, Version 2.0 (the "License");+ // you may not use this file except in compliance with the License.+ // You may obtain a copy of the License at+ //+ // http://www.apache.org/licenses/LICENSE-2.0+ //+ // Unless required by applicable law or agreed to in writing, software+ // distributed under the License is distributed on an "AS IS" BASIS,+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ // See the License for the specific language governing permissions and+ // limitations under the License.++ // Relay policy surface: /policy/{sandboxUid} — the runtime twin of the+ // vault relay. The binding input seeds the policy at create; the relay owns+ // every runtime mutation. GET returns the recorded policy + revision; PUT+ // is a full replace (optional expectedRevision); DELETE reverts to+ // default-deny. Every write runs persist → apply → ack.+ package main++ import (+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"++ "github.com/alibaba/opensandbox/egress/pkg/constants"+ "github.com/alibaba/opensandbox/egress/pkg/log"+ "github.com/alibaba/opensandbox/egress/pkg/policy"+ "github.com/alibaba/opensandbox/egress/pkg/subject"+ )++ // policyEntry records the per-subject policy bookkeeping: the revision the+ // relay preconditions fence on, the runtime fence, and the state flags. The+ // policy itself lives in the registry (active) or pendingPolicies+ // (denying). A record is authoritative once it exists: the binding input+ // only ever seeds a fresh subject — later changes ride the relay or the+ // snapshot transfer, like the vault.+ type policyEntry struct {+ revision int64+ fence subject.Fencing+ // sealed marks a paused subject whose policy file was exported into the+ // snapshot bundle: every relay op answers 409; enforcement is unchanged.+ sealed bool+ // degraded is non-empty while the persisted policy could not be+ // reloaded: the record stays default-deny (fail closed) until a+ // successful relay write heals it.+ degraded string+ }++ // policyRelayDocument is the GET response and PUT body of the relay+ // surface. Revision is echoed by GET and acts as the PUT precondition (the+ // GET body is re-pushable verbatim); ExpectedRevision is the explicit+ // precondition form. Both present must agree.+ type policyRelayDocument struct {+ Revision int64 `json:"revision"`+ ExpectedRevision *int64 `json:"expectedRevision,omitempty"`+ Policy json.RawMessage `json:"policy"`+ }++ // maxPolicyRelayBodyBytes bounds one relay body: the policy (the platform+ // binding-input cap) plus the document framing.+ const maxPolicyRelayBodyBytes = policy.MaxPolicyBodyBytes + 1<<10++ // handlePolicyRelay serves /policy/{sandboxUid} for all relay verbs.+ func (s *fastSandboxPolicyServer) handlePolicyRelay(w http.ResponseWriter, r *http.Request) {+ uid := strings.TrimPrefix(r.URL.Path, constants.PolicyRelayPathPrefix)+ if !validVaultSubjectID(uid) {+ http.Error(w, "missing or invalid sandbox uid in path", http.StatusBadRequest)+ return+ }+ subj := subject.FromSandboxUID(uid)+ switch r.Method {+ case http.MethodGet:+ doc, status, msg := s.selectRelayPolicy(r, subj)+ if status != 0 {+ http.Error(w, msg, status)+ return+ }+ writeJSON(w, http.StatusOK, doc)+ case http.MethodPut, http.MethodDelete:+ s.handlePolicyRelayWrite(w, r, subj)+ default:+ w.Header().Set("Allow", "GET, PUT, DELETE")+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)+ }+ }++ // selectRelayPolicy serves GET: registration, expectedIncarnation, seal,+ // and the recorded policy. Held across the whole read so the policy body+ // and its revision come from the same commit (the server's GET→merge→PUT+ // PATCH uses the revision as its precondition). Lock order:+ // policyCommitMu → registry → s.mu (see fastsandbox_server.go's takeover+ // path; the reverse order deadlocks the DNS hot path).+ func (s *fastSandboxPolicyServer) selectRelayPolicy(r *http.Request, subj subject.Subject) (*policyRelayDocument, int, string) {++ if s.subjectRebinding(subj) {++ return nil, http.StatusServiceUnavailable, "subject rebind in progress"++ }+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()+ fence, ok := s.reg.Fence(subj)+ if !ok {+ return nil, http.StatusNotFound, "unknown subject"+ }+ if inc := strings.TrimSpace(r.Header.Get(constants.EgressVaultIncarnationHeader)); inc != "" && inc != fence.RuntimeInstanceID {+ return nil, http.StatusPreconditionFailed, "expectedIncarnation mismatch"+ }+ pol := s.reg.UserPolicy(subj)+ s.mu.Lock()+ defer s.mu.Unlock()++ if s.subjectRebindingLocked(subj) {++ return nil, http.StatusServiceUnavailable, "subject rebind in progress"++ }+ if !s.fenceMatchesLocked(subj, fence) {+ return nil, http.StatusNotFound, "unknown subject"+ }+ if e := s.policies[subj]; e != nil && e.sealed {+ return nil, http.StatusConflict, "subject policy is sealed (paused); the bundle copy is already taken"+ }+ if pol == nil {+ pol = s.pendingPolicies[subj]+ }+ if pol == nil {+ return nil, http.StatusNotFound, "subject has no recorded policy"+ }+ rev := int64(0)+ if e := s.policies[subj]; e != nil {+ rev = e.revision+ }+ raw, err := json.Marshal(pol)+ if err != nil {+ return nil, http.StatusInternalServerError, "policy serialization failure"+ }+ return &policyRelayDocument{Revision: rev, Policy: raw}, 0, ""+ }++ // handlePolicyRelayWrite serves PUT (full replace, create-when-absent) and+ // DELETE (revert to default-deny). The body is parsed and validated before+ // policyCommitMu is taken (a stalled or invalid client must never hold+ // it); the whole write — guards, decision, commit — serializes on it.+ func (s *fastSandboxPolicyServer) handlePolicyRelayWrite(w http.ResponseWriter, r *http.Request, subj subject.Subject) {+ var doc policyRelayDocument+ if r.Method == http.MethodPut {+ data, err := io.ReadAll(io.LimitReader(r.Body, maxPolicyRelayBodyBytes+1))+ if err != nil {+ http.Error(w, "failed to read policy body: "+err.Error(), http.StatusBadRequest)+ return+ }+ if len(data) > maxPolicyRelayBodyBytes {+ http.Error(w, fmt.Sprintf("policy body exceeds %d bytes", maxPolicyRelayBodyBytes), http.StatusBadRequest)+ return+ }+ dec := json.NewDecoder(strings.NewReader(string(data)))+ dec.DisallowUnknownFields()+ if err := dec.Decode(&doc); err != nil {+ http.Error(w, "invalid policy replace request: "+err.Error(), http.StatusBadRequest)+ return+ }+ }+ // The body has been consumed; a late response must not try to read it.+ r.Body.Close()++ if r.Method == http.MethodPut && len(doc.Policy) == 0 {+ http.Error(w, "policy body required", http.StatusBadRequest)+ return+ }+ pol, err := policy.ParsePolicy(string(doc.Policy))+ if err != nil {+ http.Error(w, "invalid policy: "+err.Error(), http.StatusBadRequest)+ return+ }+ if len(doc.Policy) > policy.MaxPolicyBodyBytes {+ http.Error(w, fmt.Sprintf("policy body exceeds %d bytes", policy.MaxPolicyBodyBytes), http.StatusBadRequest)+ return+ }+ expected, perr := relayPolicyPrecondition(&doc)+ if perr != nil {+ http.Error(w, perr.Error(), http.StatusBadRequest)+ return+ }+++ if s.subjectRebinding(subj) {++ http.Error(w, "subject rebind in progress", http.StatusServiceUnavailable)++ return++ }+ // The decision must be commit-atomic or two racing replaces could land+ // the same revision. Enforcement in the apply closures never runs+ // under s.mu (it takes the registry write lock).+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()++ // Registry reads before s.mu (lock order: registry → s.mu).+ fence, ok := s.reg.Fence(subj)+ if !ok {+ http.Error(w, "unknown subject", http.StatusNotFound)+ return+ }+ if inc := strings.TrimSpace(r.Header.Get(constants.EgressVaultIncarnationHeader)); inc != "" && inc != fence.RuntimeInstanceID {+ http.Error(w, "expectedIncarnation mismatch", http.StatusPreconditionFailed)+ return+ }+ s.mu.Lock()++ if s.subjectRebindingLocked(subj) {++ s.mu.Unlock()++ http.Error(w, "subject rebind in progress", http.StatusServiceUnavailable)++ return++ }+ if !s.fenceMatchesLocked(subj, fence) {+ s.mu.Unlock()+ http.Error(w, "unknown subject", http.StatusNotFound)+ return+ }+ entry := s.policies[subj]+ if entry != nil && entry.sealed {+ s.mu.Unlock()+ http.Error(w, "subject policy is sealed (paused); the bundle copy is already taken", http.StatusConflict)+ return+ }+ if recovery := s.policyRecovery.Load(); recovery != nil {+ s.mu.Unlock()+ http.Error(w, "policy persistence recovery required: "+recovery.reason, http.StatusServiceUnavailable)+ return+ }+ cur := int64(0)+ if entry != nil {+ cur = entry.revision+ }+ s.mu.Unlock()++ if r.Method == http.MethodDelete {+ if entry == nil {+ http.Error(w, "subject has no recorded policy", http.StatusNotFound)+ return+ }+ // Deletion is an authoritative tombstone at the successor revision.+ s.deleteRelayPolicy(w, subj, fence, cur+1)+ return+ }++ // PUT: a conditional replace against an absent record is a 412, not a+ // create (sidecar parity).+ if expected != nil && entry == nil {+ http.Error(w, "expectedRevision mismatch", http.StatusPreconditionFailed)+ return+ }+ if expected != nil && *expected != cur {+ http.Error(w, "expectedRevision mismatch", http.StatusPreconditionFailed)+ return+ }+ created := entry == nil+ newRev := cur + 1+ s.putRelayPolicy(w, r, subj, fence, pol, newRev, created)+ }++ // relayPolicyPrecondition extracts the effective precondition. The revision+ // echoed by GET and an explicit expectedRevision must agree when both are+ // present (ambiguous request).+ func relayPolicyPrecondition(doc *policyRelayDocument) (expected *int64, err error) {+ switch {+ case doc.ExpectedRevision == nil:+ if doc.Revision != 0 {+ rev := doc.Revision+ expected = &rev+ }+ case doc.Revision == 0 || doc.Revision == *doc.ExpectedRevision:+ expected = doc.ExpectedRevision+ default:+ err = fmt.Errorf("revision %d and expectedRevision %d disagree", doc.Revision, *doc.ExpectedRevision)+ }+ return expected, err+ }++ // putRelayPolicy commits a full replace: persist → apply → ack. The caller+ // holds policyCommitMu (guards and commit are one serialized unit). The+ // apply closure re-reads the lifecycle state and fence at apply time —+ // both can change between the guards and the commit.+ func (s *fastSandboxPolicyServer) putRelayPolicy(w http.ResponseWriter, r *http.Request, subj subject.Subject, fence subject.Fencing, pol *policy.NetworkPolicy, newRev int64, created bool) {+ raw, err := json.Marshal(pol)+ if err != nil {+ log.Errorf("subject %s: policy marshal failed: %v", subj, err)+ http.Error(w, "policy persistence failure", http.StatusInternalServerError)+ return+ }+ doc := policyRelayDocument{Revision: newRev, Policy: raw}++ apply := func() error {+ state, err := s.policyCommitTarget(subj, fence)+ if err != nil {+ return err+ }+ if state == subject.StateActive {+ // Enforcement first: a failed apply leaves the record untouched+ // (the commit protocol rolls the file back).+ if err := s.applyPolicy(subj, pol); err != nil {+ return err+ }+ }+ s.mu.Lock()+ // The pending slot mirrors what is enforced, so a replayed+ // data-plane-ready is idempotent.+ s.pendingPolicies[subj] = pol+ // A fresh entry also clears a degraded mark: the write IS the heal.+ s.policies[subj] = &policyEntry{revision: newRev, fence: fence}+ s.mu.Unlock()+ return nil+ }++ payload, err := policy.EncodePolicyFile(fence.RuntimeInstanceID, fence.AttachmentID, newRev, raw)+ if err != nil {+ log.Errorf("subject %s: policy file encode failed: %v", subj, err)+ http.Error(w, "policy persistence failure", http.StatusInternalServerError)+ return+ }+ err = s.persistPolicyCandidateLocked(+ subj,+ func(fs vaultFileStore) (policy.FileMutationState, error) {+ return fs.SaveRaw(payload)+ },+ apply,+ )+ if err != nil {+ // Uncertain persist latched → 503; every other failure kept last-good+ // on both sides → retryable 500. Details stay in the log.+ log.Errorf("subject %s: policy relay write failed: %v", subj, err)+ status := http.StatusInternalServerError+ if recovery := s.policyRecovery.Load(); recovery != nil {+ status = http.StatusServiceUnavailable+ }+ http.Error(w, "policy persistence failure", status)+ return+ }+ writeJSON(w, putResponseStatus(created), doc)+ }++ // policyCommitTarget re-reads the lifecycle state and registration fence at+ // apply time: activation and rebinds run outside the commit serialization,+ // so a stale apply aborts (the protocol rolls the file back) instead of+ // landing on the wrong identity or state. Registry reads only — no s.mu.+ func (s *fastSandboxPolicyServer) policyCommitTarget(subj subject.Subject, fence subject.Fencing) (subject.State, error) {+ regFence, ok := s.reg.Fence(subj)+ if !ok || regFence != fence {+ return subject.StateAbsent, fmt.Errorf("stale policy commit (fence changed) for subject %s", subj)+ }+ state, _ := s.reg.Get(subj)+ return state, nil+ }++ // putResponseStatus maps the committed replace onto the relay contract:+ // 201 when it created the record, 200 otherwise.+ func putResponseStatus(created bool) int {+ if created {+ return http.StatusCreated+ }+ return http.StatusOK+ }++ // deleteRelayPolicy commits deletion as an authoritative default-deny+ // tombstone: the record persists at the successor revision, so a restart+ // reloads the deletion instead of letting the replayed bootstrap binding+ // resurrect the removed policy. On an active subject the deny applies in+ // place (stays active, so a later PUT re-enables immediately); on a+ // denying one it is held pending. The caller holds policyCommitMu.+ func (s *fastSandboxPolicyServer) deleteRelayPolicy(w http.ResponseWriter, subj subject.Subject, fence subject.Fencing, newRev int64) {+ deny := policy.DefaultDenyPolicy()+ apply := func() error {+ state, err := s.policyCommitTarget(subj, fence)+ if err != nil {+ return err+ }+ if state == subject.StateActive {+ // Enforcement first (nft commits before the registry state).+ // The subject stays active, so a later PUT re-enables without+ // a hook replay.+ if err := s.applyPolicy(subj, deny); err != nil {+ return err+ }+ }+ s.mu.Lock()+ // A replayed data-plane-ready activates the tombstone, never a+ // stale policy.+ s.pendingPolicies[subj] = deny+ s.policies[subj] = &policyEntry{revision: newRev, fence: fence}+ s.mu.Unlock()+ return nil+ }++ raw, err := json.Marshal(deny)+ if err != nil {+ http.Error(w, "policy persistence failure", http.StatusInternalServerError)+ return+ }+ payload, err := policy.EncodePolicyFile(fence.RuntimeInstanceID, fence.AttachmentID, newRev, raw)+ if err != nil {+ http.Error(w, "policy persistence failure", http.StatusInternalServerError)+ return+ }+ err = s.persistPolicyCandidateLocked(+ subj,+ func(fs vaultFileStore) (policy.FileMutationState, error) {+ return fs.SaveRaw(payload)+ },+ apply,+ )+ if err != nil {+ log.Errorf("subject %s: policy relay delete failed: %v", subj, err)+ status := http.StatusInternalServerError+ if recovery := s.policyRecovery.Load(); recovery != nil {+ status = http.StatusServiceUnavailable+ }+ http.Error(w, "policy persistence failure", status)+ return+ }+ log.Infof("subject %s: policy deleted (deny tombstone enforced and persisted at revision %d)", subj, newRev)+ w.WriteHeader(http.StatusNoContent)+ }diff --cc components/egress/fastsandbox_policy_snapshot.goindex 000000000,cb1f86295..17e04a3d2mode 000000,100644..100644--- a/components/egress/fastsandbox_policy_snapshot.go+++ b/components/egress/fastsandbox_policy_snapshot.go@@@ -1,0 -1,389 +1,399 @@@+ // Copyright 2026 The OpenSandbox Authors+ //+ // Licensed under the Apache License, Version 2.0 (the "License");+ // you may not use this file except in compliance with the License.+ // You may obtain a copy of the License at+ //+ // http://www.apache.org/licenses/LICENSE-2.0+ //+ // Unless required by applicable law or agreed to in writing, software+ // distributed under the License is distributed on an "AS IS" BASIS,+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ // See the License for the specific language governing permissions and+ // limitations under the License.++ // Policy snapshot transfer across pause/resume, mirroring the vault snapshot+ // transfer (fastsandbox_vault_snapshot.go). POLICY_EXPORT copies the+ // subject's recorded policy file into the snapshot bundle strictly before the+ // runtime teardown and seals the subject; POLICY_IMPORT lands the bundle+ // file re-stamped with the restored fence — the only authorized incarnation+ // transfer — through the same commit protocol as the relay writes, marking+ // the recorded policy so later binding replays never override it. The+ // invocation side (driver/Fastlet hooks, snapshot manifest) is platform+ // work in the fast-sandbox repository.+ package main++ import (+ "bytes"+ "errors"+ "fmt"+ "io"+ "io/fs"+ "net/http"+ "os"+ "strings"++ "github.com/alibaba/opensandbox/egress/pkg/actionhandler"+ "github.com/alibaba/opensandbox/egress/pkg/log"+ "github.com/alibaba/opensandbox/egress/pkg/policy"+ "github.com/alibaba/opensandbox/egress/pkg/subject"+ )++ // maxPolicySnapshotBytes bounds a bundle read: the largest valid policy file+ // is a max relay body plus the encoded envelope — anything over this is not+ // a v1 policy file.+ const maxPolicySnapshotBytes = policy.MaxEncodedPolicyFileBytes++ var errPolicySnapshotTooLarge = fmt.Errorf("policy bundle file exceeds %d bytes", maxPolicySnapshotBytes)++ // applyPolicyExport copies the recorded policy file into the bundle target+ // and seals the subject (a subject without a policy file just seals).+ // Failures leave it unsealed and enforcement unchanged — the driver fails+ // the pause checkpoint and retries. Three phases, the guarded ones+ // serialized with the relay commits: guards + source image, the copy, then+ // re-check + seal (source changed mid-copy → 409; the recovery latch+ // rejects the export in both guarded phases).+ func (s *fastSandboxPolicyServer) applyPolicyExport(env *actionhandler.Envelope) (int, error) {+ subj := subject.FromSandboxUID(env.Sandbox.UID)+ fence := subject.FromRevision(env)+ target := strings.TrimSpace(env.Snapshot.Path)+ if s.reservesStatePath(target) {+ return http.StatusBadRequest, fmt.Errorf("policy bundle target %q must not live under a per-subject state directory", target)+ }+ // A subject that never registered (a sandbox created without an egress+ // binding, or after terminal cleanup) has no policy to carry: 200 so the+ // checkpoint proceeds — a 404 would fail every pause of a binding-less+ // sandbox. A registered subject under a stale fence still fails below.+ // Registry reads before the lock acquisitions (lock order: registry →+ // policyCommitMu → s.mu, see selectRelayPolicy).+ regFence, registered := s.reg.Fence(subj)+ if !registered {+ log.Infof("policy export: subject %s not registered; no policy to carry, checkpoint proceeds without it", subj)+ return http.StatusOK, nil+ }++ // Phase 1: guards + consistent source image, serialized with the policy+ // relay commits (policyCommitMu). A relay writer that passed its guards+ // but has not committed yet is either flushed before the snapshot (the+ // copy carries its write) or blocked until phase 3.+ s.policyCommitMu.Lock()+ s.mu.Lock()+ snap, status, err := s.policyExportSourceImageLocked(subj, fence, regFence, registered)+ s.mu.Unlock()+ s.policyCommitMu.Unlock()+ if err != nil {+ return status, err+ }++ // Phase 2: no lock held across the driver-owned write. A relay commit+ // here is caught by the phase-3 re-check (the copied image no longer+ // matches the live file → 409, no seal).+ if snap.Exists() {+ bundle, err := s.policyFiles.newFile(target)+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle target unavailable: %w", err)+ }+ state, err := bundle.SaveRaw(snap.Data())+ if err != nil || state != policy.FileCommitted {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle copy failed (state %v): %v", state, err)+ }+ }++ // Phase 3: seal only against the exact copied image, again serialized+ // with the relay commits — between the re-check and the seal no writer+ // can pass the guards (they now observe the seal) or commit. The fence+ // is re-read fresh (registry before s.mu) so a rebind during the copy+ // fails the export instead of sealing the wrong subject's bytes.+ regFence, registered = s.reg.Fence(subj)+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()+ s.mu.Lock()+ defer s.mu.Unlock()+ live, status, err := s.policyExportSourceImageLocked(subj, fence, regFence, registered)+ if err != nil {+ return status, err+ }+ if live.Exists() != snap.Exists() || (snap.Exists() && !bytes.Equal(live.Data(), snap.Data())) {+ return http.StatusConflict, fmt.Errorf("policy file changed during export for subject %s; bundle copy not sealed", subj)+ }+ if !snap.Exists() {+ // Nothing to carry: a previous attempt may have left stale bytes at+ // the target — remove them, or a later import would restore a policy+ // deleted during the pause.+ bundle, err := s.policyFiles.newFile(target)+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle target unavailable: %w", err)+ }+ state, err := bundle.Delete()+ if err != nil || (state != policy.FileCommitted && state != policy.FileUnchanged) {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle removal failed (state %v): %v", state, err)+ }+ }+ // Seal-free template carry: the record was copied verbatim and the+ // source keeps full relay CRUD — no latch, bookkeeping untouched.+ if !env.Snapshot.Sealed() {+ if snap.Exists() {+ log.Infof("subject %s: policy exported to snapshot bundle, seal-free (template carry)", subj)+ } else {+ log.Infof("subject %s: no policy file to export, seal-free (template carry)", subj)+ }+ return http.StatusOK, nil+ }+ // Durable seal first: a restart before REMOVE_BINDING must reload the+ // entry sealed, or relay writes would stale the taken bundle.+ if err := s.policyFiles.seal(subj); err != nil {+ return http.StatusInternalServerError, fmt.Errorf("policy seal marker: %w", err)+ }+ e := s.policies[subj]+ if e == nil || e.fence != fence {+ e = &policyEntry{fence: fence}+ }+ e.sealed = true+ s.policies[subj] = e+ if snap.Exists() {+ log.Infof("subject %s: policy exported to snapshot bundle, subject sealed", subj)+ } else {+ log.Infof("subject %s: no policy file to export, subject sealed", subj)+ }+ return http.StatusOK, nil+ }++ // policyExportSourceImageLocked runs the export guards and returns a+ // consistent image of the subject's policy file. regFence/registered are+ // the caller's pre-read of the registration (lock order: registry →+ // policyCommitMu → s.mu, see applyPolicyExport). Callers hold s.mu.+ func (s *fastSandboxPolicyServer) policyExportSourceImageLocked(subj subject.Subject, fence subject.Fencing, regFence subject.Fencing, registered bool) (*policy.PolicyFileSnapshot, int, error) {++ if s.subjectRebindingLocked(subj) {++ return nil, http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")++ }+ if !registered {+ return nil, http.StatusNotFound, fmt.Errorf("policy export for unknown subject %s", subj)+ }+ if !regFence.Matches(fence) {+ return nil, http.StatusConflict, fmt.Errorf("stale policy export (fence mismatch) for subject %s", subj)+ }+ if !s.fenceMatchesLocked(subj, fence) {+ // Purged between the pre-read and the lock — the stale envelope+ // lost the race with a rebind. The registered-fence mismatch above+ // already covers the plain stale case.+ return nil, http.StatusNotFound, fmt.Errorf("policy export for unknown subject %s", subj)+ }+ if recovery := s.policyRecovery.Load(); recovery != nil {+ return nil, http.StatusServiceUnavailable, fmt.Errorf("policy persistence recovery required: %s", recovery.reason)+ }+ fs, err := s.policyFiles.storeFor(subj)+ if err != nil {+ return nil, http.StatusInternalServerError, fmt.Errorf("policy file store unavailable: %w", err)+ }+ snap, err := fs.Snapshot()+ if err != nil {+ return nil, http.StatusInternalServerError, fmt.Errorf("policy file snapshot: %w", err)+ }+ if snap.Exists() {+ // Carry only bytes attributable to the registered fence: a leftover+ // from a previous incarnation (purge failed), a corrupt file, or a+ // newer schema is treated as absent — never exported, or import+ // would re-stamp a foreign policy as current.+ pf, _, decErr := policy.DecodePolicyFile(snap.Data())+ if decErr != nil || pf.Incarnation != regFence.RuntimeInstanceID || pf.AttachmentID != regFence.AttachmentID {+ what := "unattributable fence"+ if errors.Is(decErr, policy.ErrUnsupportedPolicyFileVersion) {+ what = "newer schema"+ } else if decErr != nil {+ what = "unreadable"+ }+ log.Infof("subject %s: policy file not carried (%s)", subj, what)+ return policy.NewFileSnapshot("", nil, false), 0, nil+ }+ }+ return snap, 0, nil+ }++ // applyPolicyImport lands the bundle as the subject's policy file,+ // re-stamped with the restored fence from the envelope (the only authorized+ // incarnation transfer) and installs it file-backed. Delivery is+ // at-least-once: a local revision newer than the bundle acks idempotently.+ // Unregistered (before SET_BINDING), only the file lands — the+ // registration-time reload validates it; registered, the policy installs+ // into the live record and a rejected bundle is a 400 with last-good kept.+ func (s *fastSandboxPolicyServer) applyPolicyImport(env *actionhandler.Envelope) (int, error) {+ subj := subject.FromSandboxUID(env.Sandbox.UID)+ fence := subject.FromRevision(env)+ source := strings.TrimSpace(env.Snapshot.Path)+ if s.reservesStatePath(source) {+ return http.StatusBadRequest, fmt.Errorf("policy bundle source %q must not live under a per-subject state directory", source)+ }++ // Read before locking; a missing/oversized/unreadable source is+ // permanent — the fastlet retry cannot repair it.+ data, err := readPolicyBundle(source)+ if errors.Is(err, fs.ErrNotExist) {+ return http.StatusNotFound, fmt.Errorf("policy bundle file %q does not exist", source)+ }+ if errors.Is(err, errPolicySnapshotTooLarge) {+ return http.StatusBadRequest, err+ }+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle read failed: %w", err)+ }+ pf, body, err := policy.DecodePolicyFile(data)+ if err != nil {+ return http.StatusBadRequest, fmt.Errorf("invalid policy bundle file: %v", err)+ }+ pol, parseErr := policy.ParsePolicy(string(body))+ if parseErr != nil {+ return http.StatusBadRequest, fmt.Errorf("invalid policy bundle content: %v", parseErr)+ }+ // The authorized incarnation transfer.+ payload, err := policy.EncodePolicyFile(fence.RuntimeInstanceID, fence.AttachmentID, pf.Revision, body)+ if err != nil {+ return http.StatusInternalServerError, fmt.Errorf("policy bundle re-stamp failed: %w", err)+ }+++ if s.subjectRebinding(subj) {++ return http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")++ }+ // Serialize the commit against relay writes; guards run under s.mu+ // inside (the ordering policyCommitMu → s.mu is the commit path's).+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()++ // The registration fence re-validation happens under s.mu against our+ // own recorded fence (subjFence) — no registry read is needed in this+ // section, so the registry → policyCommitMu → s.mu order is preserved+ // trivially (see applyPolicyExport). An unknown fence (no record) means+ // the subject is not registered: the bundle lands for the next+ // registration.+ s.mu.Lock()++ if s.subjectRebindingLocked(subj) {++ s.mu.Unlock()++ return http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")++ }+ // The latch freezes every policy file mutation; only a restart+ // reconciles (relay-write parity).+ if recovery := s.policyRecovery.Load(); recovery != nil {+ s.mu.Unlock()+ return http.StatusServiceUnavailable, fmt.Errorf("policy persistence recovery required: %s", recovery.reason)+ }+ // At-least-once delivery: never roll a newer local revision back. The+ // guard requires the stored fence to match the envelope — a newer file+ // under an old incarnation is stale local state the import must+ // supersede, not ack.+ if fs, fsErr := s.policyFiles.storeFor(subj); fsErr == nil {+ if cur, snapErr := fs.Snapshot(); snapErr == nil && cur.Exists() {+ if curPF, _, decErr := policy.DecodePolicyFile(cur.Data()); decErr == nil &&+ curPF.Incarnation == fence.RuntimeInstanceID && curPF.AttachmentID == fence.AttachmentID &&+ curPF.Revision > pf.Revision {+ s.mu.Unlock()+ log.Infof("subject %s: policy import superseded (local revision %d > bundle revision %d), idempotent ack", subj, curPF.Revision, pf.Revision)+ return http.StatusOK, nil+ }+ }+ }+ registered := s.fenceMatchesLocked(subj, fence)+ if _, known := s.subjFence[subj]; known && !registered {+ s.mu.Unlock()+ return http.StatusConflict, fmt.Errorf("stale policy import (fence mismatch) for subject %s", subj)+ }+ sealed := false+ if e := s.policies[subj]; e != nil && e.sealed {+ sealed = true+ }+ s.mu.Unlock()++ err = s.persistPolicyCandidateLocked(+ subj,+ func(fs vaultFileStore) (policy.FileMutationState, error) {+ return fs.SaveRaw(payload)+ },+ func() error {+ if !registered {+ // Before SET_BINDING: registration reloads and validates.+ s.mu.Lock()+ delete(s.policies, subj)+ s.mu.Unlock()+ return s.policyFiles.unseal(subj)+ }+ err := s.installImportedPolicyLocked(subj, fence, pf.Revision, pol, sealed)+ if err != nil && sealed {+ // The unseal already happened; restore the durable seal so+ // disk and memory agree the bundle is still the truth (the+ // commit protocol rolls the file back to the sealed image;+ // the in-memory entry was never modified).+ if sealErr := s.policyFiles.seal(subj); sealErr != nil {+ log.Errorf("subject %s: policy seal marker restore failed after import apply failure: %v", subj, sealErr)+ }+ }+ return err+ },+ )+ if err != nil {+ log.Errorf("subject %s: policy import failed: %v", subj, err)+ status := http.StatusInternalServerError+ if recovery := s.policyRecovery.Load(); recovery != nil {+ status = http.StatusServiceUnavailable+ }+ return status, errors.New("policy import persistence failure")+ }+ if registered {+ log.Infof("subject %s: policy imported from snapshot bundle (revision %d, re-stamped to %s/%s)",+ subj, pf.Revision, fence.RuntimeInstanceID, fence.AttachmentID)+ } else {+ log.Infof("subject %s: policy bundle landed for the next registration (revision %d, re-stamped to %s/%s)",+ subj, pf.Revision, fence.RuntimeInstanceID, fence.AttachmentID)+ }+ return http.StatusOK, nil+ }++ // installImportedPolicyLocked binds the imported revision into the live+ // per-subject record under the restored fence, replacing any stale record,+ // and unseals it. Ordering inside the commit protocol's apply step: the+ // durable unseal FIRST (a failure here mutates nothing live — the commit+ // protocol rolls the file back and the seal stays), then the state/fence+ // re-read, then enforcement, then the record. Enforcement runs WITHOUT+ // s.mu (it takes the registry write lock); the s.mu suffix is the+ // docstring's "Locked" sense: map mutations under s.mu.+ func (s *fastSandboxPolicyServer) installImportedPolicyLocked(subj subject.Subject, fence subject.Fencing, revision int64, pol *policy.NetworkPolicy, wasSealed bool) error {+ if wasSealed {+ if err := s.policyFiles.unseal(subj); err != nil {+ return err+ }+ }+ state, err := s.policyCommitTarget(subj, fence)+ if err != nil {+ return err+ }+ if state == subject.StateActive {+ // Enforcement first: a failed apply leaves the record untouched+ // (the commit protocol rolls the file back).+ if err := s.applyPolicy(subj, pol); err != nil {+ return err+ }+ }+ s.mu.Lock()+ // The pending slot mirrors what is enforced (same rationale as the+ // relay PUT: a replayed data-plane-ready must be idempotent).+ s.pendingPolicies[subj] = pol+ s.policies[subj] = &policyEntry{revision: revision, fence: fence}+ s.mu.Unlock()+ return nil+ }++ // readPolicyBundle reads the driver-staged bundle source with a hard size+ // cap — a read-only lookup in the driver's trust domain, so plain bounded+ // I/O suffices (writes keep the hardened atomic machinery).+ func readPolicyBundle(path string) ([]byte, error) {+ f, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ data, err := io.ReadAll(io.LimitReader(f, maxPolicySnapshotBytes+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxPolicySnapshotBytes {+ return nil, errPolicySnapshotTooLarge+ }+ return data, nil+ }diff --cc components/egress/fastsandbox_server.goindex 4cd352c5f,5a979e0cc..bc880e2ba--- a/components/egress/fastsandbox_server.go+++ b/components/egress/fastsandbox_server.go@@@ -70,9 -65,15 +70,14 @@@ type fastSandboxPolicyServer struct// policy has not been made effective.pendingPolicies map[subject.Subject]*policy.NetworkPolicyvaults map[subject.Subject]vaultEntry- // subjAtt records the latest network attachment, used for terminal- // cleanup (gateway refcounts) even when the REMOVE_BINDING envelope omits- // the attachment block.+ // subjAtt records the latest validated registration attempt, including+ // failed enforcement, for same-fence comparison and old-IP cleanup.subjAtt map[subject.Subject]actionhandler.NetworkAttachment+ // subjFence mirrors the registered fence per subject: the relay paths+ // pre-read the registry before s.mu (lock order: registry → s.mu), and+ // this in-lock comparison rejects requests whose pre-read went stale+ // across a rebind.+ subjFence map[subject.Subject]subject.Fencing// vaultFiles owns the per-subject vault files; nil keeps the vault// memory-only (the default, and the sidecar posture).@@@ -116,11 -137,11 +141,13 @@@ func newFastSandboxPolicyServer(ctx conctx: ctx,reg: reg,nft: nft,+ actionGate: make(chan struct{}, 1),+ rebinds: make(map[subject.Subject]*subjectRebind),vaults: make(map[subject.Subject]vaultEntry),pendingPolicies: make(map[subject.Subject]*policy.NetworkPolicy),+ policies: make(map[subject.Subject]*policyEntry),subjAtt: make(map[subject.Subject]actionhandler.NetworkAttachment),+ subjFence: make(map[subject.Subject]subject.Fencing),gatewayDNSRefs: make(map[subject.Subject]netip.Addr),dnsRedirectInstall: iptables.SetupGatewayDNSRedirect,dnsRedirectRemove: iptables.RemoveGatewayDNSRedirect,@@@ -523,39 -555,44 +578,60 @@@ func (s *fastSandboxPolicyServer) takeo}// dropSubjectState removes every piece of per-subject bookkeeping (vault,- // pending policy, attachment) plus the persisted vault file — terminal- // cleanup (OSEP-0022: REMOVE_BINDING purges memory + file).+ // policy record, pending policy, attachment) plus the persisted files —+ // terminal cleanup.+ //-// Deliberately without policyCommitMu: the takeover caller runs under the-// registry write lock, and taking policyCommitMu there would invert against-// relay commits (policyCommitMu → registry). Safety comes from the commit-// paths' fence re-check and fence-keyed stale-file discards.++// Purges run after registry eviction, never in a registry callback.++// The action gate prevents another registration from racing victim cleanup.func (s *fastSandboxPolicyServer) dropSubjectState(subj subject.Subject) {s.mu.Lock()- delete(s.vaults, subj)+ s.dropSubjectStateLocked(subj)+ cleared := s.rebinds[subj] != nil+ delete(s.rebinds, subj)+ s.mu.Unlock()+ if cleared {+ log.Infof("subject_rebind_cleared")+ }+}++// dropSubjectStateLocked preserves an in-flight rebind token. Superseding+// SETs use it only after full kernel removal and Unregister; Vault must stay+// guarded until the successor has completed local publication.+func (s *fastSandboxPolicyServer) dropSubjectStateLocked(subj subject.Subject) error {+ err := s.dropVault(subj)+ delete(s.policies, subj)++ s.purgePolicyFile(subj)++ delete(s.subjFence, subj)delete(s.pendingPolicies, subj)delete(s.subjAtt, subj)- delete(s.subjFence, subj)- s.purgeVaultFile(subj)- s.purgePolicyFile(subj)- s.mu.Unlock()+ return err}-// recordBindingState stores the SET_BINDING bookkeeping for a registered-// subject: the network attachment (terminal cleanup) and the registered-// fence (relay commit-time re-validation, see subjFence). Called after the-// registry lock is released.-func (s *fastSandboxPolicyServer) recordBindingState(subj subject.Subject, att actionhandler.NetworkAttachment, fence subject.Fencing) {+// recordBindingState records a validated network attempt before enforcement.+// A failed initial deny-first may already have kernel effects; retries must+// still compare its network rather than treat missing success metadata as+// evidence that no rules exist. Called outside the registry lock.+func (s *fastSandboxPolicyServer) recordBindingState(subj subject.Subject, att actionhandler.NetworkAttachment) {s.mu.Lock()s.subjAtt[subj] = att+ s.mu.Unlock()+}+++// recordRegisteredFence publishes relay bookkeeping after registration succeeds.++func (s *fastSandboxPolicyServer) recordRegisteredFence(subj subject.Subject, fence subject.Fencing) {++ s.mu.Lock()+ s.subjFence[subj] = fence+ s.mu.Unlock()+ }++ // fenceMatchesLocked reports whether the recorded fence equals the request+ // fence (commit-time re-validation for the pre-read window). Callers hold+ // s.mu.+ func (s *fastSandboxPolicyServer) fenceMatchesLocked(subj subject.Subject, fence subject.Fencing) bool {+ got, ok := s.subjFence[subj]+ return ok && got == fence+ }+// attachment returns the last observed network attachment for a registered// subject (used by terminal cleanup when the REMOVE_BINDING envelope omits// the attachment block).diff --cc components/egress/fastsandbox_transition.goindex 7c2314b12,000000000..a0b080c12mode 100644,000000..100644--- a/components/egress/fastsandbox_transition.go+++ b/components/egress/fastsandbox_transition.go@@@ -1,103 -1,0 +1,111 @@@+// Copyright 2026 The OpenSandbox Authors+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package main++import (+ "context"++ "github.com/alibaba/opensandbox/egress/pkg/actionhandler"+ "github.com/alibaba/opensandbox/egress/pkg/log"+ "github.com/alibaba/opensandbox/egress/pkg/subject"+)++// subjectRebind protects only one unfinished same-UID registration intent.+// The allocated pointer is its exact, non-reusable identity. Stages record+// completed cleanup, not assumptions based on the registry's new fence:+// RegisterAndEnforce publishes that fence before deny-first can fail.+// Identity fields are immutable. Map/stage access is under mu; only an+// action-gate holder changes stages.+type subjectRebind struct {+ old, expectedNew subject.Fencing+ oldNetwork, newNetwork actionhandler.NetworkAttachment+ needsReset bool // a newer SET superseded an unfinished intent+ removeOld bool // old IP differs, or its network is unknown+ oldRemoved bool+ purged bool+}++// subjectRebindingLocked is shared by Vault entry points. Callers hold mu.+func (s *fastSandboxPolicyServer) subjectRebindingLocked(subj subject.Subject) bool {+ return s.rebinds[subj] != nil+}++func (s *fastSandboxPolicyServer) actionCanceled(ctx context.Context) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ return s.ctx.Err()+}++func (s *fastSandboxPolicyServer) acquireAction(ctx context.Context) (func(), error) {+ if err := s.actionCanceled(ctx); err != nil {+ return nil, err+ }+ select {+ case s.actionGate <- struct{}{}:+ // Cancellation and gate availability can become ready together. Never+ // let a canceled queued SET replace the current registration intent.+ if err := s.actionCanceled(ctx); err != nil {+ <-s.actionGate+ return nil, err+ }+ return func() { <-s.actionGate }, nil+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-s.ctx.Done():+ return nil, s.ctx.Err()+ }+}++func sameBindingNetwork(a, b actionhandler.NetworkAttachment) bool {+ return a.IP == b.IP && a.Gateway == b.Gateway+}++func (s *fastSandboxPolicyServer) finishRebind(subj subject.Subject, token *subjectRebind) {+ if token == nil {+ return+ }+ s.mu.Lock()+ cleared := s.rebinds[subj] == token+ if cleared {+ delete(s.rebinds, subj)+ }+ s.mu.Unlock()+ if cleared {+ log.Infof("subject_rebind_cleared")+ }+}++// logPendingRebind runs once at the end of an attempted SET/REMOVE, never on+// polling Vault/HOOK reads. Fixed events contain no identity or request data.+func (s *fastSandboxPolicyServer) logPendingRebind(subj subject.Subject, token *subjectRebind) {+ if token == nil {+ return+ }+ s.mu.Lock()+ pending := s.rebinds[subj] == token+ s.mu.Unlock()+ if pending {+ log.Warnf("subject_rebind_pending")+ }+}++++// subjectRebinding permits fail-fast rejection before waiting on a policy commit.++// Commit paths must repeat this check under mu after acquiring their commit lock.++func (s *fastSandboxPolicyServer) subjectRebinding(subj subject.Subject) bool {++ s.mu.Lock()++ defer s.mu.Unlock()++ return s.subjectRebindingLocked(subj)++}diff --cc components/egress/fastsandbox_transition_policy_test.goindex 000000000,000000000..f24dcdde7new file mode 100644--- /dev/null+++ b/components/egress/fastsandbox_transition_policy_test.go@@@ -1,0 -1,0 +1,63 @@@++// Copyright 2026 The OpenSandbox Authors++//++// Licensed under the Apache License, Version 2.0 (the "License");++// you may not use this file except in compliance with the License.++// You may obtain a copy of the License at++//++// http://www.apache.org/licenses/LICENSE-2.0++//++// Unless required by applicable law or agreed to in writing, software++// distributed under the License is distributed on an "AS IS" BASIS,++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.++// See the License for the specific language governing permissions and++// limitations under the License.++++package main++++import (++ "errors"++ "net/http"++ "path/filepath"++ "testing"++++ "github.com/stretchr/testify/require"++)++++// The policy relay and snapshot surfaces arrived on main after the original++// transition fix. They must obey the same unfinished-registration guard as++// Vault, including a failed registration that has not published subjFence.++func TestTransitionPolicySurfacesRejectPendingRebind(t *testing.T) {++ for _, phase := range []string{"old-network-removal", "new-registration"} {++ t.Run(phase, func(t *testing.T) {++ h := newPolicyPersistHarness(t)++ subj := h.readySubject(t, policyTestUID, vaultTestIP)++ if phase == "old-network-removal" {++ h.nft.removeErr = errors.New("remove failed")++ } else {++ h.nft.denyFirstErr = errors.New("deny failed")++ }++ rec := doAction(t, h.srv, bindBody(t, policyTestUID, "10.0.0.6", "new-r", "new-a", 2, strPtr(policyAllow())))++ require.Equal(t, http.StatusInternalServerError, rec.Code)++ require.NotNil(t, transitionCurrentToken(h.srv, subj))++ before := append([]byte(nil), h.fileFor(policyTestUID).data...)++ for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {++ rec := doPolicy(t, h.srv, method, policyTestUID, policyPutDoc(policyAllowAlt(), 0, false, false), "")++ require.Equal(t, http.StatusServiceUnavailable, rec.Code, method)++ }++ export := filepath.Join(t.TempDir(), "export.json")++ rec = doAction(t, h.srv, policySnapshotBody(t, policyTestUID, "new-r", "new-a", "POLICY_EXPORT", export, nil))++ require.Equal(t, http.StatusServiceUnavailable, rec.Code)++ require.False(t, h.fakeForPath(export).exists)++ bundle := filepath.Join(t.TempDir(), "bundle.json")++ h.seedPolicyBundle(t, bundle, 7, policyAllowAlt())++ rec = doAction(t, h.srv, policySnapshotBody(t, policyTestUID, "new-r", "new-a", "POLICY_IMPORT", bundle, nil))++ require.Equal(t, http.StatusServiceUnavailable, rec.Code)++ require.Equal(t, before, h.fileFor(policyTestUID).data)++ require.False(t, h.fileFor(policyTestUID).exists, "rebind purges the predecessor policy file")++ h.nft.removeErr, h.nft.denyFirstErr = nil, nil++ require.Equal(t, http.StatusOK, doAction(t, h.srv, bindBody(t, policyTestUID, "10.0.0.6", "new-r", "new-a", 2, strPtr(policyAllow()))).Code)++ require.Nil(t, transitionCurrentToken(h.srv, subj))++ require.Equal(t, http.StatusOK, doPolicy(t, h.srv, http.MethodGet, policyTestUID, "", "new-r").Code)++ })++ }++}diff --cc components/egress/fastsandbox_vault.goindex a0993aeff,3621b7811..3bf716f92--- a/components/egress/fastsandbox_vault.go+++ b/components/egress/fastsandbox_vault.go@@@ -122,124 -123,148 +122,130 @@@ func (s *fastSandboxPolicyServer) handl// The body has been consumed; a late response must not try to read it.r.Body.Close()- // The whole write holds policyCommitMu: the validation policy must not- // change between the pre-read and the commit (policy mutations — relay- // PUT/DELETE, hooks, removals — serialize on the same mutex, and none- // of them bump the fence, so the commit-time fence re-check alone- // cannot catch this). Lock order: policyCommitMu → registry → s.mu.- s.policyCommitMu.Lock()- defer s.policyCommitMu.Unlock()-- // Registry reads before s.mu (lock order: policyCommitMu → registry →- // s.mu).- fence, ok := s.reg.Fence(subj)- if !ok {- http.Error(w, "unknown subject", http.StatusNotFound)- return- }- if inc := strings.TrimSpace(r.Header.Get(constants.EgressVaultIncarnationHeader)); inc != "" && inc != fence.RuntimeInstanceID {- http.Error(w, "expectedIncarnation mismatch", http.StatusPreconditionFailed)- return- }- // Pre-compute the validation policy BEFORE s.mu (registry → s.mu- // order): a vault op held to the data-plane-ready barrier must validate- // against the SAME policy the hook will enforce, operator always-rules- // included.- effective := s.vaultValidationPolicy(subj)-- // The rest of the mutation holds s.mu, serializing per-subject writers- // and fencing rebind/terminal purges. The validation policy was fully- // pre-computed above — nothing inside the lock touches the registry.- s.mu.Lock()- defer s.mu.Unlock()- // Commit-time fence re-validation: the pre-read above cannot see a- // rebind that completed after it (see subjFence).- if !s.fenceMatchesLocked(subj, fence) {- http.Error(w, "unknown subject", http.StatusNotFound)- return- }- if s.vaultSealedLocked(subj) {- http.Error(w, "subject vault is sealed (paused); the bundle copy is already taken", http.StatusConflict)- return- }- if recovery := s.vaultRecovery.Load(); recovery != nil {- http.Error(w, "vault persistence recovery required: "+recovery.reason, http.StatusServiceUnavailable)- return- }- store := s.vaultForLocked(subj, fence)- pol := effective+ // Capture a response while committing; no network output holds s.mu.+ respond := func() func() {++ if s.subjectRebinding(subj) {++ return func() { http.Error(w, "subject rebind in progress", http.StatusServiceUnavailable) }++ }++ s.policyCommitMu.Lock()++ defer s.policyCommitMu.Unlock()++ effective := s.vaultValidationPolicy(subj)+ s.mu.Lock()+ defer s.mu.Unlock()+ if s.subjectRebindingLocked(subj) {+ return func() { http.Error(w, "subject rebind in progress", http.StatusServiceUnavailable) }+ }+ fence, ok := s.reg.Fence(subj)+ if !ok {+ return func() { http.Error(w, "unknown subject", http.StatusNotFound) }+ }+ if inc := strings.TrimSpace(r.Header.Get(constants.EgressVaultIncarnationHeader)); inc != "" && inc != fence.RuntimeInstanceID {+ return func() { http.Error(w, "expectedIncarnation mismatch", http.StatusPreconditionFailed) }+ }+ if s.vaultSealedLocked(subj) {+ return func() {+ http.Error(w, "subject vault is sealed (paused); the bundle copy is already taken", http.StatusConflict)+ }+ }+ if recovery := s.vaultRecovery.Load(); recovery != nil {+ return func() {+ http.Error(w, "vault persistence recovery required: "+recovery.reason, http.StatusServiceUnavailable)+ }+ }+ store := s.vaultForLocked(subj, fence)+ if store == nil {+ return func() { http.Error(w, "unknown subject", http.StatusNotFound) }+ }- pol := s.vaultValidationPolicyLocked(subj)++ pol := effective- var (- candidate *credentialvault.MutationCandidate- created bool- err error- )- switch r.Method {- case http.MethodPost:- candidate, err = store.PrepareCreate(createReq, pol)- case http.MethodPut:- candidate, err = store.PrepareReplace(replaceReq, pol)- created = candidate.Created()- case http.MethodDelete:- candidate, err = store.PrepareDelete()- }- if err != nil {- writeVaultRelayError(w, err)- return- }- defer candidate.Discard()+ var (+ candidate *credentialvault.MutationCandidate+ created bool+ err error+ )+ switch r.Method {+ case http.MethodPost:+ candidate, err = store.PrepareCreate(createReq, pol)+ case http.MethodPut:+ candidate, err = store.PrepareReplace(replaceReq, pol)+ created = candidate.Created()+ case http.MethodDelete:+ candidate, err = store.PrepareDelete()+ }+ if err != nil {+ return func() { writeVaultRelayError(w, err) }+ }+ defer candidate.Discard()- // Rendering is required before commit; an unresolvable credential is a- // NACK before anything durable happens.- if candidate.Exists() {- if _, err = candidate.ActiveSnapshot(r.Context()); err != nil {- http.Error(w, "credential vault candidate cannot be rendered", http.StatusBadRequest)- return+ // Rendering is required before commit; an unresolvable credential is a+ // NACK before anything durable happens.+ if candidate.Exists() {+ if _, err = candidate.ActiveSnapshot(r.Context()); err != nil {+ return func() { http.Error(w, "credential vault candidate cannot be rendered", http.StatusBadRequest) }+ }}- }- if s.vaultFiles == nil {- // Memory-only (persistence disabled): direct commit.- state, commitErr := store.CommitCandidate(candidate)- if commitErr != nil {- writeVaultRelayError(w, commitErr)- return+ if s.vaultFiles == nil {+ // Memory-only (persistence disabled): direct commit.+ state, commitErr := store.CommitCandidate(candidate)+ if commitErr != nil {+ return func() { writeVaultRelayError(w, commitErr) }+ }+ return func() { writeVaultRelayWriteResponse(w, r, state, created) }}- writeVaultRelayWriteResponse(w, r, state, created)- return- }- // Persistence enabled: encode the candidate — stamped with the owning- // runtime fence — then run the commit protocol.- var payload []byte- if candidate.Exists() {- full, fullErr := candidate.Full()- if fullErr != nil {- log.Errorf("subject %s: vault candidate read failed: %v", subj, fullErr)- http.Error(w, "vault persistence failure", http.StatusInternalServerError)- return+ // Persistence enabled: encode the candidate — stamped with the owning+ // runtime fence — then run the commit protocol.+ var payload []byte+ if candidate.Exists() {+ full, fullErr := candidate.Full()+ if fullErr != nil {+ log.Errorf("subject %s: vault candidate read failed: %v", subj, fullErr)+ return func() { http.Error(w, "vault persistence failure", http.StatusInternalServerError) }+ }+ payload, err = credentialvault.EncodeVaultFile(fence.RuntimeInstanceID, fence.AttachmentID, full.Revision, credentialvault.VaultFileBody{+ Credentials: full.Credentials,+ Bindings: full.Bindings,+ })+ if err != nil {+ log.Errorf("subject %s: vault file encode failed: %v", subj, err)+ return func() { http.Error(w, "vault persistence failure", http.StatusInternalServerError) }+ }}- payload, err = credentialvault.EncodeVaultFile(fence.RuntimeInstanceID, fence.AttachmentID, full.Revision, credentialvault.VaultFileBody{- Credentials: full.Credentials,- Bindings: full.Bindings,- })+ err = s.persistVaultCandidateLocked(+ subj,+ func(fs vaultFileStore) (policy.FileMutationState, error) {+ if payload == nil {+ return fs.Delete()+ }+ return fs.SaveRaw(payload)+ },+ func() error {+ _, commitErr := store.CommitCandidate(candidate)+ return commitErr+ },+ )if err != nil {- log.Errorf("subject %s: vault file encode failed: %v", subj, err)- http.Error(w, "vault persistence failure", http.StatusInternalServerError)- return- }- }- err = s.persistVaultCandidateLocked(- subj,- func(fs vaultFileStore) (policy.FileMutationState, error) {- if payload == nil {- return fs.Delete()+ // Uncertain persist latched → 503; every other failure kept last-good+ // on both sides → retryable 500. Details stay in the log.+ log.Errorf("subject %s: vault relay write failed: %v", subj, err)+ status := http.StatusInternalServerError+ if recovery := s.vaultRecovery.Load(); recovery != nil {+ status = http.StatusServiceUnavailable}- return fs.SaveRaw(payload)- },- func() error {- _, commitErr := store.CommitCandidate(candidate)- return commitErr- },- )- if err != nil {- // Uncertain persist latched → 503; every other failure kept last-good- // on both sides → retryable 500. Details stay in the log.- log.Errorf("subject %s: vault relay write failed: %v", subj, err)- status := http.StatusInternalServerError- if recovery := s.vaultRecovery.Load(); recovery != nil {- status = http.StatusServiceUnavailable+ return func() { http.Error(w, "vault persistence failure", status) }}- http.Error(w, "vault persistence failure", status)- return- }- if r.Method == http.MethodDelete {- w.WriteHeader(http.StatusNoContent)- return- }- state, err := store.Sanitized()- if err != nil {- log.Errorf("subject %s: vault sanitized read failed: %v", subj, err)- http.Error(w, "vault persistence failure", http.StatusInternalServerError)- return- }- writeVaultRelayWriteResponse(w, r, state, created)+ if r.Method == http.MethodDelete {+ return func() { w.WriteHeader(http.StatusNoContent) }+ }+ state, err := store.Sanitized()+ if err != nil {+ log.Errorf("subject %s: vault sanitized read failed: %v", subj, err)+ return func() { http.Error(w, "vault persistence failure", http.StatusInternalServerError) }+ }+ return func() { writeVaultRelayWriteResponse(w, r, state, created) }+ }()+ respond()}// writeVaultRelayWriteResponse maps the committed mutation onto the relaydiff --cc components/egress/fastsandbox_vault_snapshot.goindex 277008a10,5f8f5c2da..79dde79ef--- a/components/egress/fastsandbox_vault_snapshot.go+++ b/components/egress/fastsandbox_vault_snapshot.go@@@ -147,13 -183,11 +183,14 @@@ func (s *fastSandboxPolicyServer) apply}// exportSourceImageLocked runs the export guards and returns a consistent- // image of the subject's vault file. Callers hold s.mu.- func (s *fastSandboxPolicyServer) exportSourceImageLocked(subj subject.Subject, fence subject.Fencing) (*policy.PolicyFileSnapshot, int, error) {+ // image of the subject's vault file. regFence/registered are the caller's+ // pre-read of the registration (lock order: registry → s.mu, see+ // applyVaultExport). Callers hold s.mu.+ func (s *fastSandboxPolicyServer) exportSourceImageLocked(subj subject.Subject, fence subject.Fencing, regFence subject.Fencing, registered bool) (*policy.PolicyFileSnapshot, int, error) {+ if s.subjectRebindingLocked(subj) {+ return nil, http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")+ }- regFence, ok := s.reg.Fence(subj)- if !ok {+ if !registered {return nil, http.StatusNotFound, fmt.Errorf("vault export for unknown subject %s", subj)}if !regFence.Matches(fence) {@@@ -236,11 -276,15 +279,21 @@@ func (s *fastSandboxPolicyServer) applyreturn http.StatusInternalServerError, fmt.Errorf("vault bundle re-stamp failed: %w", err)}+ // The whole import holds policyCommitMu (vault-write parity with+ // handleVaultRelayWrite): the validation policy and the registration+ // fence cannot change between the pre-reads and the commit. Lock+ // order: policyCommitMu → registry → s.mu.++ if s.subjectRebinding(subj) {++ return http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")++ }+ s.policyCommitMu.Lock()+ defer s.policyCommitMu.Unlock()+ validation := s.vaultValidationPolicy(subj)s.mu.Lock()defer s.mu.Unlock()+ if s.subjectRebindingLocked(subj) {+ return http.StatusServiceUnavailable, fmt.Errorf("subject rebind in progress")+ }// The latch freezes every vault file mutation; only a restart// reconciles (relay-write parity).if recovery := s.vaultRecovery.Load(); recovery != nil {