An open-source, faster Devin alternative
TypeScript
fix(deploy): consume standard sandboxes for repo builds
Igor Zalutski8c3a5715c00a
diff --git a/.github/workflows/flue-managed-build-golden.yml b/.github/workflows/flue-managed-build-golden.ymlindex 5848173b..b0c8ceb3 100644--- a/.github/workflows/flue-managed-build-golden.yml+++ b/.github/workflows/flue-managed-build-golden.yml@@ -41,7 +41,7 @@ jobs:with:node-version: '22.19.0'- - name: Verify pinned builder snapshot and substrate probe+ - name: Verify pinned builder snapshot and sandbox proberun: |python3 deploy/flue-builder/snapshot.py checkpython3 ci/flue-builder-substrate-probe.py --checkdiff --git a/ci/flue-builder-substrate-probe.py b/ci/flue-builder-substrate-probe.pyindex 75f00b02..c9a983aa 100755--- a/ci/flue-builder-substrate-probe.py+++ b/ci/flue-builder-substrate-probe.py@@ -1,19 +1,16 @@#!/usr/bin/env python3-"""Prove the Flue build sandbox's final network and credential topology."""+"""Prove the pinned Flue builder in an ordinary OpenComputer sandbox."""from __future__ import annotationsimport argparseimport base64import importlib.util-import ipaddressimport jsonimport osfrom pathlib import Path-import reimport secretsimport sys-import timefrom typing import Anyfrom urllib import error, parse, requestimport uuid@@ -22,13 +19,8 @@ import uuidROOT = Path(__file__).resolve().parents[1]SNAPSHOT_MODULE_PATH = ROOT / "deploy" / "flue-builder" / "snapshot.py"PRODUCTION_HOSTS = {"app.opencomputer.dev", "api.opencomputer.dev"}-FINAL_NETWORK_POLICY = "public"-METADATA_URL = "http://169.254.169.254/v1/status"-NPM_PROBE_PACKAGE = "[email protected]"-PRIVATE_CANARY_NETWORKS = tuple(- ipaddress.ip_network(value)- for value in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10")-)+STARTER_REPO = "https://github.com/diggerhq/oc-flue-starter.git"+STARTER_REF = "5c51d7edbbf2472fbe48386c4f9b192279330c9b"FORBIDDEN_CREDENTIAL_NAMES = ("OPENCOMPUTER_API_KEY","GITHUB_TOKEN",@@ -69,21 +61,6 @@ def require_env(name: str) -> str:return value-def validate_private_canary(raw: str) -> str:- parsed = parse.urlsplit(raw)- if parsed.scheme not in {"http", "https"} or not parsed.hostname:- raise ProbeError("AGENT_BUILD_PRIVATE_CANARY_URL must be an absolute HTTP(S) URL")- if parsed.username or parsed.password or parsed.query or parsed.fragment:- raise ProbeError("private canary URL must not contain credentials, query, or fragment")- try:- address = ipaddress.ip_address(parsed.hostname)- except ValueError as exc:- raise ProbeError("private canary host must be a literal IPv4 address") from exc- if address.version != 4 or not any(address in network for network in PRIVATE_CANARY_NETWORKS):- raise ProbeError("private canary must use RFC1918 or CGNAT IPv4 space")- return raw--def safe_api_url(raw: str) -> str:try:normalized = SNAPSHOT.normalize_api_url(raw)@@ -102,12 +79,17 @@ def static_check() -> tuple[dict[str, Any], dict[str, Any]]:coordinate, manifest = SNAPSHOT.check_recipe()except SNAPSHOT.SnapshotError as exc:raise ProbeError(str(exc)) from exc- if coordinate["snapshot"].get("networkPolicy") != FINAL_NETWORK_POLICY:- raise ProbeError("probe requires the final networkPolicy=public topology")- if METADATA_URL != "http://169.254.169.254/v1/status":- raise ProbeError("probe metadata coordinate has drifted")- if NPM_PROBE_PACKAGE != "[email protected]":- raise ProbeError("probe npm package coordinate has drifted")+ if set(coordinate["snapshot"]) != {"name", "builderMemoryMB", "runtimeMemoryMB"}:+ raise ProbeError("builder coordinate must use only ordinary snapshot fields")+ if set(coordinate["attestation"]) != {+ "schemaVersion", "snapshotName", "baseImage", "platform", "node", "npm", "oc",+ "buildToolchain",+ }:+ raise ProbeError("builder attestation must contain only toolchain coordinates")+ if STARTER_REPO != "https://github.com/diggerhq/oc-flue-starter.git":+ raise ProbeError("golden starter repository coordinate has drifted")+ if len(STARTER_REF) != 40 or any(c not in "0123456789abcdef" for c in STARTER_REF):+ raise ProbeError("golden starter ref must be a lowercase commit SHA")return coordinate, manifest@@ -126,27 +108,23 @@ class LiveProbe:raise ProbeError("AGENT_BUILD_SANDBOX_CHECKPOINT_ID must be a UUID from snapshot.py's receipt") from exc- configured_snapshot = require_env("AGENT_BUILD_SANDBOX_SNAPSHOT")- if configured_snapshot != self.snapshot_name:- raise ProbeError("AGENT_BUILD_SANDBOX_SNAPSHOT does not match coordinate.json")- expected_node = coordinate["attestation"]["node"]["version"]- if require_env("AGENT_BUILD_NODE_VERSION") != expected_node:- raise ProbeError("AGENT_BUILD_NODE_VERSION does not match coordinate.json")- if os.environ.get("AGENT_BUILD_PROBE_ALLOW_UNRESTRICTED_CONTROL") != "1":- raise ProbeError(- "set AGENT_BUILD_PROBE_ALLOW_UNRESTRICTED_CONTROL=1 to permit the control sandbox"- )- self.private_canary = validate_private_canary(- require_env("AGENT_BUILD_PRIVATE_CANARY_URL")- )- self.private_marker = require_env("AGENT_BUILD_PRIVATE_CANARY_EXPECT")- if not (4 <= len(self.private_marker) <= 128) or "\n" in self.private_marker:- raise ProbeError("private canary marker must be a 4-128 character non-secret string")++ expected = coordinate["attestation"]+ configured = {+ "AGENT_BUILD_SANDBOX_SNAPSHOT": self.snapshot_name,+ "AGENT_BUILD_NODE_VERSION": expected["node"]["version"],+ "AGENT_BUILD_NPM_VERSION": expected["npm"]["version"],+ "AGENT_BUILD_OC_VERSION": expected["oc"]["version"],+ "AGENT_BUILD_OC_BINARY_SHA256": expected["oc"]["binarySha256"],+ }+ for name, expected_value in configured.items():+ if require_env(name) != expected_value:+ raise ProbeError(f"{name} does not match coordinate.json")+self.sandboxes: list[str] = []- # Put synthetic values under the real forbidden names in this trusted- # coordinator process. The raw adapter below constructs every body- # explicitly; none of these values may cross into the guest.+ # These values exist only in the trusted probe process. Sandbox request+ # bodies are constructed explicitly below and never include its env.self.sentinels: dict[str, str] = {}for name in FORBIDDEN_CREDENTIAL_NAMES:original = os.environ.get(name)@@ -181,10 +159,10 @@ class LiveProbe:if snapshot.get("checkpointId") != self.checkpoint_id:raise ProbeError("snapshot checkpoint differs from the immutable receipt coordinate")- def create_sandbox(self, restricted: bool) -> tuple[str, dict[str, Any]]:- body: dict[str, Any] = {"snapshot": self.snapshot_name, "timeout": 600}- if restricted:- body["networkPolicy"] = FINAL_NETWORK_POLICY+ def create_sandbox(self) -> str:+ # This is deliberately the normal public create shape. In particular it+ # carries no credentials, secret store, or feature-specific policy.+ body = {"snapshot": self.snapshot_name, "timeout": 600}_, response = self.call("POST", "/sandboxes", body, allowed_statuses={201}, timeout=180)if not isinstance(response, dict) or not isinstance(response.get("sandboxID"), str):raise ProbeError("sandbox create response is missing sandboxID")@@ -192,9 +170,7 @@ class LiveProbe:self.sandboxes.append(sandbox_id)if response.get("fromCheckpointId") != self.checkpoint_id:raise ProbeError("sandbox did not fork the pinned checkpoint")- if restricted and int(response.get("hostPort") or 0) != 0:- raise ProbeError("restricted sandbox unexpectedly received an inbound host port")- return sandbox_id, response+ return sandbox_iddef exec(self,@@ -241,270 +217,65 @@ class LiveProbe:raise ProbeError(f"{label} failed inside the sandbox")return str(response.get("stdout", ""))- @staticmethod- def expect_transport_block(label: str, response: dict[str, Any]) -> None:- exit_code = response["exitCode"]- if exit_code == 0:- raise ProbeError(f"{label} was reachable from the restricted sandbox")- if exit_code not in {7, 28}:- raise ProbeError(- f"{label} failed with exit {exit_code}, not a curl connection refusal/timeout"- )-- @staticmethod- def curl_args(url: str) -> list[str]:- return [- "--noproxy",- "*",- "--fail",- "--silent",- "--show-error",- "--connect-timeout",- "2",- "--max-time",- "5",- url,- ]-- def assert_builder_attestation(self, sandbox_id: str) -> None:- self.expect_success(- "non-root runtime verifier",- self.exec(- sandbox_id,- "/opt/opencomputer/bin/verify-flue-builder-runtime",- ),- )-+ def assert_builder_runtime(self, sandbox_id: str) -> None:javascript = r"""const cp = require("child_process");const fs = require("fs");const run = (cmd, args) => cp.execFileSync(cmd, args, {encoding: "utf8"}).trim();-const endpointPaths = [- "/dev/virtio-ports/agent", "/dev/vport0p1", "/dev/vport1p1", "/dev/vport2p1",- "/tmp/osb-agent.sock"-];-const result = {+const marker = "/workspace/.flue-builder-probe-" + process.pid;+fs.writeFileSync(marker, "ok");+fs.unlinkSync(marker);+process.stdout.write(JSON.stringify({nodeVersion: process.versions.node,npmVersion: run("/usr/local/bin/npm", ["--version"]),ocVersion: run("/opt/opencomputer/bin/oc", ["--version"]),ocSha256: run("/usr/bin/sha256sum", ["/opt/opencomputer/bin/oc"]).split(/\s+/)[0],gitVersion: run("/usr/bin/git", ["--version"]),- runtimeUid: process.getuid(),- runtimeGid: process.getgid(),- runtimeGroups: process.getgroups().sort((a, b) => a - b),- nodeUid: fs.statSync("/opt/opencomputer/node-v22.19.0/bin/node").uid,- nodeMode: fs.statSync("/opt/opencomputer/node-v22.19.0/bin/node").mode & 0o777,- ocUid: fs.statSync("/opt/opencomputer/bin/oc").uid,- ocMode: fs.statSync("/opt/opencomputer/bin/oc").mode & 0o777,- verifierUid: fs.statSync("/opt/opencomputer/bin/verify-flue-builder-runtime").uid,- verifierMode: fs.statSync("/opt/opencomputer/bin/verify-flue-builder-runtime").mode & 0o777,- attestationUid: fs.statSync("/opt/opencomputer/agent-build-snapshot.json").uid,- attestationMode: fs.statSync("/opt/opencomputer/agent-build-snapshot.json").mode & 0o777,- sudoPresent: fs.existsSync("/usr/bin/sudo") || fs.existsSync("/bin/sudo"),- agentEndpoints: endpointPaths.filter((path) => fs.existsSync(path)).map((path) => {- const stat = fs.statSync(path);- return {path, uid: stat.uid, mode: stat.mode & 0o777};- }),installerRemoved: !fs.existsSync("/tmp/opencomputer-flue-builder-install.sh"),+ workspaceWritable: true,attestation: JSON.parse(fs.readFileSync("/opt/opencomputer/agent-build-snapshot.json", "utf8"))-};-process.stdout.write(JSON.stringify(result));+}));""".strip()raw = self.expect_success(- "builder attestation", self.exec(sandbox_id, "node", ["-e", javascript])+ "builder runtime attestation",+ self.exec(sandbox_id, "node", ["-e", javascript]),)try:observed = json.loads(raw)except json.JSONDecodeError as exc:- raise ProbeError("builder attestation command returned invalid JSON") from exc+ raise ProbeError("builder runtime attestation returned invalid JSON") from excattestation = self.coordinate["attestation"]expected = {"nodeVersion": attestation["node"]["version"],"npmVersion": attestation["npm"]["version"],+ "ocVersion": f"oc version {attestation['oc']['sourceCommit']}","ocSha256": attestation["oc"]["binarySha256"],- "runtimeUid": attestation["security"]["runtimeUid"],- "runtimeGid": attestation["security"]["runtimeGid"],- "runtimeGroups": [attestation["security"]["runtimeGid"]],- "nodeUid": 0,- "nodeMode": 0o755,- "ocUid": 0,- "ocMode": 0o555,- "verifierUid": 0,- "verifierMode": 0o555,- "attestationUid": 0,- "attestationMode": 0o444,- "sudoPresent": False,+ "installerRemoved": True,+ "workspaceWritable": True,"attestation": attestation,}for key, value in expected.items():if observed.get(key) != value:raise ProbeError(f"builder runtime differs from coordinate field {key}")- expected_oc_version = f"oc version {attestation['oc']['sourceCommit']}"- if observed.get("ocVersion") != expected_oc_version:- raise ProbeError("builder oc --version differs from the pinned source commit")if not str(observed.get("gitVersion", "")).startswith("git version "):raise ProbeError("builder snapshot is missing git")- if observed.get("installerRemoved") is not True:- raise ProbeError("builder installer was left in the runtime snapshot")- endpoints = observed.get("agentEndpoints")- if not isinstance(endpoints, list):- raise ProbeError("builder endpoint attestation is invalid")- for endpoint in endpoints:- if (- not isinstance(endpoint, dict)- or endpoint.get("uid") != 0- or endpoint.get("mode") != 0o600- ):- raise ProbeError("a guest agent transport node is accessible to repository code")-- self.prove_guest_agent_isolation(sandbox_id)-- def prove_guest_agent_isolation(self, sandbox_id: str) -> None:- # osb-agent is PID 1 and its unauthenticated RPC surface includes root- # exec, root file writes, and binary upgrade. This adversarial probe- # runs as uid 1000. It sends an HTTP/2 client preface to guest-local- # AF_VSOCK/Unix endpoints and fails if the root gRPC server answers;- # it also attempts to open every known virtio-serial agent device.- python = r'''-import array-import fcntl-import glob-import json-import os-import socket-import sys--HTTP2_PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"-EMPTY_SETTINGS = b"\x00\x00\x00\x04\x00\x00\x00\x00\x00"-failures = []-checked = []--def root_grpc_answered(sock):- sock.settimeout(1.0)- sock.sendall(HTTP2_PREFACE + EMPTY_SETTINGS)- try:- return bool(sock.recv(9))- except (ConnectionError, OSError, TimeoutError):- return False--if hasattr(socket, "AF_VSOCK"):- cids = {getattr(socket, "VMADDR_CID_LOCAL", 1)}- try:- values = array.array("I", [0])- with open("/dev/vsock", "rb", buffering=0) as device:- fcntl.ioctl(device.fileno(), 0x7B9, values, True)- cids.add(values[0])- except OSError:- pass- for cid in sorted(cids):- checked.append(f"vsock:{cid}:1024")- client = socket.socket(socket.AF_VSOCK, socket.SOCK_STREAM)- client.settimeout(1.0)- try:- client.connect((cid, 1024))- if root_grpc_answered(client):- failures.append(f"vsock:{cid}:1024")- except OSError:- pass- finally:- client.close()--devices = sorted(set(- glob.glob("/dev/virtio-ports/agent")- + glob.glob("/dev/vport0p1")- + glob.glob("/dev/vport1p1")- + glob.glob("/dev/vport2p1")-))-for path in devices:- checked.append(path)- try:- descriptor = os.open(path, os.O_RDWR | os.O_NONBLOCK)- except OSError:- continue- else:- os.close(descriptor)- failures.append(path)--unix_path = "/tmp/osb-agent.sock"-if os.path.exists(unix_path):- checked.append(unix_path)- client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)- client.settimeout(1.0)- try:- client.connect(unix_path)- if root_grpc_answered(client):- failures.append(unix_path)- except OSError:- pass- finally:- client.close()--print(json.dumps({"checked": checked, "failures": failures}, sort_keys=True))-if failures:- sys.exit(42)-'''.strip()- response = self.exec(- sandbox_id,- "/usr/bin/python3",- ["-c", python],- timeout=15,- )- if response["exitCode"] != 0:- raise ProbeError("repository code reached a root guest-agent control transport")- try:- result = json.loads(str(response.get("stdout", "")))- except json.JSONDecodeError as exc:- raise ProbeError("guest-agent isolation probe returned invalid JSON") from exc- if (- not isinstance(result.get("checked"), list)- or not result["checked"]- or result.get("failures") != []- ):- raise ProbeError("guest-agent isolation probe returned an invalid result")-- def prove_control_paths(self, sandbox_id: str) -> None:- private = self.expect_success(- "private control canary",- self.exec(sandbox_id, "curl", self.curl_args(self.private_canary)),- )- if self.private_marker not in private:- raise ProbeError("private control canary did not return its expected non-secret marker")- metadata = self.expect_success(- "metadata control path",- self.exec(- sandbox_id,- "curl",- self.curl_args(METADATA_URL),- ),- )- if not metadata.strip():- raise ProbeError("metadata control path returned an empty response")-- host_script = r'''+ def prove_golden_build(self, sandbox_id: str) -> None:+ script = r"""set -euo pipefail-gateway="$(ip -4 route show default | awk 'NR == 1 {print $3}')"-test -n "$gateway"-curl --noproxy '*' --fail --silent --show-error --connect-timeout 2 --max-time 5 "http://${gateway}:8888/"-'''.strip()- host = self.expect_success(- "guest-to-host control path",- self.exec(sandbox_id, "/bin/bash", ["-c", host_script]),- )- if not host.strip():- raise ProbeError("guest-to-host control path returned an empty response")-- def prove_public_npm(self, sandbox_id: str) -> None:- script = r'''-set -euo pipefail-mkdir -p "$HOME" "$npm_config_cache"-work="$(mktemp -d)"-trap 'rm -rf "$work"' EXIT-cd "$work"-package="$(npm pack --ignore-scripts --silent "$1")"-test -s "$package"-sha256sum "$package" >/dev/null-'''.strip()+root=/workspace/flue-builder-probe+rm -rf "$root"+mkdir -p "$root" "$HOME" "$npm_config_cache"+trap 'rm -rf "$root" "$HOME" "$npm_config_cache"' EXIT+git init -q "$root"+git -C "$root" remote add origin "$1"+git -C "$root" fetch -q --depth=1 origin "$2"+git -C "$root" checkout -q --detach FETCH_HEAD+test "$(git -C "$root" rev-parse HEAD)" = "$2"+cd "$root"+npm ci --no-audit --no-fund+OC_BIN=/opt/opencomputer/bin/oc npm run test:fixtures+""".strip()clean_env = {"PATH": "/opt/opencomputer/bin:/usr/local/bin:/usr/bin:/bin","HOME": "/tmp/flue-probe-home",@@ -514,130 +285,16 @@ sha256sum "$package" >/dev/null"TZ": "UTC",}self.expect_success(- "public npm registry and tarball",+ "public npm install and golden Flue artifact build",self.exec(sandbox_id,"/bin/bash",- ["-c", script, "probe", NPM_PROBE_PACKAGE],+ ["-c", script, "probe", STARTER_REPO, STARTER_REF],clean_env,- timeout=90,+ timeout=300,),)- def prove_restricted_paths(self, sandbox_id: str) -> None:- self.expect_transport_block(- "private service canary",- self.exec(sandbox_id, "curl", self.curl_args(self.private_canary)),- )- self.expect_transport_block(- "link-local metadata service",- self.exec(- sandbox_id,- "curl",- self.curl_args(METADATA_URL),- ),- )- host_script = r'''-set -euo pipefail-gateway="$(ip -4 route show default | awk 'NR == 1 {print $3}')"-test -n "$gateway"-curl --noproxy '*' --fail --silent --show-error --connect-timeout 2 --max-time 5 "http://${gateway}:8888/"-'''.strip()- self.expect_transport_block(- "guest-to-host service",- self.exec(sandbox_id, "/bin/bash", ["-c", host_script]),- )-- def start_inbound_test_server(self, sandbox_id: str) -> None:- javascript = (- 'require("http").createServer((_,res)=>res.end("flue-probe-ok"))'- '.listen(32123,"0.0.0.0");setInterval(()=>{},60000);'- )- start_script = (- "set -euo pipefail; "- "setsid node -e \"$1\" >/tmp/flue-probe-http.log 2>&1 </dev/null & "- "echo $! >/tmp/flue-probe-http.pid"- )- self.expect_success(- "local inbound test server start",- self.exec(sandbox_id, "/bin/bash", ["-c", start_script, "probe", javascript]),- )- readiness_script = r'''-set -euo pipefail-for _ in $(seq 1 30); do- if value="$(curl --noproxy '*' --fail --silent --connect-timeout 1 --max-time 2 "$1")"; then- printf '%s' "$value"- exit 0- fi- sleep 0.1-done-exit 1-'''.strip()- loopback = self.expect_success(- "local inbound test server loopback",- self.exec(- sandbox_id,- "/bin/bash",- ["-c", readiness_script, "probe", "http://127.0.0.1:32123/"],- ),- )- if loopback.strip() != "flue-probe-ok":- raise ProbeError("local inbound test server did not become ready")-- @staticmethod- def public_preview_body(hostname: str) -> bytes:- if not re.fullmatch(r"[A-Za-z0-9.-]+", hostname) or "." not in hostname:- raise ProbeError("preview API returned an invalid hostname")- opener = request.build_opener(SNAPSHOT.NoCredentialRedirect())- req = request.Request(f"https://{hostname}/", headers={"Accept": "text/plain"})- try:- with opener.open(req, timeout=5) as response:- return response.read(4096)- except error.HTTPError as exc:- return exc.read(4096)- except error.URLError:- return b""-- def prove_control_inbound(self, sandbox_id: str) -> None:- self.start_inbound_test_server(sandbox_id)- quoted = parse.quote(sandbox_id, safe="")- _, preview = self.call(- "POST",- f"/sandboxes/{quoted}/preview",- {"port": 32123},- allowed_statuses={200, 201},- )- if not isinstance(preview, dict) or not isinstance(preview.get("hostname"), str):- raise ProbeError("control preview response is missing hostname")- deadline = time.monotonic() + 30- while time.monotonic() < deadline:- if self.public_preview_body(preview["hostname"]).strip() == b"flue-probe-ok":- return- time.sleep(1)- raise ProbeError("unrestricted control preview never reached its live guest server")-- def prove_inbound_disabled(self, sandbox_id: str, create_response: dict[str, Any]) -> None:- self.start_inbound_test_server(sandbox_id)- quoted = parse.quote(sandbox_id, safe="")- status, _ = self.call(- "POST",- f"/sandboxes/{quoted}/preview",- {"port": 32123},- allowed_statuses={409},- )- if status != 409:- raise ProbeError("restricted sandbox preview creation was not rejected")-- sandbox_domain = create_response.get("sandboxDomain")- if not isinstance(sandbox_domain, str) or not sandbox_domain:- raise ProbeError("restricted sandbox response is missing sandboxDomain")- hostname = f"{sandbox_id}-p32123.{sandbox_domain}"- deadline = time.monotonic() + 10- while time.monotonic() < deadline:- if self.public_preview_body(hostname).strip() == b"flue-probe-ok":- raise ProbeError("restricted sandbox guest server was reachable through public ingress")- time.sleep(1)-def scan_guest_for_credentials(self, sandbox_id: str) -> None:javascript = r"""const fs = require("fs");@@ -668,7 +325,7 @@ try {for (const candidate of fs.readdirSync("/etc/profile.d")) add(path.join("/etc/profile.d", candidate));} catch (_) {}for (const entry of fs.readdirSync("/proc")) {- if (/^[0-9]+$/.test(entry)) add(`/proc/${entry}/environ`);+ if (/^[0-9]+$/.test(entry)) add("/proc/" + entry + "/environ");}process.stdout.write(JSON.stringify({payload: Buffer.concat(chunks).subarray(0, MAX_TOTAL).toString("base64"),@@ -689,13 +346,9 @@ process.stdout.write(JSON.stringify({if required not in seen:raise ProbeError(f"credential sentinel scan could not inspect {required}")- # Exec correctly runs as the unprivileged repository user. The trusted- # coordinator's file API is serviced by PID 1 and can still inspect- # PID 1's environment without restoring sudo to repository code.guest_bytes += b"\n/proc/1/environ\n" + self.read_guest_file(sandbox_id, "/proc/1/environ")-matches: list[str] = []for name, value in self.sentinels.items():raw = value.encode()@@ -708,8 +361,6 @@ process.stdout.write(JSON.stringify({if any(variant and variant in guest_bytes for variant in variants):matches.append(name)if matches:- # Names are safe diagnostics. Never print the matching values or- # the guest blob, which could itself contain unrelated secrets.raise ProbeError("credential sentinel values reached the guest: " + ", ".join(matches))def destroy_all(self) -> list[str]:@@ -724,32 +375,20 @@ process.stdout.write(JSON.stringify({return failuresdef run(self) -> None:- print("[1/8] validating immutable snapshot name, manifest, and checkpoint")+ print("[1/5] validating immutable snapshot name, manifest, and checkpoint")self.validate_snapshot()- print("[2/8] creating unrestricted control sandbox (explicitly authorized)")- control_id, _ = self.create_sandbox(restricted=False)- self.assert_builder_attestation(control_id)-- print("[3/8] proving private, metadata, and guest-host control targets are live")- self.prove_control_paths(control_id)- self.prove_control_inbound(control_id)-- print("[4/8] creating final-topology networkPolicy=public sandbox")- restricted_id, restricted_response = self.create_sandbox(restricted=True)- self.assert_builder_attestation(restricted_id)-- print("[5/8] proving public npm registry and package tarball egress")- self.prove_public_npm(restricted_id)+ print("[2/5] creating an ordinary disposable OpenComputer sandbox")+ sandbox_id = self.create_sandbox()- print("[6/8] proving private, link-local/metadata, and guest-host denial")- self.prove_restricted_paths(restricted_id)+ print("[3/5] verifying the exact toolchain and writable workspace")+ self.assert_builder_runtime(sandbox_id)- print("[7/8] proving inbound host-port and preview paths are disabled")- self.prove_inbound_disabled(restricted_id, restricted_response)+ print("[4/5] running public npm install and the golden Flue artifact build")+ self.prove_golden_build(sandbox_id)- print("[8/8] proving coordinator credential sentinels are absent from the guest")- self.scan_guest_for_credentials(restricted_id)+ print("[5/5] proving coordinator credential sentinels were not passed to the sandbox")+ self.scan_guest_for_credentials(sandbox_id)def parse_args() -> argparse.Namespace:@@ -768,7 +407,7 @@ def main() -> int:coordinate, manifest = static_check()if args.check:print(- "Flue builder substrate probe is runnable for "+ "Flue builder sandbox probe is runnable for "f"{coordinate['snapshot']['name']} ({coordinate['recipe']['materializedManifestSha256']})")return 0@@ -787,7 +426,7 @@ def main() -> int:)if cleanup_failures:return 1- print("PASS: final Flue build topology permits public npm only and exposes no credential sentinels")+ print("PASS: ordinary Flue build sandbox produced the golden artifact without coordinator credentials")return 0diff --git a/ci/test_flue_builder_substrate_probe.py b/ci/test_flue_builder_substrate_probe.pyindex 4df662ec..5694bc88 100644--- a/ci/test_flue_builder_substrate_probe.py+++ b/ci/test_flue_builder_substrate_probe.py@@ -10,86 +10,21 @@ from unittest import mockPROBE_PATH = Path(__file__).with_name("flue-builder-substrate-probe.py")SPEC = importlib.util.spec_from_file_location("flue_builder_substrate_probe", PROBE_PATH)if SPEC is None or SPEC.loader is None:- raise RuntimeError("cannot load substrate probe")+ raise RuntimeError("cannot load sandbox probe")PROBE = importlib.util.module_from_spec(SPEC)SPEC.loader.exec_module(PROBE)-class SubstrateProbeTest(unittest.TestCase):- def test_static_contract_is_pinned(self) -> None:+class SandboxProbeTest(unittest.TestCase):+ def test_static_contract_uses_an_ordinary_sandbox(self) -> None:coordinate, manifest = PROBE.static_check()- self.assertEqual(coordinate["snapshot"]["networkPolicy"], "public")- self.assertEqual(coordinate["snapshot"]["roles"], ["source", "build"])- self.assertEqual(manifest["runtimeMemoryMB"], 1024)- self.assertEqual(- coordinate["attestation"]["security"],- {- "runtimeUser": "sandbox",- "runtimeUid": 1000,- "runtimeGid": 1000,- "supplementaryGroups": [],- "sudoPolicy": "binary-removed",- "agentControl": "host-only",- "toolchainOwner": "root",- "workspace": "/workspace",- "workspaceWritable": True,- },- )- def test_root_finalization_precedes_non_root_runtime_proof(self) -> None:- _, manifest = PROBE.static_check()self.assertEqual(- manifest["steps"][-2],- {- "type": "run",- "args": {- "commands": [- "sudo -n bash /tmp/opencomputer-flue-builder-install.sh finalize"- ]- },- },- )- self.assertEqual(- manifest["steps"][-1],- {- "type": "run",- "args": {- "commands": [- "bash /opt/opencomputer/bin/verify-flue-builder-runtime"- ]- },- },- )-- def test_sudo_scan_targets_entrypoints_not_package_directories(self) -> None:- installer = (PROBE.ROOT / "deploy" / "flue-builder" / "install-snapshot.sh").read_text()- entrypoint_scan = (- r"find / -xdev \( -type f -o -type l \) "- r"\( -name sudo -o -name sudoedit \)"+ set(coordinate["snapshot"]),+ {"name", "builderMemoryMB", "runtimeMemoryMB"},)- self.assertGreaterEqual(installer.count(entrypoint_scan), 2)- self.assertNotIn("find / -xdev -name sudo", installer)- self.assertIn("/usr/share/doc/sudo", installer)- self.assertIn("/usr/lib/*/sudo", installer)-- def test_private_canary_requires_literal_private_or_cgnat_address(self) -> None:- for value in (- "http://10.1.2.3/probe",- "https://172.16.0.1:8443/probe",- "http://192.168.1.1/probe",- "http://100.64.1.2/probe",- ):- self.assertEqual(PROBE.validate_private_canary(value), value)-- for value in (- "https://example.com/probe",- "https://8.8.8.8/probe",- "http://169.254.169.254/probe",- "http://user:[email protected]/probe",- "http://10.1.2.3/probe?token=nope",- ):- with self.subTest(value=value), self.assertRaises(PROBE.ProbeError):- PROBE.validate_private_canary(value)+ self.assertEqual(manifest["runtimeMemoryMB"], 1024)+ self.assertEqual(PROBE.STARTER_REF, "5c51d7edbbf2472fbe48386c4f9b192279330c9b")def test_production_and_http_urls_require_separate_guards(self) -> None:with mock.patch.dict(os.environ, {}, clear=True):@@ -115,35 +50,7 @@ class SubstrateProbeTest(unittest.TestCase):"http://127.0.0.1:8080/api",)- def test_only_curl_connection_failure_counts_as_transport_block(self) -> None:- for exit_code in (7, 28):- PROBE.LiveProbe.expect_transport_block("target", {"exitCode": exit_code})- for exit_code in (0, 22, 35, 127):- with self.subTest(exit_code=exit_code), self.assertRaises(PROBE.ProbeError):- PROBE.LiveProbe.expect_transport_block("target", {"exitCode": exit_code})-- def test_guest_agent_isolation_requires_adversarial_probe_success(self) -> None:- live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)- live.exec = mock.Mock(- return_value={"exitCode": 0, "stdout": '{"checked":["vsock:1:1024"],"failures":[]}'}- )- live.prove_guest_agent_isolation("sb-test")- command = live.exec.call_args.args- self.assertEqual(command[:2], ("sb-test", "/usr/bin/python3"))- self.assertIn("HTTP2_PREFACE", command[2][1])-- live.exec.return_value = {- "exitCode": 42,- "stdout": '{"checked":["vsock:1:1024"],"failures":["vsock:1:1024"]}',- }- with self.assertRaises(PROBE.ProbeError):- live.prove_guest_agent_isolation("sb-test")-- live.exec.return_value = {"exitCode": 0, "stdout": '{"checked":[],"failures":[]}'}- with self.assertRaises(PROBE.ProbeError):- live.prove_guest_agent_isolation("sb-test")-- def test_create_body_is_allowlisted_and_final_topology_is_explicit(self) -> None:+ def test_create_body_is_the_standard_snapshot_create_shape(self) -> None:live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)live.snapshot_name = "snapshot-coordinate"live.checkpoint_id = "00000000-0000-0000-0000-000000000001"@@ -165,7 +72,7 @@ class SubstrateProbeTest(unittest.TestCase):}live.call = fake_call- live.create_sandbox(restricted=True)+ self.assertEqual(live.create_sandbox(), "sb-test")self.assertEqual(calls,[@@ -175,13 +82,51 @@ class SubstrateProbeTest(unittest.TestCase):{"snapshot": "snapshot-coordinate","timeout": 600,- "networkPolicy": "public",},)],)- self.assertNotIn("envs", calls[0][2])- self.assertNotIn("secretStore", calls[0][2])+ body = calls[0][2]+ self.assertIsInstance(body, dict)+ self.assertNotIn("envs", body)+ self.assertNotIn("secretStore", body)++ def test_create_rejects_a_different_checkpoint(self) -> None:+ live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)+ live.snapshot_name = "snapshot-coordinate"+ live.checkpoint_id = "00000000-0000-0000-0000-000000000001"+ live.sandboxes = []+ live.call = lambda *_args, **_kwargs: (+ 201,+ {+ "sandboxID": "sb-test",+ "fromCheckpointId": "00000000-0000-0000-0000-000000000002",+ },+ )++ with self.assertRaisesRegex(PROBE.ProbeError, "pinned checkpoint"):+ live.create_sandbox()+ self.assertEqual(live.sandboxes, ["sb-test"])++ def test_destroy_attempts_every_created_sandbox(self) -> None:+ live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)+ live.sandboxes = ["sb-one", "sb-two"]+ calls: list[str] = []++ def fake_call(+ _method: str,+ path: str,+ _body: object = None,+ allowed_statuses: set[int] | None = None,+ timeout: float = 60,+ ) -> tuple[int, object]:+ calls.append(path)+ return 204, None++ live.call = fake_call+ self.assertEqual(live.destroy_all(), [])+ self.assertEqual(calls, ["/sandboxes/sb-two", "/sandboxes/sb-one"])+ self.assertEqual(live.sandboxes, [])if __name__ == "__main__":diff --git a/cmd/agent/listen_linux.go b/cmd/agent/listen_linux.goindex 162d6a1b..06f52a8e 100644--- a/cmd/agent/listen_linux.go+++ b/cmd/agent/listen_linux.go@@ -56,11 +56,6 @@ func listenPortForPTY(port uint32) (net.Listener, error) {if err != nil {return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)}- if err := restrictAgentEndpoint(sockPath); err != nil {- lis.Close()- os.Remove(sockPath)- return nil, err- }log.Printf("agent: PTY data listening on %s", sockPath)return lis, nil}@@ -84,10 +79,6 @@ func listenVirtioSerial(path string) (net.Listener, error) {if err != nil {return nil, fmt.Errorf("open virtio-serial %s: %w", path, err)}- if err := restrictAgentEndpoint(path); err != nil {- f.Close()- return nil, err- }// Mark CLOEXEC so the fd is closed on agent re-exec (upgrade).// Without this, syscall.Exec inherits the fd, the host never sees the@@ -293,7 +284,7 @@ func (a vsockAddr) String() string { return fmt.Sprintf("vsock(%d:%d)", a.cid,func (l *vsockListener) Accept() (net.Conn, error) {for {- nfd, remote, err := unix.Accept(l.fd)+ nfd, _, err := unix.Accept(l.fd)if err != nil {select {case <-l.closed:@@ -302,14 +293,6 @@ func (l *vsockListener) Accept() (net.Conn, error) {}return nil, fmt.Errorf("vsock accept: %w", err)}- remoteVM, ok := remote.(*unix.SockaddrVM)- if !ok || !isTrustedAgentVsockPeer(remoteVM.CID) {- // The agent RPC surface includes root exec, root file writes, and- // binary upgrade. It is intentionally reachable only from CID 2,- // the hypervisor host. In-guest AF_VSOCK loopback is untrusted.- unix.Close(nfd)- continue- }return newRawVsockConn(nfd), nil}}@@ -355,11 +338,6 @@ func listenUnix(vsockErr error) (net.Listener, error) {if err != nil {return nil, fmt.Errorf("unix listen: %w (vsock: %v)", err, vsockErr)}- if err := restrictAgentEndpoint(sockPath); err != nil {- lis.Close()- os.Remove(sockPath)- return nil, err- }log.Printf("agent: listening on %s (vsock not available: %v)", sockPath, vsockErr)return lis, nil}diff --git a/cmd/agent/listen_other.go b/cmd/agent/listen_other.goindex b45d5b5f..4a044ddc 100644--- a/cmd/agent/listen_other.go+++ b/cmd/agent/listen_other.go@@ -18,11 +18,6 @@ func listenVsock() (net.Listener, error) {if err != nil {return nil, err}- if err := restrictAgentEndpointForOwner(sockPath, os.Geteuid(), os.Getegid()); err != nil {- lis.Close()- os.Remove(sockPath)- return nil, err- }log.Printf("agent: listening on %s (non-Linux, vsock not available)", sockPath)return lis, nil}@@ -36,11 +31,6 @@ func listenPortForPTY(port uint32) (net.Listener, error) {if err != nil {return nil, fmt.Errorf("pty unix listen port %d: %w", port, err)}- if err := restrictAgentEndpointForOwner(sockPath, os.Geteuid(), os.Getegid()); err != nil {- lis.Close()- os.Remove(sockPath)- return nil, err- }log.Printf("agent: PTY data listening on %s (vsock not available)", sockPath)return lis, nil}diff --git a/cmd/agent/transport_security.go b/cmd/agent/transport_security.godeleted file mode 100644index 5dcb5b48..00000000--- a/cmd/agent/transport_security.go+++ /dev/null@@ -1,45 +0,0 @@-package main--import (- "fmt"- "os"- "syscall"-)--const (- // Linux reserves CID 2 for the host side of an AF_VSOCK connection.- // Guest-local callers use CID 1 (VMADDR_CID_LOCAL) or the guest's own- // transport CID and must never reach the root agent RPC surface.- vsockHostCID = uint32(2)-- agentEndpointMode = os.FileMode(0600)-)--func isTrustedAgentVsockPeer(cid uint32) bool {- return cid == vsockHostCID-}--// restrictAgentEndpoint makes a guest-side transport node usable only by the-// root agent. Host control continues through the already-open virtio-serial-// device or the host-owned side of the Unix socket.-func restrictAgentEndpoint(path string) error {- return restrictAgentEndpointForOwner(path, 0, 0)-}--func restrictAgentEndpointForOwner(path string, uid int, gid int) error {- if err := os.Chown(path, uid, gid); err != nil {- return fmt.Errorf("own agent endpoint %s: %w", path, err)- }- if err := os.Chmod(path, agentEndpointMode); err != nil {- return fmt.Errorf("restrict agent endpoint %s: %w", path, err)- }- info, err := os.Stat(path)- if err != nil {- return fmt.Errorf("stat agent endpoint %s: %w", path, err)- }- stat, ok := info.Sys().(*syscall.Stat_t)- if !ok || int(stat.Uid) != uid || info.Mode().Perm() != agentEndpointMode {- return fmt.Errorf("agent endpoint %s did not retain owner %d and mode %#o", path, uid, agentEndpointMode)- }- return nil-}diff --git a/cmd/agent/transport_security_test.go b/cmd/agent/transport_security_test.godeleted file mode 100644index a7f17b91..00000000--- a/cmd/agent/transport_security_test.go+++ /dev/null@@ -1,76 +0,0 @@-package main--import (- "os"- "path/filepath"- "syscall"- "testing"-)--func TestIsTrustedAgentVsockPeerAllowsOnlyHost(t *testing.T) {- for _, test := range []struct {- name string- cid uint32- trusted bool- }{- {name: "local transport", cid: 1, trusted: false},- {name: "host", cid: 2, trusted: true},- {name: "guest transport", cid: 3, trusted: false},- {name: "wildcard", cid: ^uint32(0), trusted: false},- } {- t.Run(test.name, func(t *testing.T) {- if got := isTrustedAgentVsockPeer(test.cid); got != test.trusted {- t.Fatalf("isTrustedAgentVsockPeer(%d) = %v, want %v", test.cid, got, test.trusted)- }- })- }-}--func TestRestrictAgentEndpointRemovesGuestAccess(t *testing.T) {- path := filepath.Join(t.TempDir(), "agent-endpoint")- if err := os.WriteFile(path, nil, 0666); err != nil {- t.Fatal(err)- }- if err := restrictAgentEndpointForOwner(path, os.Geteuid(), os.Getegid()); err != nil {- t.Fatal(err)- }- info, err := os.Stat(path)- if err != nil {- t.Fatal(err)- }- if got := info.Mode().Perm(); got != agentEndpointMode {- t.Fatalf("endpoint mode = %#o, want %#o", got, agentEndpointMode)- }- stat, ok := info.Sys().(*syscall.Stat_t)- if !ok {- t.Fatal("endpoint stat has no syscall metadata")- }- if got := int(stat.Uid); got != os.Geteuid() {- t.Fatalf("endpoint uid = %d, want agent uid %d", got, os.Geteuid())- }-}--func TestRestrictAgentEndpointRequiresRootOwnership(t *testing.T) {- path := filepath.Join(t.TempDir(), "root-agent-endpoint")- if err := os.WriteFile(path, nil, 0666); err != nil {- t.Fatal(err)- }- err := restrictAgentEndpoint(path)- if os.Geteuid() != 0 {- if err == nil {- t.Fatal("non-root agent unexpectedly created a root-owned endpoint")- }- return- }- if err != nil {- t.Fatal(err)- }- info, err := os.Stat(path)- if err != nil {- t.Fatal(err)- }- stat := info.Sys().(*syscall.Stat_t)- if stat.Uid != 0 || info.Mode().Perm() != agentEndpointMode {- t.Fatalf("root endpoint uid:mode = %d:%#o", stat.Uid, info.Mode().Perm())- }-}diff --git a/deploy/flue-builder/README.md b/deploy/flue-builder/README.mdindex 966407dd..22ac45ac 100644--- a/deploy/flue-builder/README.md+++ b/deploy/flue-builder/README.md@@ -1,13 +1,13 @@# Flue managed-build snapshot-This directory owns the immutable runtime used by the managed Flue repository-builder. It is an internal deployment asset, not a customer-selectable image.-Repository code runs here with public-only networking and without GitHub,-OpenComputer, R2, Cloudflare, WfP, or coordinator credentials. It runs as uid-1000 with no `sudo` binary or supplementary groups; the pinned toolchain is-root-owned while `/workspace` remains writable. The root guest-agent control-transport remains available to the trusted host but is unreachable from-repository processes inside the guest.+This directory owns the immutable toolchain image used by managed Flue+repository builds. It is an internal deployment asset, not a customer-selectable+image.++The image is an ordinary disposable OpenComputer sandbox created from the+standard `base` image through the existing snapshot and sandbox APIs. The+repository-deploy feature consumes those public APIs as-is and does not require+changes to lower sandbox-platform layers.## Pinned coordinate@@ -20,42 +20,39 @@ repository processes inside the guest.- npm 10.9.3 from that Node archive;- the exact OpenComputer source commit and source-archive digest;- Go 1.25.0, used only to build `oc`, and its archive digest;-- the reproducible Linux/amd64 `oc` binary digest;-- raw installer, image-template, and materialized-manifest digests;-- the required runtime `networkPolicy=public`; and-- the hardened runtime contract: `sandbox` uid/gid 1000 with no supplementary- groups, no `sudo` path, host-only guest-agent control, a root-owned read-only- toolchain, and writable `/workspace`.+- the reproducible Linux/amd64 `oc` binary digest; and+- raw installer, image-template, and materialized-manifest digests.The named snapshot is not the complete physical coordinate. The snapshot API'sready response supplies its immutable `checkpointId`. `snapshot.py create`-writes that ID to a receipt. The production canary and real-substrate probe-must configure both the reviewed snapshot name and that receipt's checkpoint-ID. Name-only validation is insufficient because an operator could delete and-recreate a snapshot.--The recipe starts from OpenComputer's trusted `base` image, verifies every-downloaded toolchain/source archive, and verifies the built `oc` bytes. The-checkpoint receipt freezes the resulting base and OS-package state. A future-rebuild is a new `rN` snapshot name, coordinate, and receipt even when the-toolchain versions do not change.--The base image normally grants `sandbox ALL=(ALL) NOPASSWD:ALL`. The recipe uses-that privilege only for trusted installation steps. Its penultimate step runs a-root finalizer that clears every supplementary group, removes every `sudo` path-from the root filesystem, locks the account password, restricts the active-virtio-serial/Unix agent nodes to root, makes `/opt/opencomputer` root-owned and-non-writable, preserves the user-owned workspace, installs a read-only runtime-verifier, and removes the installer. Removing `sudo` avoids relying on parsing-its alias/group/include policy language. The last image step runs the verifier-as the ordinary sandbox user. No privileged step follows finalization.--`osb-agent` is a root PID-1 gRPC server whose trusted host API necessarily-includes root exec, filesystem operations, and binary upgrade. Its AF_VSOCK-listener accepts only Linux host CID 2; guest-local/own-CID connections are-closed before gRPC sees them. The virtio-serial device and Unix fallback are-mode `0600`. This keeps host orchestration working without exposing that RPC-surface to untrusted lifecycle scripts.+writes that ID to a receipt. The build worker and live sandbox proof configure+both the reviewed snapshot name and that receipt's checkpoint ID. Name-only+validation is insufficient because an operator could delete and recreate a+snapshot.++The recipe verifies every downloaded toolchain/source archive and the built+`oc` bytes. The checkpoint freezes the resulting base and OS-package state. A+future rebuild gets a new `rN` snapshot name, coordinate, and receipt even when+the toolchain versions do not change.++## Credential separation++Isolation between repository access, build execution, and deployment authority+is an orchestration responsibility:++1. A short-lived source sandbox receives only the scoped repository credential+ needed to fetch one resolved commit.+2. The source sandbox emits a digest-checked, tokenless archive and is+ destroyed.+3. A separate ordinary sandbox created from this snapshot receives that archive+ and runs install/build commands without GitHub, OpenComputer, object-store,+ model, or Workers deployment credentials.+4. Trusted coordinator and deploy services move artifacts and hold their own+ narrowly scoped credentials outside repository code.++The build sandbox request must be constructed from an explicit allowlist. Do+not pass the worker process environment, an OpenComputer key, or a secret store+to the sandbox.## Offline validation@@ -64,28 +61,20 @@ These commands perform no API calls and create nothing:```bashpython3 deploy/flue-builder/snapshot.py checkpython3 ci/flue-builder-substrate-probe.py --check+python3 -m unittest ci/test_flue_builder_substrate_probe.py```-They verify the shell syntax, recipe digests, materialized manifest, memory-settings, runtime policy, finalizer ordering, generated runtime-verifier-syntax, and the installer-emitted security/toolchain attestation. CI runs both.--## Create a new production canary after review+They verify shell syntax, recipe digests, the materialized manifest, memory+settings, installer-emitted attestation, and the ordinary sandbox-create+contract. CI also runs the byte-identical managed-build golden fixture.-There is no separate development environment for this proof. Snapshot creation-is therefore an explicit, billable production write and is not part of routine-branch validation. First review the evergreen branch, merge the latest `main`-into it, and agree the new canary snapshot/resource plan. Never repoint, delete,-replace, or rebuild an existing snapshot/resource without separate operator-approval. If the reviewed name is already occupied by any earlier resource,-stop and bump the `rN` name plus every recipe coordinate before creating-anything.+## Create the immutable snapshot-With that plan approved, load a production operator key without printing it and-run:+Snapshot creation is an explicit, billable platform write. Load an API key+without printing it and run:```bash-export OPENCOMPUTER_API_URL='<approved-production-api>'+export OPENCOMPUTER_API_URL='https://app.opencomputer.dev'export OPENCOMPUTER_API_KEY='...'export AGENT_BUILD_SNAPSHOT_ALLOW_CREATE=1export AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1@@ -95,96 +84,59 @@ python3 deploy/flue-builder/snapshot.py create \--receipt /secure/operator-state/flue-build-node22-19-0-oc-c39b315-r2.json```-The command never deletes or replaces a snapshot. Its existing-name path is-validation-only and succeeds only for the exact pinned manifest, but the-operator plan above still requires asking before using an existing resource. A-mismatch fails and requires a new snapshot name. Known production hosts require-the separate `AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1` guard; local HTTP-requires `AGENT_BUILD_SNAPSHOT_ALLOW_HTTP=1`.+The command is idempotent only when an existing snapshot has the exact pinned+manifest. It never deletes or replaces a snapshot. A mismatch fails and+requires a new snapshot name. Known production hosts require the separate+production guard; local HTTP requires `AGENT_BUILD_SNAPSHOT_ALLOW_HTTP=1`.-Store the receipt in the deployment system's non-secret release metadata. Do-not commit environment files or API keys. Configure the build worker from the-receipt:+Store the receipt in non-secret release metadata. Do not commit environment+files or API keys. Configure the build worker from the coordinate and receipt:```textAGENT_BUILD_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r2AGENT_BUILD_SANDBOX_CHECKPOINT_ID=<receipt checkpointId>AGENT_BUILD_NODE_VERSION=22.19.0-AGENT_BUILD_NETWORK_POLICY=public+AGENT_BUILD_NPM_VERSION=10.9.3+AGENT_BUILD_OC_VERSION=oc@c39b31560cb78e0d5708a9eda4cfb30ec372eed9+AGENT_BUILD_OC_BINARY_SHA256=7f7286095aefe78c3027efb79465442070370c6dcf3cda67c9b1315949a42bc1```-For the fastest safe P1 path, use this same hardened snapshot/checkpoint for the-token-bearing source sandbox and the tokenless build sandbox until a smaller,-independently pinned source image exists:+Worker readiness must compare the live snapshot manifest and checkpoint ID to+these coordinates before claiming repository builds.-```text-AGENT_SOURCE_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r2-AGENT_SOURCE_SANDBOX_CHECKPOINT_ID=<same receipt checkpointId>-```+## Live ordinary-sandbox proof-They remain separate ephemeral sandboxes with different inputs: only the source-sandbox's controlled Git exec receives the short-lived repository token; the-build sandbox receives tokenless source bytes. Sharing an immutable base does-not merge those trust boundaries. Worker readiness must compare both live-snapshot names and checkpoint IDs to these coordinates before claiming source-or build work.--## Real-substrate proof--The live probe creates two short-lived sandboxes from the same checkpoint:--1. an explicitly authorized unrestricted control, proving that the private- canary, link-local metadata service, and guest-to-host service are actually- live; and-2. the final `networkPolicy=public` sandbox, proving public npm registry and- tarball access succeeds while those targets and inbound exposure fail.--It also requires the `sudo` binary to be absent, uid/gid 1000 to have no-supplementary groups, writes and deletes a workspace probe, verifies exact-Node/npm/`oc` versions and the `oc` digest, and checks root ownership/read-only-modes for the trusted binaries. An adversarial uid-1000 check sends an HTTP/2-preface to guest-local AF_VSOCK and Unix agent endpoints and fails if root gRPC-answers; it also tries to open every known virtio-serial agent node. It checks-that-the create response has no host port, proves a temporary non-secret server is-publicly reachable through the unrestricted control, then requires preview-creation to return 409 and the equivalent restricted guest server to remain-unreachable. Finally it scans guest process environments plus common-configuration files for exact credential sentinel values; the trusted file API-inspects PID 1 without restoring sudo to repository code. The raw adapter-constructs request bodies from an allowlist and never forwards the coordinator-process environment. Both sandboxes are destroyed in `finally`; a teardown-failure makes the probe fail and prints only the sandbox ID for operator-cleanup.--Provide a newly provisioned, disposable HTTP(S) production canary at a literal-RFC1918 or CGNAT address. It must be reachable from the newly approved-unrestricted control sandbox and return a short, non-secret marker. Do not put-credentials in its URL or marker. Then run:+The guarded live probe:++1. validates the named snapshot's manifest and immutable checkpoint receipt;+2. creates one disposable sandbox with the normal+ `{"snapshot": "...", "timeout": 600}` request;+3. verifies the exact Node, npm, and `oc` versions/digests and a writable+ `/workspace`;+4. fetches the pinned public starter, runs `npm ci`, and reproduces its golden+ Flue artifact with the pinned `oc`; and+5. confirms coordinator credential sentinels were not passed into the sandbox.++The probe destroys every sandbox in `finally`; a cleanup failure fails the run+and prints only the sandbox ID for operator cleanup.```bash-export OPENCOMPUTER_API_URL='<approved-production-api>'+export OPENCOMPUTER_API_URL='https://app.opencomputer.dev'export OPENCOMPUTER_API_KEY='...'export AGENT_BUILD_SANDBOX_SNAPSHOT='flue-build-node22-19-0-oc-c39b315-r2'export AGENT_BUILD_SANDBOX_CHECKPOINT_ID='<receipt checkpointId>'export AGENT_BUILD_NODE_VERSION='22.19.0'-export AGENT_BUILD_PRIVATE_CANARY_URL='http://10.0.0.10:8080/flue-probe'-export AGENT_BUILD_PRIVATE_CANARY_EXPECT='flue-private-canary-ok'-export AGENT_BUILD_PROBE_ALLOW_UNRESTRICTED_CONTROL=1+export AGENT_BUILD_NPM_VERSION='10.9.3'+export AGENT_BUILD_OC_VERSION='oc@c39b31560cb78e0d5708a9eda4cfb30ec372eed9'+export AGENT_BUILD_OC_BINARY_SHA256='7f7286095aefe78c3027efb79465442070370c6dcf3cda67c9b1315949a42bc1'export AGENT_BUILD_PROBE_ALLOW_PRODUCTION=1python3 ci/flue-builder-substrate-probe.py --run```-The script refuses known production hosts unless-`AGENT_BUILD_PROBE_ALLOW_PRODUCTION=1` is also set, and refuses HTTP control-planes unless `AGENT_BUILD_PROBE_ALLOW_HTTP=1` is set. The unrestricted control-guard is deliberately separate: without it, a policy regression could look-like a passing denial test merely because the target was down.--This repository does not create the production canary snapshot or run the live-proof in CI. They require the reviewed evergreen branch integrated with latest-`main`, deployed sandbox-policy code, a newly approved resource plan, a real-checkpoint receipt, a private control canary, and explicit operator authority.-Record the exact receipt and probe result in the cross-repository working-document after that controlled production-canary run.+The script refuses known production hosts without the production guard and+refuses HTTP control planes without `AGENT_BUILD_PROBE_ALLOW_HTTP=1`.++This proof deliberately tests the repository-deploy feature as a consumer of+OpenComputer's existing public sandbox contract, without feature-specific+sandbox variants.diff --git a/deploy/flue-builder/coordinate.json b/deploy/flue-builder/coordinate.jsonindex 8f0533b2..da1f3fc1 100644--- a/deploy/flue-builder/coordinate.json+++ b/deploy/flue-builder/coordinate.json@@ -2,17 +2,15 @@"schemaVersion": 1,"snapshot": {"name": "flue-build-node22-19-0-oc-c39b315-r2",- "roles": ["source", "build"],- "networkPolicy": "public","builderMemoryMB": 4096,"runtimeMemoryMB": 1024},"recipe": {"installer": "install-snapshot.sh",- "installerSha256": "8210ac33b9690de36689a97851cd7ac8b29c0d0fc8c25fe0454fbc1486875ce9",+ "installerSha256": "6d66f04a958579940b865b9ef17bfbee89b8a8e87a3e9d78430f2e84ea3d47e1","imageTemplate": "image.json",- "imageTemplateSha256": "e5e8827412e76e6da94f8c2f9b97ddfe25579637905ef4e6d2f7fa563712683f",- "materializedManifestSha256": "8b11a2f879a2ceedc2bd858019a886f06e9dacec43b719f9cf23447b7989d9a5"+ "imageTemplateSha256": "d1fc4f3cd27fd1248327f52d9d768a99c9a922d4f0fabf8bf0d6913e2d1e7cd2",+ "materializedManifestSha256": "a768a1c00e46c65540e485ac37ea1513ae6a2a9398941f782e26df5c312e69f9"},"attestation": {"schemaVersion": 1,@@ -39,17 +37,6 @@"buildToolchain": {"goVersion": "1.25.0","goArchiveSha256": "2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613"- },- "security": {- "runtimeUser": "sandbox",- "runtimeUid": 1000,- "runtimeGid": 1000,- "supplementaryGroups": [],- "sudoPolicy": "binary-removed",- "agentControl": "host-only",- "toolchainOwner": "root",- "workspace": "/workspace",- "workspaceWritable": true}}}diff --git a/deploy/flue-builder/image.json b/deploy/flue-builder/image.jsonindex 06e9a906..da46df7d 100644--- a/deploy/flue-builder/image.json+++ b/deploy/flue-builder/image.json@@ -32,23 +32,8 @@"args": {"commands": ["sudo -n bash /tmp/opencomputer-flue-builder-install.sh attest",- "bash /tmp/opencomputer-flue-builder-install.sh verify"- ]- }- },- {- "type": "run",- "args": {- "commands": [- "sudo -n bash /tmp/opencomputer-flue-builder-install.sh finalize"- ]- }- },- {- "type": "run",- "args": {- "commands": [- "bash /opt/opencomputer/bin/verify-flue-builder-runtime"+ "bash /tmp/opencomputer-flue-builder-install.sh verify",+ "sudo -n rm -f /tmp/opencomputer-flue-builder-install.sh"]}}diff --git a/deploy/flue-builder/install-snapshot.sh b/deploy/flue-builder/install-snapshot.shindex b0c8d088..0f9d22ae 100755--- a/deploy/flue-builder/install-snapshot.sh+++ b/deploy/flue-builder/install-snapshot.sh@@ -29,11 +29,6 @@ OC_VERSION="oc@${OC_SOURCE_COMMIT}"NODE_ROOT="/opt/opencomputer/node-v${NODE_VERSION}"OC_BIN="/opt/opencomputer/bin/oc"ATTESTATION="/opt/opencomputer/agent-build-snapshot.json"-RUNTIME_VERIFIER="/opt/opencomputer/bin/verify-flue-builder-runtime"-RUNTIME_USER="sandbox"-RUNTIME_UID="1000"-RUNTIME_GID="1000"-WORKSPACE="/workspace"die() {echo "flue builder snapshot: $*" >&2@@ -92,17 +87,6 @@ write_attestation() {"buildToolchain": {"goVersion": "$GO_VERSION","goArchiveSha256": "$GO_ARCHIVE_SHA256"- },- "security": {- "runtimeUser": "$RUNTIME_USER",- "runtimeUid": $RUNTIME_UID,- "runtimeGid": $RUNTIME_GID,- "supplementaryGroups": [],- "sudoPolicy": "binary-removed",- "agentControl": "host-only",- "toolchainOwner": "root",- "workspace": "$WORKSPACE",- "workspaceWritable": true}}EOF@@ -202,130 +186,10 @@ verify() {|| die "snapshot attestation does not match the installer contract"}-write_runtime_verifier() {- local output="$1"- local attestation_sha="$2"- cat >"$output" <<EOF-#!/usr/bin/env bash-set -euo pipefail--fail() {- echo "flue builder runtime verification failed: \$*" >&2- exit 1-}--# shellcheck disable=SC1091-source /etc/os-release-[[ "\${ID:-}" == "$OS_ID" ]] || fail "OS changed"-[[ "\${VERSION_ID:-}" == "$OS_VERSION_ID" ]] || fail "OS version changed"-[[ "\$(uname -m)" == "$ARCHITECTURE" ]] || fail "architecture changed"-[[ "\$(id -u)" == "$RUNTIME_UID" ]] || fail "expected uid $RUNTIME_UID"-[[ "\$(id -un)" == "$RUNTIME_USER" ]] || fail "expected user $RUNTIME_USER"-[[ "\$(id -g)" == "$RUNTIME_GID" ]] || fail "expected gid $RUNTIME_GID"-[[ "\$(id -G)" == "$RUNTIME_GID" ]] || fail "supplementary groups are present"-[[ "\$(node --version)" == "v${NODE_VERSION}" ]] || fail "Node version changed"-[[ "\$(npm --version)" == "$NPM_VERSION" ]] || fail "npm version changed"-[[ "\$($OC_BIN --version)" == "oc version $OC_SOURCE_COMMIT" ]] || fail "oc version changed"-printf '%s %s\n' "$OC_BINARY_SHA256" "$OC_BIN" | sha256sum --check --status \- || fail "oc binary digest changed"-printf '%s %s\n' "$attestation_sha" "$ATTESTATION" | sha256sum --check --status \- || fail "snapshot attestation changed"-[[ ! -w "$OC_BIN" ]] || fail "oc binary is writable"-[[ ! -w "/opt/opencomputer/bin" ]] || fail "toolchain bin directory is writable"-[[ ! -w "$NODE_ROOT" ]] || fail "Node toolchain is writable"-[[ ! -e /usr/bin/sudo && ! -e /bin/sudo ]] || fail "sudo executable was restored"-[[ -z "\$(find / -xdev \( -type f -o -type l \) \( -name sudo -o -name sudoedit \) -print -quit 2>/dev/null)" ]] \- || fail "a sudo executable entrypoint remains on the runtime root filesystem"-[[ -d "$WORKSPACE" && -w "$WORKSPACE" ]] || fail "workspace is not writable"-probe="\$(mktemp "$WORKSPACE/.flue-builder-write.XXXXXX")" \- || fail "cannot create a workspace file"-rm -f "\$probe"-EOF-}--install_runtime_verifier() {- require_root-- local attestation_sha- attestation_sha="$(sha256sum "$ATTESTATION" | awk '{print $1}')"- write_runtime_verifier "$RUNTIME_VERIFIER" "$attestation_sha"- chown root:root "$RUNTIME_VERIFIER"- chmod 0555 "$RUNTIME_VERIFIER"-}--remove_runtime_privilege_surfaces() {- # Empty the complete supplementary-group list. This is intentionally not an- # allow/deny list of familiar administrator groups: a base-image change must- # not silently preserve privilege through a differently named group.- usermod -G '' "$RUNTIME_USER"- usermod --lock "$RUNTIME_USER"- rm -rf "/run/sudo/ts/$RUNTIME_USER" "/var/run/sudo/ts/$RUNTIME_USER"-- # Sudoers is a rich policy language (aliases, groups, includes, commands).- # Trying to prove every policy path denied is brittle, so the managed image- # removes the setuid entrypoint itself after the last trusted sudo command.- # Search the root filesystem rather than assuming one package path. Remove- # regular files and symlinks named sudo/sudoedit, including alternate PATH- # locations and the sudoedit entrypoint, while preserving inert package- # directories such as /usr/share/doc/sudo and /usr/lib/*/sudo.- find / -xdev \( -type f -o -type l \) \( -name sudo -o -name sudoedit \) \- -exec rm -f -- {} + 2>/dev/null- [[ -z "$(find / -xdev \( -type f -o -type l \) \( -name sudo -o -name sudoedit \) -print -quit 2>/dev/null)" ]] \- || die "could not remove every sudo executable entrypoint"-}--harden_agent_transport_nodes() {- local path-- # The root guest agent owns root exec, filesystem, and upgrade RPCs. QEMU's- # virtio-serial device and the test-only Unix fallback must not be openable- # by repository code. AF_VSOCK peer rejection is enforced by osb-agent and- # exercised by the live substrate probe.- for path in /dev/virtio-ports/agent /dev/vport0p1 /dev/vport1p1 /dev/vport2p1 \- /tmp/osb-agent.sock; do- if [[ -e "$path" || -S "$path" ]]; then- chmod 0600 "$path"- fi- done-}--finalize() {- require_root- assert_platform- verify- install_runtime_verifier-- # Repository code must be able to write only its workspace. The trusted- # toolchain and attestation remain root-owned and immutable to uid 1000.- chown -R root:root /opt/opencomputer- chmod -R go-w /opt/opencomputer- chmod 0555 "$OC_BIN" "$RUNTIME_VERIFIER"- chmod 0444 "$ATTESTATION"- if [[ -d /home/sandbox ]]; then- chown -R "$RUNTIME_USER:$RUNTIME_USER" /home/sandbox- fi- if [[ -d "$WORKSPACE" && ! -L "$WORKSPACE" ]]; then- chown -R "$RUNTIME_USER:$RUNTIME_USER" "$WORKSPACE"- fi-- harden_agent_transport_nodes- remove_runtime_privilege_surfaces- [[ "$(runuser -u "$RUNTIME_USER" -- id -G)" == "$RUNTIME_GID" ]] \- || die "runtime user retains supplementary groups"-- # No later image-build operation needs privilege. Remove the root-capable- # installer before returning to the non-root image builder.- rm -f -- "$0"-}-case "${1:-}" incoordinate)write_attestation /dev/stdout;;- runtime-verifier)- write_runtime_verifier /dev/stdout \- 0000000000000000000000000000000000000000000000000000000000000000- ;;node)install_node;;@@ -338,10 +202,7 @@ case "${1:-}" inverify)verify;;- finalize)- finalize- ;;*)- die "usage: $0 {coordinate|runtime-verifier|node|oc|attest|verify|finalize}"+ die "usage: $0 {coordinate|node|oc|attest|verify}";;esacdiff --git a/deploy/flue-builder/snapshot.py b/deploy/flue-builder/snapshot.pyindex 6fe66026..4f01d253 100755--- a/deploy/flue-builder/snapshot.py+++ b/deploy/flue-builder/snapshot.py@@ -106,50 +106,12 @@ def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]:if snapshot.get("name") != expected_attestation.get("snapshotName"):raise SnapshotError("snapshot name and attestation snapshotName differ")- if snapshot.get("networkPolicy") != "public":- raise SnapshotError("the Flue builder snapshot must declare networkPolicy=public")- if snapshot.get("roles") != ["source", "build"]:- raise SnapshotError("the hardened snapshot must be pinned for source and build roles")if manifest.get("base") != expected_attestation.get("baseImage"):raise SnapshotError("image base and attestation baseImage differ")for key in ("builderMemoryMB", "runtimeMemoryMB"):if manifest.get(key) != snapshot.get(key):raise SnapshotError(f"manifest and coordinate disagree on {key}")- expected_finalize = {- "type": "run",- "args": {- "commands": [- "sudo -n bash /tmp/opencomputer-flue-builder-install.sh finalize"- ]- },- }- expected_runtime_proof = {- "type": "run",- "args": {- "commands": [- "bash /opt/opencomputer/bin/verify-flue-builder-runtime"- ]- },- }- if manifest["steps"][-2:] != [expected_finalize, expected_runtime_proof]:- raise SnapshotError(- "image must end with the root finalize step followed by the non-root runtime proof"- )- security = expected_attestation.get("security")- if security != {- "runtimeUser": "sandbox",- "runtimeUid": 1000,- "runtimeGid": 1000,- "supplementaryGroups": [],- "sudoPolicy": "binary-removed",- "agentControl": "host-only",- "toolchainOwner": "root",- "workspace": "/workspace",- "workspaceWritable": True,- }:- raise SnapshotError("attestation must pin the hardened non-root runtime contract")-syntax = subprocess.run(["bash", "-n", str(installer_path)],check=False,@@ -176,49 +138,6 @@ def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]:if actual_attestation != expected_attestation:raise SnapshotError("installer attestation and coordinate.json attestation differ")- runtime_verifier = subprocess.run(- ["bash", str(installer_path), "runtime-verifier"],- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- if runtime_verifier.returncode != 0:- raise SnapshotError(- f"installer runtime-verifier failed: {runtime_verifier.stderr.strip()}"- )- verifier_syntax = subprocess.run(- ["bash", "-n", "/dev/stdin"],- input=runtime_verifier.stdout,- check=False,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- )- if verifier_syntax.returncode != 0:- raise SnapshotError(- f"generated runtime verifier fails bash -n: {verifier_syntax.stderr.strip()}"- )- for command in (- '[[ "$(id -G)" == "1000" ]]',- "sudo executable was restored",- "a sudo executable entrypoint remains on the runtime root filesystem",- "sha256sum --check --status",- 'mktemp "/workspace/.flue-builder-write.XXXXXX"',- ):- if command not in runtime_verifier.stdout:- raise SnapshotError(f"generated runtime verifier is missing {command!r}")-- sudo_entrypoint_scan = (- r"find / -xdev \( -type f -o -type l \) "- r"\( -name sudo -o -name sudoedit \)"- )- installer_source = installer_path.read_text()- if installer_source.count(sudo_entrypoint_scan) < 2:- raise SnapshotError(- "finalizer and runtime verifier must scan sudo executable entrypoints without matching directories"- )-return coordinate, manifest@@ -374,7 +293,7 @@ def create_snapshot(args: argparse.Namespace) -> None:raise SnapshotError(f"snapshot ended in status {current.get('status')!r}")write_receipt(Path(args.receipt), current, coordinate)print(f"Snapshot is ready; immutable checkpoint receipt written to {args.receipt}")- print("Set AGENT_BUILD_SANDBOX_CHECKPOINT_ID from that receipt before running the substrate probe.")+ print("Set AGENT_BUILD_SANDBOX_CHECKPOINT_ID from that receipt before running the sandbox probe.")def parse_args() -> argparse.Namespace:diff --git a/docs/agent-sessions/flue.mdx b/docs/agent-sessions/flue.mdxindex 54913242..eaf2bf15 100644--- a/docs/agent-sessions/flue.mdx+++ b/docs/agent-sessions/flue.mdx@@ -90,9 +90,9 @@ commands, and build-time secrets are not supported.OpenComputer resolves the selected branch to one commit, fetches only that tracked tree in ashort-lived Git sandbox, and transfers tokenless source to a separate build sandbox. The build runs-fixed `npm ci --no-audit --no-fund` and offline `oc agent build` commands. Repository code receives-public-Internet-only egress for npm, but no GitHub token, OpenComputer key, model credential,-Workers credential, secret store, inbound port, or preview URL.+fixed `npm ci --no-audit --no-fund` and offline `oc agent build` commands in an ordinary disposable+OpenComputer sandbox. The build request carries no GitHub token, OpenComputer key, model+credential, Workers credential, or secret store.<Note>Repository import currently creates the initial deployment from the selected production branch.diff --git a/docs/agent-sessions/repos.mdx b/docs/agent-sessions/repos.mdxindex c6ee0221..a745ce80 100644--- a/docs/agent-sessions/repos.mdx+++ b/docs/agent-sessions/repos.mdx@@ -130,8 +130,9 @@ implementation itself. The dashboard uses the OpenComputer App to:The Git box writes a bounded, digest-checked source archive to object storage and is destroyed.A different sandbox receives that archive without `.git` or GitHub auth, runs the fixed install and-build commands with public-Internet-only egress, and emits an artifact. The Workers deployment-credential belongs to another trusted service and is never present during source or build work.+build commands as an ordinary disposable OpenComputer sandbox, and emits an artifact. The Workers+deployment credential belongs to another trusted service and is never present during source or+build work.Flue repository deployment currently supports one self-contained npm root with `agent.toml`,`package.json`, and `package-lock.json`. Automatic deployment on later pushes is not enabled;diff --git a/docs/agent-sessions/revisions.mdx b/docs/agent-sessions/revisions.mdxindex b1058003..a553e590 100644--- a/docs/agent-sessions/revisions.mdx+++ b/docs/agent-sessions/revisions.mdx@@ -120,8 +120,8 @@ The managed path is deliberately narrow: one self-contained npm root, a committe`package-lock.json`, a compatible `engines.node`, and a local `@flue/cli` dependency. OpenComputerfetches the exact commit with a repository-scoped GitHub App token in a source sandbox, removes Gitmetadata and auth, then runs `npm ci` and the offline builder in a separate tokenless sandbox. npm-lifecycle scripts do run, but that build sandbox has only host-enforced public-Internet egress and-no platform or deployment credential.+lifecycle scripts do run in that ordinary disposable OpenComputer sandbox, but its request carries+no source, platform, model, or deployment credential.The deployment detail page groups the attempt into **Queued**, **Source**, **Install**, **Build**,**Artifact**, **Deploy**, and **Verify**, with one persisted chronological log. An install/builddiff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex 7dad2d0b..d72fbf8b 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -113,9 +113,6 @@ 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@@ -189,7 +186,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, cfg.NetworkPolicy)+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)if cpErr != nil {return c.JSON(status, map[string]string{"error": cpErr.Error()})}diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 5f098594..33a4a504 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -63,9 +63,6 @@ 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.@@ -212,7 +209,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, cfg.NetworkPolicy)+ result, status, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)if cpErr != nil {return c.JSON(status, map[string]string{"error": cpErr.Error()})}@@ -400,7 +397,7 @@ func (s *Server) createSandboxWithSSE(c echo.Context, ctx context.Context, orgIDc.SetParamNames("checkpointId")c.SetParamValues(checkpointID.String())- result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB, cfg.NetworkPolicy)+ result, _, cpErr := s.createFromCheckpointCore(c, cfg.Envs, cfg.SecretStore, cfg.Metadata, cfg.MemoryMB)if cpErr != nil {emit("error", map[string]string{"error": cpErr.Error()})return nil@@ -560,96 +557,6 @@ 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.@@ -813,7 +720,6 @@ func (s *Server) createSandboxRemote(c echo.Context, ctx context.Context, cfg tyTimeout: int32(cfg.Timeout),Envs: cfg.Envs,NetworkEnabled: cfg.IsNetworkEnabled(),- NetworkPolicy: string(cfg.NetworkPolicy),Port: int32(cfg.Port),TemplateRootfsKey: templateRootfsKey,TemplateWorkspaceKey: templateWorkspaceKey,@@ -1885,7 +1791,6 @@ func (s *Server) migrateForScale(ctx context.Context, sandboxID string, sessionEgressAllowlist: 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)@@ -2779,7 +2684,6 @@ func (s *Server) promoteCheckpointToFull(ctx context.Context, checkpointID, promMemoryMb: int32(cfg.MemoryMB),CpuCount: int32(cfg.CpuCount),NetworkEnabled: cfg.IsNetworkEnabled(),- NetworkPolicy: string(cfg.NetworkPolicy),Port: int32(cfg.Port),TemplateRootfsKey: rootfsKey,TemplateWorkspaceKey: workspaceKey,@@ -2910,22 +2814,6 @@ 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{})}@@ -2989,14 +2877,13 @@ 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"`- NetworkPolicy types.NetworkPolicy `json:"networkPolicy"`+ Envs map[string]string `json:"envs"`+ SecretStore string `json:"secretStore"`+ Metadata map[string]string `json:"metadata"`+ MemoryMB int `json:"memoryMB"`}_ = c.Bind(&body)- result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata, body.MemoryMB, body.NetworkPolicy)+ result, httpStatus, err := s.createFromCheckpointCore(c, body.Envs, body.SecretStore, body.Metadata, body.MemoryMB)if err != nil {return c.JSON(httpStatus, map[string]string{"error": err.Error()})}@@ -3022,7 +2909,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, userNetworkPolicy types.NetworkPolicy) (map[string]interface{}, int, error) {+func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]string, userSecretStore string, userMetadata map[string]string, userMemoryMB int) (map[string]interface{}, int, error) {checkpointIDStr := c.Param("checkpointId")ctx := c.Request().Context()@@ -3109,15 +2996,6 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]st// Parse the original sandbox config to reuse settingsvar 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.@@ -3306,7 +3184,6 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]stMemoryMb: int32(originalCfg.MemoryMB),CpuCount: int32(originalCfg.CpuCount),NetworkEnabled: originalCfg.IsNetworkEnabled(),- NetworkPolicy: string(originalCfg.NetworkPolicy),Port: int32(originalCfg.Port),TemplateRootfsKey: forkRootfsKey,TemplateWorkspaceKey: forkWorkspaceKey,@@ -3813,15 +3690,6 @@ 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 requiredvar req struct {@@ -3850,8 +3718,9 @@ func (s *Server) createPreviewURL(c echo.Context) error {sandboxRunning = true}}- if !sandboxRunning {- if session.Status == "running" {+ if !sandboxRunning && s.store != nil {+ session, err := s.store.GetSandboxSession(ctx, sandboxID)+ if err == nil && session.Status == "running" && session.OrgID == orgID {sandboxRunning = true}}diff --git a/internal/api/sandbox_test.go b/internal/api/sandbox_test.goindex 22022213..b6ca3162 100644--- a/internal/api/sandbox_test.go+++ b/internal/api/sandbox_test.go@@ -9,7 +9,6 @@ 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) {@@ -118,123 +117,3 @@ 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.goindex 2cf107cc..f4858d9b 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 launchespendingWorkerTTL = 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.0emergencyMemThreshold = 95.0emergencyDiskThreshold = 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.HourcreationFailureThreshold = 3 // consecutive failures before exponential backoffcreationBackoffMin = 1 * time.Minute // initial backoff after threshold hit@@ -85,14 +85,14 @@ type OrphanCleaner interface {type ScalerConfig struct {Pool compute.PoolRegistry ScalerRegistry- Store *db.Store // for updating session worker_id after migration+ Store *db.Store // for updating session worker_id after migrationStateStore ScalerStateStore // optional: persists scaler state to Redis (nil = in-memory)WorkerImage stringCooldown time.Duration // minimum time between scale-up actions per regionInterval 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 stringcooldown time.Durationinterval 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 boolmachineSizes []string // ranked list of provider-specific sizes for scale-up fallback@@ -1946,7 +1946,6 @@ func (s *Scaler) liveMigrateSandbox(ctx context.Context, sandboxID, sourceWorkerSealedTokens: 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.goindex 7320912a..2e107e14 100644--- a/internal/controlplane/server.go+++ b/internal/controlplane/server.go@@ -96,16 +96,15 @@ 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"`- NetworkPolicy string `json:"networkPolicy"`- 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"`+ 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()})@@ -210,7 +209,6 @@ 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.goindex 85c0724b..8921a20a 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -852,28 +852,6 @@ func (s *Store) UpdateSandboxSessionStatus(ctx context.Context, sandboxID, statureturn 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 reasondiff --git a/internal/qemu/manager.go b/internal/qemu/manager.goindex 6f4f5703..588d0ec1 100644--- a/internal/qemu/manager.go+++ b/internal/qemu/manager.go@@ -248,9 +248,6 @@ type VMInstance struct {MemoryMB intHostPort intGuestPort int- // NetworkPolicy is the host-enforced network boundary that must survive- // wake, restore, fork, power-cycle, and live migration.- NetworkPolicy types.NetworkPolicy// VM internalspid int@@ -294,12 +291,11 @@ 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"`- NetworkPolicy types.NetworkPolicy `json:"networkPolicy,omitempty"`+ SandboxID string `json:"sandboxId"`+ Template string `json:"template"`+ CpuCount int `json:"cpuCount"`+ MemoryMB int `json:"memoryMB"`+ GuestPort int `json:"guestPort"`}// SecretsProxyIntegration provides the interface for the secrets proxy to integrate@@ -909,7 +905,7 @@ func (m *Manager) PrepareGoldenSnapshot() error {if err != nil {return fmt.Errorf("allocate golden subnet: %w", err)}- if err := CreateTAP(netCfg, types.NetworkPolicyNone); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)return fmt.Errorf("create golden TAP: %w", err)}@@ -1196,7 +1192,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, cfg.NetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)return nil, fmt.Errorf("create TAP: %w", err)@@ -1206,12 +1202,21 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,if guestPort == 0 {guestPort = m.cfg.DefaultPort}- hostPort, err := configureIngress(netCfg, cfg.NetworkPolicy, guestPort)+ hostPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("configure ingress: %w", err)+ 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)}// Add metadata service DNAT (169.254.169.254:80 → host:8888)@@ -1327,7 +1332,6 @@ 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,@@ -1446,12 +1450,11 @@ func (m *Manager) createFromGolden(ctx context.Context, cfg types.SandboxConfig,}sbMeta := SandboxMeta{- SandboxID: id,- Template: template,- CpuCount: cpus,- MemoryMB: memMB,- GuestPort: guestPort,- NetworkPolicy: cfg.NetworkPolicy,+ SandboxID: id,+ Template: template,+ CpuCount: cpus,+ MemoryMB: memMB,+ GuestPort: guestPort,}if metaJSON, err := json.Marshal(sbMeta); err == nil {if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {@@ -1757,7 +1760,7 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *typeos.RemoveAll(sandboxDir)return nil, fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, cfg.NetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)return nil, fmt.Errorf("create TAP: %w", err)@@ -1767,12 +1770,21 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *typeif guestPort == 0 {guestPort = m.cfg.DefaultPort}- hostPort, err := configureIngress(netCfg, cfg.NetworkPolicy, guestPort)+ hostPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("configure ingress: %w", err)+ 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)}// Add metadata service DNAT (169.254.169.254:80 → host:8888)@@ -1854,7 +1866,6 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *typebaseMemoryMB: memMB,HostPort: hostPort,GuestPort: guestPort,- NetworkPolicy: cfg.NetworkPolicy,pid: cmd.Process.Pid,cmd: cmd,network: netCfg,@@ -1906,12 +1917,11 @@ func (m *Manager) Create(ctx context.Context, cfg types.SandboxConfig) (sb *type}sbMeta := SandboxMeta{- SandboxID: id,- Template: template,- CpuCount: cpus,- MemoryMB: memMB,- GuestPort: guestPort,- NetworkPolicy: cfg.NetworkPolicy,+ SandboxID: id,+ Template: template,+ CpuCount: cpus,+ MemoryMB: memMB,+ GuestPort: guestPort,}if metaJSON, err := json.Marshal(sbMeta); err == nil {if writeErr := os.WriteFile(filepath.Join(sandboxDir, "sandbox-meta.json"), metaJSON, 0644); writeErr != nil {@@ -3260,7 +3270,6 @@ func (m *Manager) CreateCheckpoint(ctx context.Context, sandboxID, checkpointIDBaseMemoryMB: vm.baseMemoryMB,Template: vm.Template,GuestPort: vm.GuestPort,- NetworkPolicy: vm.NetworkPolicy,GoldenVersion: vm.goldenVersion,SnapshotedAt: time.Now(),}@@ -3462,7 +3471,6 @@ func (m *Manager) CreateDiskOnlyCheckpoint(ctx context.Context, sandboxID, checkBaseMemoryMB: vm.baseMemoryMB,Template: vm.Template,GuestPort: vm.GuestPort,- NetworkPolicy: vm.NetworkPolicy,GoldenVersion: vm.goldenVersion,SnapshotedAt: time.Now(),}@@ -3578,12 +3586,6 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoiif 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.@@ -3627,19 +3629,22 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoiif err != nil {return fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, restoreNetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)return fmt.Errorf("create TAP: %w", err)}- guestPort := vm.GuestPort- if guestPort == 0 {- guestPort = m.cfg.DefaultPort- }- hostPort, err := configureIngress(netCfg, restoreNetworkPolicy, guestPort)+ hostPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)- return fmt.Errorf("configure ingress: %w", err)+ return fmt.Errorf("find free port: %w", err)+ }+ netCfg.HostPort = hostPort+ netCfg.GuestPort = vm.GuestPort+ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return fmt.Errorf("add DNAT: %w", err)}if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {log.Printf("qemu: RestoreFromCheckpoint %s: metadata DNAT failed: %v", sandboxID, err)@@ -3806,8 +3811,6 @@ func (m *Manager) RestoreFromCheckpoint(ctx context.Context, sandboxID, checkpoivm.agent = agentClientvm.network = netCfgvm.HostPort = hostPort- vm.GuestPort = guestPort- vm.NetworkPolicy = restoreNetworkPolicyvm.qmpSockPath = qmpSockPathvm.agentSockPath = agentSockPathvm.guestMAC = guestMAC@@ -3860,10 +3863,6 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cif data, err := os.ReadFile(metaPath); err == nil {json.Unmarshal(data, &meta)}- forkNetworkPolicy := cfg.NetworkPolicy- if forkNetworkPolicy == types.NetworkPolicyNone {- forkNetworkPolicy = meta.NetworkPolicy- }id := cfg.SandboxIDif id == "" {@@ -3896,7 +3895,7 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cos.RemoveAll(sandboxDir)return nil, fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, forkNetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)return nil, fmt.Errorf("create TAP: %w", err)@@ -3906,12 +3905,20 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cif guestPort == 0 {guestPort = m.cfg.DefaultPort}- hostPort, err := configureIngress(netCfg, forkNetworkPolicy, guestPort)+ hostPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)os.RemoveAll(sandboxDir)- return nil, fmt.Errorf("configure ingress: %w", err)+ 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)}// Add metadata service DNAT (169.254.169.254:80 → host:8888)@@ -4207,7 +4214,6 @@ func (m *Manager) ForkFromCheckpoint(ctx context.Context, checkpointID string, cvirtioMemRequestedMB: virtioMemAddedMB,HostPort: hostPort,GuestPort: guestPort,- NetworkPolicy: forkNetworkPolicy,pid: cmd.Process.Pid,cmd: cmd,network: netCfg,@@ -4443,7 +4449,7 @@ func (m *Manager) CleanupOrphanedProcesses() {}tapName := strings.TrimSuffix(fields[1], ":")if strings.HasPrefix(tapName, "qm-") {- DeleteTAP(tapName)+ _ = exec.Command("ip", "link", "del", tapName).Run()log.Printf("qemu: cleaned up orphaned TAP %s", tapName)}}@@ -4485,12 +4491,11 @@ 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,- NetworkPolicy: snapMeta.NetworkPolicy,+ SandboxID: sandboxID,+ Template: snapMeta.Template,+ CpuCount: snapMeta.CpuCount,+ MemoryMB: snapMeta.MemoryMB,+ GuestPort: snapMeta.GuestPort,},})continuediff --git a/internal/qemu/migration.go b/internal/qemu/migration.goindex a47e0fbe..a380e260 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, networkPolicy types.NetworkPolicy) (incomingAddr string, hostPort int, err error) {+func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (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,19 +395,27 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfif err != nil {return "", 0, fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, networkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)return "", 0, fmt.Errorf("create TAP: %w", err)}- if guestPort == 0 {- guestPort = 80- }- hp, err := configureIngress(netCfg, networkPolicy, guestPort)+ hp, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)- return "", 0, fmt.Errorf("configure ingress: %w", err)+ return "", 0, fmt.Errorf("find free port: %w", err)+ }+ netCfg.HostPort = hp+ netCfg.GuestPort = guestPort+ if netCfg.GuestPort == 0 {+ netCfg.GuestPort = 80+ }++ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return "", 0, fmt.Errorf("add DNAT: %w", err)}if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {log.Printf("qemu: warning: metadata DNAT failed: %v", err)@@ -509,7 +517,6 @@ func (m *Manager) PrepareIncomingMigration(ctx context.Context, sandboxID, rootfbaseMemoryMB: memMB,HostPort: hp,GuestPort: netCfg.GuestPort,- NetworkPolicy: networkPolicy,pid: cmd.Process.Pid,cmd: cmd,network: netCfg,@@ -653,7 +660,6 @@ func (m *Manager) PreCopyDrives(ctx context.Context, sandboxID string, checkpoinbaseCPU = vm.CpuCountbaseMem = vm.baseMemoryMBpid = vm.pid- secrets.NetworkPolicy = string(vm.NetworkPolicy)if vm.network != nil {guestIP = vm.network.GuestIP}@@ -778,7 +784,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, types.NetworkPolicy(secrets.NetworkPolicy))+ incomingAddr, hostPort, err = m.PrepareIncomingMigration(ctx, sandboxID, rootfsPath, workspacePath, cpus, memMB, guestPort, template)if err != nil {return "", 0, err}diff --git a/internal/qemu/network.go b/internal/qemu/network.goindex bf4542b7..4d59c491 100644--- a/internal/qemu/network.go+++ b/internal/qemu/network.go@@ -6,8 +6,6 @@ import ("os/exec""strings""sync"-- "github.com/opensandbox/opensandbox/pkg/types")// NetworkConfig holds the networking state for a single VM.@@ -119,9 +117,8 @@ func (a *SubnetAllocator) Release(tapName string) {delete(a.used, block)}-// 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 {+// CreateTAP creates a TAP device and configures it with the host IP.+func CreateTAP(cfg *NetworkConfig) error {if err := run("ip", "tuntap", "add", "dev", cfg.TAPName, "mode", "tap"); err != nil {return fmt.Errorf("create tap %s: %w", cfg.TAPName, err)}@@ -145,11 +142,6 @@ func CreateTAP(cfg *NetworkConfig, policy types.NetworkPolicy) 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}@@ -162,180 +154,12 @@ func applyRateLimit(tapName string) {"rate", "500mbit", "burst", "10mb", "latency", "50ms")}-// 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.+// DeleteTAP removes a TAP device and its tc qdisc.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 {@@ -381,31 +205,6 @@ 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.godeleted file mode 100644index 707b8534..00000000--- a/internal/qemu/network_policy_test.go+++ /dev/null@@ -1,203 +0,0 @@-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.goindex d3952ec8..d4a0f8ec 100644--- a/internal/qemu/reset.go+++ b/internal/qemu/reset.go@@ -219,15 +219,22 @@ func (m *Manager) PowerCycleSandbox(ctx context.Context, sandboxID string) (hostif err != nil {return 0, fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, vm.NetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)return 0, fmt.Errorf("create TAP: %w", err)}- freshPort, err := configureIngress(netCfg, vm.NetworkPolicy, guestPort)+ freshPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)- return 0, fmt.Errorf("configure ingress: %w", err)+ 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)}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.goindex 57e5fa04..b722f7b8 100644--- a/internal/qemu/snapshot.go+++ b/internal/qemu/snapshot.go@@ -22,28 +22,27 @@ 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"`- NetworkPolicy types.NetworkPolicy `json:"networkPolicy,omitempty"`- 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"`+ 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@@ -170,7 +169,6 @@ func (m *Manager) doHibernate(ctx context.Context, vm *VMInstance, checkpointStoBaseMemoryMB: vm.baseMemoryMB,Template: vm.Template,GuestPort: vm.GuestPort,- NetworkPolicy: vm.NetworkPolicy,GoldenVersion: vm.goldenVersion,SnapshotedAt: time.Now(),}@@ -441,20 +439,27 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, creturn nil, fmt.Errorf("allocate subnet: %w", err)}}- if err := CreateTAP(netCfg, meta.NetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); err != nil {m.subnets.Release(netCfg.TAPName)return nil, fmt.Errorf("create TAP: %w", err)}- guestPort := meta.GuestPort- if guestPort == 0 {- guestPort = 80- }- hostPort, err := configureIngress(netCfg, meta.NetworkPolicy, guestPort)+ hostPort, err := FindFreePort()if err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)- return nil, fmt.Errorf("configure ingress: %w", err)+ return nil, fmt.Errorf("find free port: %w", err)+ }+ netCfg.HostPort = hostPort+ netCfg.GuestPort = meta.GuestPort+ if netCfg.GuestPort == 0 {+ netCfg.GuestPort = 80+ }++ if err := AddDNAT(netCfg); err != nil {+ DeleteTAP(netCfg.TAPName)+ m.subnets.Release(netCfg.TAPName)+ return nil, fmt.Errorf("add DNAT: %w", err)}if err := AddMetadataDNAT(netCfg.TAPName, netCfg.HostIP); err != nil {log.Printf("qemu: warning: metadata DNAT failed: %v", err)@@ -639,19 +644,18 @@ func (m *Manager) doWake(ctx context.Context, sandboxID, checkpointKey string, cbaseMemoryMB: baseMem,virtioMemRequestedMB: pluggedMB,HostPort: hostPort,- 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+ 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}// Recompute virtio-mem amount from the meta. Without this the field// stays at zero on wake, which would (a) make grow deltas under-charge@@ -799,12 +803,11 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timereturn 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,- NetworkPolicy: snap.NetworkPolicy,+ SandboxID: sandboxID,+ Template: snap.Template,+ CpuCount: snap.CpuCount,+ MemoryMB: snap.MemoryMB,+ GuestPort: snap.GuestPort,}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)@@ -835,20 +838,28 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timeif err != nil {return nil, fmt.Errorf("allocate subnet: %w", err)}- if err := CreateTAP(netCfg, meta.NetworkPolicy); err != nil {+ if err := CreateTAP(netCfg); 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.GuestPortif guestPort == 0 {guestPort = 80}- hostPort, err := configureIngress(netCfg, meta.NetworkPolicy, guestPort)- if err != nil {+ netCfg.HostPort = hostPort+ netCfg.GuestPort = guestPort++ if err := AddDNAT(netCfg); err != nil {DeleteTAP(netCfg.TAPName)m.subnets.Release(netCfg.TAPName)- return nil, fmt.Errorf("configure ingress: %w", err)+ return nil, fmt.Errorf("add DNAT: %w", err)}// Add metadata service DNAT (169.254.169.254:80 → host:8888)@@ -926,7 +937,6 @@ func (m *Manager) coldBootLocalInner(ctx context.Context, sandboxID string, timebaseMemoryMB: 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.goindex b835f9d3..2e0aaa6c 100644--- a/internal/sandbox/interface.go+++ b/internal/sandbox/interface.go@@ -29,10 +29,6 @@ type MigrationSecrets struct {SealedTokens map[string]stringEgressAllowlist []stringTokenHosts 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@@ -44,10 +40,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"`// bytesPIDs int `json:"pids"`}diff --git a/internal/worker/grpc_server.go b/internal/worker/grpc_server.goindex 418a4b47..623d4e13 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, networkPolicy types.NetworkPolicy) (incomingAddr string, hostPort int, err error)+ PrepareIncomingMigration(ctx context.Context, sandboxID, rootfsPath, workspacePath string, cpus, memMB, guestPort int, template string) (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,7 +211,6 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqMemoryMB: 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@@ -221,9 +220,6 @@ func (s *GRPCServer) CreateSandbox(ctx context.Context, req *pb.CreateSandboxReqSecretEnvs: 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.@@ -1407,7 +1403,6 @@ func (s *GRPCServer) PreCopyDrives(ctx context.Context, req *pb.PreCopyDrivesReqBaseMemoryMb: 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).@@ -1429,9 +1424,6 @@ func (s *GRPCServer) PrepareMigrationIncoming(ctx context.Context, req *pb.Prepaif 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@@ -1456,7 +1448,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.- secrets := sandbox.MigrationSecrets{NetworkPolicy: req.NetworkPolicy}+ var secrets sandbox.MigrationSecretsif len(req.SealedTokens) > 0 {secrets.SealedTokens = req.SealedTokenssecrets.EgressAllowlist = req.EgressAllowlist@@ -1483,7 +1475,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, types.NetworkPolicy(req.NetworkPolicy))+ int(req.CpuCount), int(req.MemoryMb), int(req.GuestPort), req.Template)}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.godeleted file mode 100644index ae5d979f..00000000--- a/internal/worker/network_policy_test.go+++ /dev/null@@ -1,129 +0,0 @@-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.goindex eef33085..78b87ec6 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,18 +80,11 @@ 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"`- // 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+ NetworkEnabled *bool `json:"networkEnabled,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"`@@ -138,22 +131,6 @@ 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 intdiff --git a/pkg/types/sandbox_test.go b/pkg/types/sandbox_test.godeleted file mode 100644index a800691b..00000000--- a/pkg/types/sandbox_test.go+++ /dev/null@@ -1,16 +0,0 @@-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.goindex 49508cee..47caf9da 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 v5.29.3+// protoc v7.35.0// source: proto/worker/worker.protopackage worker@@ -90,12 +90,8 @@ 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)- // 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"`+ 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)unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -242,13 +238,6 @@ 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"`@@ -3529,7 +3518,6 @@ 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.UnknownFieldssizeCache protoimpl.SizeCache}@@ -3634,13 +3622,6 @@ 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"`@@ -3712,8 +3693,7 @@ 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"`- NetworkPolicy string `protobuf:"bytes,18,opt,name=network_policy,json=networkPolicy,proto3" json:"network_policy,omitempty"`+ ArrivePaused bool `protobuf:"varint,17,opt,name=arrive_paused,json=arrivePaused,proto3" json:"arrive_paused,omitempty"`unknownFields protoimpl.UnknownFieldssizeCache protoimpl.SizeCache}@@ -3867,13 +3847,6 @@ 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")@@ -4294,7 +4267,7 @@ var File_proto_worker_worker_proto protoreflect.FileDescriptorconst file_proto_worker_worker_proto_rawDesc = "" +"\n" +- "\x19proto/worker/worker.proto\x12\x06worker\"\xa7\a\n" ++ "\x19proto/worker/worker.proto\x12\x06worker\"\x80\a\n" +"\x14CreateSandboxRequest\x12\x1a\n" +"\btemplate\x18\x01 \x01(\tR\btemplate\x12\x18\n" +"\atimeout\x18\x02 \x01(\x05R\atimeout\x12:\n" +@@ -4314,8 +4287,7 @@ 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\x12%\n" +- "\x0enetwork_policy\x18\x11 \x01(\tR\rnetworkPolicy\x1a7\n" ++ "\adisk_mb\x18\x10 \x01(\x05R\x06diskMb\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" +@@ -4576,7 +4548,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\"\x95\x06\n" ++ "sandbox_id\x18\x01 \x01(\tR\tsandboxIdJ\x04\b\x02\x10\x03\"\xee\x05\n" +"\x15PreCopyDrivesResponse\x12\x1d\n" +"\n" +"rootfs_key\x18\x01 \x01(\tR\trootfsKey\x12#\n" +@@ -4590,8 +4562,7 @@ 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\x12%\n" +- "\x0enetwork_policy\x18\v \x01(\tR\rnetworkPolicy\x1a?\n" ++ " \x03(\v2..worker.PreCopyDrivesResponse.SealedNamesEntryR\vsealedNames\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" +@@ -4602,7 +4573,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\"\xac\b\n" ++ "\x05hosts\x18\x01 \x03(\tR\x05hosts\"\x85\b\n" +"\x1fPrepareMigrationIncomingRequest\x12\x1d\n" +"\n" +"sandbox_id\x18\x01 \x01(\tR\tsandboxId\x12\x1f\n" +@@ -4625,8 +4596,7 @@ 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\x12%\n" +- "\x0enetwork_policy\x18\x12 \x01(\tR\rnetworkPolicy\x1a?\n" ++ "\rarrive_paused\x18\x11 \x01(\bR\farrivePaused\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.protoindex deb22b45..f2ce3020 100644--- a/proto/worker/worker.proto+++ b/proto/worker/worker.proto@@ -110,10 +110,6 @@ 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 {@@ -473,7 +469,6 @@ 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.@@ -507,7 +502,6 @@ 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.goindex aed9320c..7c258a5e 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 v5.29.3+// - protoc v7.35.0// source: proto/worker/worker.protopackage workerdiff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.jsonindex c6c0dfd7..f3cd7de3 100644--- a/sdks/typescript/package-lock.json+++ b/sdks/typescript/package-lock.json@@ -1,12 +1,12 @@{"name": "@opencomputer/sdk",- "version": "0.12.2",+ "version": "0.12.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@opencomputer/sdk",- "version": "0.12.2",+ "version": "0.12.1","license": "MIT","devDependencies": {"@types/node": "^25.3.0",diff --git a/sdks/typescript/package.json b/sdks/typescript/package.jsonindex 77b6583b..4f797612 100644--- a/sdks/typescript/package.json+++ b/sdks/typescript/package.json@@ -1,6 +1,6 @@{"name": "@opencomputer/sdk",- "version": "0.12.2",+ "version": "0.12.1","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.tsindex bbfe997b..09672f9e 100644--- a/sdks/typescript/src/sandbox.test.ts+++ b/sdks/typescript/src/sandbox.test.ts@@ -71,65 +71,3 @@ 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.tsindex 4ddbbaed..11370ba0 100644--- a/sdks/typescript/src/sandbox.ts+++ b/sdks/typescript/src/sandbox.ts@@ -39,13 +39,6 @@ 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. */@@ -357,7 +350,6 @@ 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;@@ -793,7 +785,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" | "networkPolicy"> = {}): Promise<Sandbox> {+ static async createFromCheckpoint(checkpointId: string, opts: Pick<SandboxOpts, "apiKey" | "apiUrl" | "timeout" | "envs" | "secretStore"> = {}): 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 ?? "";@@ -801,7 +793,6 @@ 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",diff --git a/web/src/api/deployment-schemas.test.ts b/web/src/api/deployment-schemas.test.tsindex 59e20fd0..44e35b50 100644--- a/web/src/api/deployment-schemas.test.ts+++ b/web/src/api/deployment-schemas.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest'import {+ AgentSchema,AgentDeploymentCommandResponseSchema,AgentDeploymentListSchema,AgentDeploymentLogsSchema,@@ -88,6 +89,33 @@ describe('repository deployment API schemas', () => {expect('future_server_field' in parsed).toBe(false)})+ it('preserves the legacy Flue admission proof without inventing live status', () => {+ const parsed = AgentSchema.parse({+ id: 'agt_legacy',+ name: 'Legacy Flue agent',+ prompt: null,+ model: 'anthropic/claude-haiku-4-5',+ runtime: 'flue',+ revision: 1,+ active_revision_id: 'rev_legacy',+ deployment_status: {+ deployment_id: 'dep_legacy',+ state: 'ready',+ result: 'created',+ error_class: null,+ live_touched: false,+ live_status: null,+ legacy_live_compatible: true,+ updated_at: '2026-07-14T20:00:00.000Z',+ },+ flue: { agent_name: 'legacy', live: null },+ created_at: '2026-07-14T00:00:00.000Z',+ })++ expect(parsed.deployment_status?.legacy_live_compatible).toBe(true)+ expect(parsed.deployment_status?.live_status).toBeNull()+ })+it('keeps deployment-log sequence identity as an opaque string', () => {const seq = '900719925474099312345'const parsed = AgentDeploymentLogsSchema.parse({diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 914a8434..cbb67f2e 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -345,6 +345,7 @@ export const AgentSchema = z.object({error_class: z.string().nullish(),live_touched: z.boolean(),live_status: z.string().nullish(),+ legacy_live_compatible: z.boolean().optional(),updated_at: z.string().nullish(),}).optional(),diff --git a/web/src/lib/agent-deployment-status.test.ts b/web/src/lib/agent-deployment-status.test.tsindex cb1ec8ac..e216dfca 100644--- a/web/src/lib/agent-deployment-status.test.ts+++ b/web/src/lib/agent-deployment-status.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from 'vitest'-import { agentDeploymentDisplayStatus } from './agent-deployment-status'+import {+ agentCanStartNewSession,+ agentDeploymentDisplayStatus,+} from './agent-deployment-status'const baseAgent = {runtime: 'flue',@@ -90,3 +93,59 @@ describe('agent deployment display status', () => {).toBe('not_deployed')})})++describe('agent session admission', () => {+ it('admits an active legacy Flue agent only from the server proof', () => {+ const legacy = {+ ...baseAgent,+ flue: { agent_name: 'support', live: null },+ deployment_status: {+ deployment_id: 'dep_legacy',+ state: 'ready',+ result: 'created',+ error_class: null,+ live_touched: false,+ live_status: null,+ legacy_live_compatible: true,+ updated_at: '2026-07-14T20:00:00.000Z',+ },+ }++ expect(agentCanStartNewSession(legacy)).toBe(true)+ expect(agentDeploymentDisplayStatus(legacy)).not.toBe('verified')+ })++ it('does not let the compatibility proof replace an active revision', () => {+ expect(+ agentCanStartNewSession({+ runtime: 'flue',+ revision: 0,+ active_revision_id: null,+ deployment_status: {+ deployment_id: null,+ state: 'not_deployed',+ result: null,+ error_class: null,+ live_touched: false,+ live_status: null,+ legacy_live_compatible: true,+ updated_at: null,+ },+ flue: { agent_name: 'support', live: null },+ }),+ ).toBe(false)+ })++ it('keeps verified Flue and active built-in agents startable', () => {+ expect(agentCanStartNewSession(baseAgent)).toBe(true)+ expect(+ agentCanStartNewSession({+ runtime: 'claude',+ revision: 1,+ active_revision_id: 'rev_builtin',+ deployment_status: undefined,+ flue: null,+ }),+ ).toBe(true)+ })+})diff --git a/web/src/lib/agent-deployment-status.ts b/web/src/lib/agent-deployment-status.tsindex 9901b249..c9aca526 100644--- a/web/src/lib/agent-deployment-status.ts+++ b/web/src/lib/agent-deployment-status.ts@@ -26,3 +26,26 @@ export function agentDeploymentDisplayStatus(return status}++/**+ * Session admission is stricter than the display status. New Flue deployments+ * require a verified live pointer. Existing CLI-created Flue agents can carry+ * a server-computed compatibility proof while their physical live status is+ * intentionally unknown; that proof enables admission only and must never be+ * projected as a live/verified label.+ */+export function agentCanStartNewSession(+ agent: AgentDeploymentHealth,+): boolean {+ const hasActiveRevision =+ !!agent.active_revision_id || (agent.revision ?? 0) > 0+ if (!hasActiveRevision) return false+ if (agent.runtime !== 'flue') return true++ const liveStatus =+ agent.deployment_status?.live_status ?? agent.flue?.live?.status ?? null+ return (+ liveStatus === 'verified' ||+ agent.deployment_status?.legacy_live_compatible === true+ )+}diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex 6d6821da..4ca4890a 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -38,7 +38,10 @@ import {type WorkingRepo,} from '@/components/working-repo-field'import { ApiHint, type ApiRef } from '@/components/api-hint'-import { agentDeploymentDisplayStatus } from '@/lib/agent-deployment-status'+import {+ agentCanStartNewSession,+ agentDeploymentDisplayStatus,+} from '@/lib/agent-deployment-status'import { getRuntime, keyFieldFor, providerForModel, withModelGroups } from '@/lib/runtimes'const DOCS = 'https://docs.opencomputer.dev/agent-sessions'@@ -301,11 +304,7 @@ export default function AgentDetail() {const base = `/agents/${agent.id}`const latestDeploymentId = agent.deployment_status?.deployment_idconst deploymentStatus = agentDeploymentDisplayStatus(agent)- const liveStatus =- agent.deployment_status?.live_status ?? agent.flue?.live?.status ?? null- const canStartNewSession =- activeRev !== null &&- (agent.runtime !== 'flue' || liveStatus === 'verified')+ const canStartNewSession = agentCanStartNewSession(agent)return (<div className="mx-auto max-w-5xl">@@ -519,7 +518,9 @@ export default function AgentDetail() {</div>{/* Right rail: connect-or-status for the agent's source + Slack. */}<div className="space-y-4">- <AgentDeploySource agentId={agent.id} />+ {agent.runtime !== 'flue' ? (+ <AgentDeploySource agentId={agent.id} />+ ) : null}<SlackConnect agentId={agent.id} agentName={agent.name} /></div></div>