Skip to content

An open-source, faster Devin alternative

TypeScript

feat(deploy): pin Flue builder substrate proof

Igor Zalutski6286d4d73d8c
diff --git a/.github/workflows/flue-managed-build-golden.yml b/.github/workflows/flue-managed-build-golden.yml
index 58a6cb55..5848173b 100644
--- a/.github/workflows/flue-managed-build-golden.yml
+++ b/.github/workflows/flue-managed-build-golden.yml
@@ -5,14 +5,20 @@ on:
branches: [main]
paths:
- 'cmd/oc/**'
+ - 'ci/flue-builder-substrate-probe.py'
+ - 'ci/test_flue_builder_substrate_probe.py'
- 'ci/flue-managed-build-golden.sh'
+ - 'deploy/flue-builder/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/flue-managed-build-golden.yml'
pull_request:
paths:
- 'cmd/oc/**'
+ - 'ci/flue-builder-substrate-probe.py'
+ - 'ci/test_flue_builder_substrate_probe.py'
- 'ci/flue-managed-build-golden.sh'
+ - 'deploy/flue-builder/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/flue-managed-build-golden.yml'
@@ -35,5 +41,11 @@ jobs:
with:
node-version: '22.19.0'
+ - name: Verify pinned builder snapshot and substrate probe
+ run: |
+ python3 deploy/flue-builder/snapshot.py check
+ python3 ci/flue-builder-substrate-probe.py --check
+ python3 -m unittest ci/test_flue_builder_substrate_probe.py
+
- name: Verify current CLI against pinned starter artifact
run: ./ci/flue-managed-build-golden.sh
diff --git a/ci/flue-builder-substrate-probe.py b/ci/flue-builder-substrate-probe.py
new file mode 100755
index 00000000..85344097
--- /dev/null
+++ b/ci/flue-builder-substrate-probe.py
@@ -0,0 +1,627 @@
+#!/usr/bin/env python3
+"""Prove the Flue build sandbox's final network and credential topology."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import importlib.util
+import ipaddress
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import sys
+import time
+from typing import Any
+from urllib import error, parse, request
+import uuid
+
+
+ROOT = 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")
+)
+FORBIDDEN_CREDENTIAL_NAMES = (
+ "OPENCOMPUTER_API_KEY",
+ "GITHUB_TOKEN",
+ "GH_TOKEN",
+ "AGENT_BUILD_SOURCE_TOKEN",
+ "AGENT_BUILD_SOURCE_BROKER_SECRET",
+ "AGENT_WORKER_WFP_API_TOKEN",
+ "WFP_API_TOKEN",
+ "CLOUDFLARE_API_TOKEN",
+ "R2_ACCESS_KEY_ID",
+ "R2_SECRET_ACCESS_KEY",
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+)
+
+
+class ProbeError(RuntimeError):
+ pass
+
+
+def load_snapshot_module() -> Any:
+ spec = importlib.util.spec_from_file_location("flue_builder_snapshot", SNAPSHOT_MODULE_PATH)
+ if spec is None or spec.loader is None:
+ raise ProbeError("cannot load the snapshot recipe validator")
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+SNAPSHOT = load_snapshot_module()
+
+
+def require_env(name: str) -> str:
+ value = os.environ.get(name, "")
+ if not value:
+ raise ProbeError(f"{name} is required")
+ 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)
+ except SNAPSHOT.SnapshotError as exc:
+ raise ProbeError(str(exc)) from exc
+ parsed = parse.urlsplit(normalized)
+ if parsed.scheme == "http" and os.environ.get("AGENT_BUILD_PROBE_ALLOW_HTTP") != "1":
+ raise ProbeError("HTTP API URLs require AGENT_BUILD_PROBE_ALLOW_HTTP=1")
+ if parsed.hostname in PRODUCTION_HOSTS and os.environ.get("AGENT_BUILD_PROBE_ALLOW_PRODUCTION") != "1":
+ raise ProbeError("production probing requires AGENT_BUILD_PROBE_ALLOW_PRODUCTION=1")
+ return normalized
+
+
+def static_check() -> tuple[dict[str, Any], dict[str, Any]]:
+ try:
+ 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")
+ return coordinate, manifest
+
+
+class LiveProbe:
+ def __init__(self, coordinate: dict[str, Any], manifest: dict[str, Any]):
+ self.coordinate = coordinate
+ self.manifest = manifest
+ self.snapshot_name = coordinate["snapshot"]["name"]
+ self.api_url = safe_api_url(require_env("OPENCOMPUTER_API_URL"))
+ self.api_key = require_env("OPENCOMPUTER_API_KEY")
+ self.api = SNAPSHOT.API(self.api_url, self.api_key)
+ self.checkpoint_id = require_env("AGENT_BUILD_SANDBOX_CHECKPOINT_ID")
+ try:
+ uuid.UUID(self.checkpoint_id)
+ except ValueError as exc:
+ 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")
+ 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.
+ self.sentinels: dict[str, str] = {}
+ for name in FORBIDDEN_CREDENTIAL_NAMES:
+ original = os.environ.get(name)
+ if original and len(original) >= 12:
+ self.sentinels[f"{name} (original)"] = original
+ synthetic = f"flue-probe-{name.lower()}-{secrets.token_urlsafe(24)}"
+ os.environ[name] = synthetic
+ self.sentinels[name] = synthetic
+
+ def call(
+ self,
+ method: str,
+ path: str,
+ body: Any | None = None,
+ allowed_statuses: set[int] | None = None,
+ timeout: float = 60,
+ ) -> tuple[int, Any]:
+ try:
+ return self.api.call(method, path, body, allowed_statuses, timeout)
+ except SNAPSHOT.SnapshotError as exc:
+ raise ProbeError(str(exc)) from exc
+
+ def validate_snapshot(self) -> None:
+ name = parse.quote(self.snapshot_name, safe="")
+ _, response = self.call("GET", f"/snapshots/{name}", allowed_statuses={200})
+ try:
+ snapshot = SNAPSHOT.assert_snapshot_matches(response, self.coordinate, self.manifest)
+ except SNAPSHOT.SnapshotError as exc:
+ raise ProbeError(str(exc)) from exc
+ if snapshot.get("status") != "ready":
+ raise ProbeError("pinned builder snapshot is not ready")
+ 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
+ _, 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")
+ sandbox_id = response["sandboxID"]
+ 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
+
+ def exec(
+ self,
+ sandbox_id: str,
+ command: str,
+ args: list[str] | None = None,
+ envs: dict[str, str] | None = None,
+ timeout: int = 20,
+ ) -> dict[str, Any]:
+ body: dict[str, Any] = {"cmd": command, "args": args or [], "timeout": timeout}
+ if envs is not None:
+ body["envs"] = envs
+ quoted = parse.quote(sandbox_id, safe="")
+ _, response = self.call(
+ "POST",
+ f"/sandboxes/{quoted}/exec/run",
+ body,
+ allowed_statuses={200},
+ timeout=timeout + 20,
+ )
+ if not isinstance(response, dict) or not isinstance(response.get("exitCode"), int):
+ raise ProbeError("exec response is missing exitCode")
+ return response
+
+ @staticmethod
+ def expect_success(label: str, response: dict[str, Any]) -> str:
+ if response["exitCode"] != 0:
+ 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:
+ javascript = r"""
+const cp = require("child_process");
+const fs = require("fs");
+const run = (cmd, args) => cp.execFileSync(cmd, args, {encoding: "utf8"}).trim();
+const result = {
+ 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"]),
+ installerRemoved: !fs.existsSync("/tmp/opencomputer-flue-builder-install.sh"),
+ 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])
+ )
+ try:
+ observed = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise ProbeError("builder attestation command returned invalid JSON") from exc
+ attestation = self.coordinate["attestation"]
+ expected = {
+ "nodeVersion": attestation["node"]["version"],
+ "npmVersion": attestation["npm"]["version"],
+ "ocSha256": attestation["oc"]["binarySha256"],
+ "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")
+
+ 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'''
+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()
+ clean_env = {
+ "PATH": "/opt/opencomputer/bin:/usr/local/bin:/usr/bin:/bin",
+ "HOME": "/tmp/flue-probe-home",
+ "npm_config_cache": "/tmp/flue-probe-npm-cache",
+ "CI": "1",
+ "LANG": "C.UTF-8",
+ "TZ": "UTC",
+ }
+ self.expect_success(
+ "public npm registry and tarball",
+ self.exec(
+ sandbox_id,
+ "/bin/bash",
+ ["-c", script, "probe", NPM_PROBE_PACKAGE],
+ clean_env,
+ timeout=90,
+ ),
+ )
+
+ 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");
+const path = require("path");
+const chunks = [Buffer.from(JSON.stringify(process.env))];
+const seen = ["process.env"];
+let total = chunks[0].length;
+const MAX_TOTAL = 384 * 1024;
+const add = (candidate) => {
+ if (total >= MAX_TOTAL) return;
+ try {
+ const stat = fs.statSync(candidate);
+ if (!stat.isFile()) return;
+ const value = fs.readFileSync(candidate).subarray(0, Math.min(stat.size, 64 * 1024));
+ chunks.push(Buffer.from("\n" + candidate + "\n"));
+ chunks.push(value);
+ seen.push(candidate);
+ total += value.length + candidate.length + 2;
+ } catch (_) {}
+};
+add("/proc/1/environ");
+for (const candidate of [
+ "/etc/environment", "/etc/profile", "/etc/bash.bashrc", "/etc/npmrc",
+ "/root/.npmrc", "/root/.config/npm/npmrc",
+ "/home/sandbox/.npmrc", "/home/sandbox/.config/npm/npmrc",
+ "/home/oai/share/.npmrc", "/opt/opencomputer/agent-build-snapshot.json"
+]) add(candidate);
+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`);
+}
+process.stdout.write(JSON.stringify({
+ payload: Buffer.concat(chunks).subarray(0, MAX_TOTAL).toString("base64"),
+ seen
+}));
+""".strip()
+ raw_result = self.expect_success(
+ "credential sentinel scan",
+ self.exec(
+ sandbox_id,
+ "/usr/bin/sudo",
+ ["-n", "node", "-e", javascript],
+ timeout=30,
+ ),
+ ).strip()
+ try:
+ scan = json.loads(raw_result)
+ guest_bytes = base64.b64decode(scan["payload"], validate=True)
+ seen = set(scan["seen"])
+ except (json.JSONDecodeError, KeyError, TypeError, ValueError) as exc:
+ raise ProbeError("credential sentinel scan returned an invalid result") from exc
+ for required in (
+ "process.env",
+ "/proc/1/environ",
+ "/opt/opencomputer/agent-build-snapshot.json",
+ ):
+ if required not in seen:
+ raise ProbeError(f"credential sentinel scan could not inspect {required}")
+
+ matches: list[str] = []
+ for name, value in self.sentinels.items():
+ raw = value.encode()
+ variants = {
+ raw,
+ base64.b64encode(raw),
+ base64.urlsafe_b64encode(raw),
+ base64.urlsafe_b64encode(raw).rstrip(b"="),
+ }
+ 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]:
+ failures: list[str] = []
+ while self.sandboxes:
+ sandbox_id = self.sandboxes.pop()
+ quoted = parse.quote(sandbox_id, safe="")
+ try:
+ self.call("DELETE", f"/sandboxes/{quoted}", allowed_statuses={200, 204}, timeout=60)
+ except ProbeError:
+ failures.append(sandbox_id)
+ return failures
+
+ def run(self) -> None:
+ print("[1/8] 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("[6/8] proving private, link-local/metadata, and guest-host denial")
+ self.prove_restricted_paths(restricted_id)
+
+ print("[7/8] proving inbound host-port and preview paths are disabled")
+ self.prove_inbound_disabled(restricted_id, restricted_response)
+
+ print("[8/8] proving coordinator credential sentinels are absent from the guest")
+ self.scan_guest_for_credentials(restricted_id)
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ mode = parser.add_mutually_exclusive_group(required=True)
+ mode.add_argument("--check", action="store_true", help="validate the probe and recipe offline")
+ mode.add_argument("--run", action="store_true", help="run the guarded real-sandbox proof")
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ probe: LiveProbe | None = None
+ cleanup_failures: list[str] = []
+ try:
+ coordinate, manifest = static_check()
+ if args.check:
+ print(
+ "Flue builder substrate probe is runnable for "
+ f"{coordinate['snapshot']['name']} ({coordinate['recipe']['materializedManifestSha256']})"
+ )
+ return 0
+ probe = LiveProbe(coordinate, manifest)
+ probe.run()
+ except (ProbeError, SNAPSHOT.SnapshotError) as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ finally:
+ if probe is not None:
+ cleanup_failures = probe.destroy_all()
+ if cleanup_failures:
+ print(
+ "warning: failed to destroy probe sandboxes: " + ", ".join(cleanup_failures),
+ file=sys.stderr,
+ )
+ if cleanup_failures:
+ return 1
+ print("PASS: final Flue build topology permits public npm only and exposes no credential sentinels")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ci/test_flue_builder_substrate_probe.py b/ci/test_flue_builder_substrate_probe.py
new file mode 100644
index 00000000..20308ae2
--- /dev/null
+++ b/ci/test_flue_builder_substrate_probe.py
@@ -0,0 +1,116 @@
+from __future__ import annotations
+
+import importlib.util
+import os
+from pathlib import Path
+import unittest
+from unittest import mock
+
+
+PROBE_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")
+PROBE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(PROBE)
+
+
+class SubstrateProbeTest(unittest.TestCase):
+ def test_static_contract_is_pinned(self) -> None:
+ coordinate, manifest = PROBE.static_check()
+ self.assertEqual(coordinate["snapshot"]["networkPolicy"], "public")
+ self.assertEqual(manifest["runtimeMemoryMB"], 1024)
+
+ 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)
+
+ def test_production_and_http_urls_require_separate_guards(self) -> None:
+ with mock.patch.dict(os.environ, {}, clear=True):
+ with self.assertRaises(PROBE.ProbeError):
+ PROBE.safe_api_url("https://app.opencomputer.dev")
+ with self.assertRaises(PROBE.ProbeError):
+ PROBE.safe_api_url("http://127.0.0.1:8080")
+
+ with mock.patch.dict(
+ os.environ,
+ {
+ "AGENT_BUILD_PROBE_ALLOW_PRODUCTION": "1",
+ "AGENT_BUILD_PROBE_ALLOW_HTTP": "1",
+ },
+ clear=True,
+ ):
+ self.assertEqual(
+ PROBE.safe_api_url("https://app.opencomputer.dev"),
+ "https://app.opencomputer.dev/api",
+ )
+ self.assertEqual(
+ PROBE.safe_api_url("http://127.0.0.1:8080"),
+ "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_create_body_is_allowlisted_and_final_topology_is_explicit(self) -> None:
+ live = PROBE.LiveProbe.__new__(PROBE.LiveProbe)
+ live.snapshot_name = "snapshot-coordinate"
+ live.checkpoint_id = "00000000-0000-0000-0000-000000000001"
+ live.sandboxes = []
+ calls: list[tuple[str, str, object]] = []
+
+ def fake_call(
+ method: str,
+ path: str,
+ body: object = None,
+ allowed_statuses: set[int] | None = None,
+ timeout: float = 60,
+ ) -> tuple[int, object]:
+ calls.append((method, path, body))
+ return 201, {
+ "sandboxID": "sb-test",
+ "fromCheckpointId": live.checkpoint_id,
+ "status": "running",
+ }
+
+ live.call = fake_call
+ live.create_sandbox(restricted=True)
+ self.assertEqual(
+ calls,
+ [
+ (
+ "POST",
+ "/sandboxes",
+ {
+ "snapshot": "snapshot-coordinate",
+ "timeout": 600,
+ "networkPolicy": "public",
+ },
+ )
+ ],
+ )
+ self.assertNotIn("envs", calls[0][2])
+ self.assertNotIn("secretStore", calls[0][2])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/deploy/flue-builder/README.md b/deploy/flue-builder/README.md
new file mode 100644
index 00000000..89fbad16
--- /dev/null
+++ b/deploy/flue-builder/README.md
@@ -0,0 +1,132 @@
+# 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.
+
+## Pinned coordinate
+
+`coordinate.json` is the reviewed logical coordinate. It pins:
+
+- snapshot name `flue-build-node22-19-0-oc-c39b315-r1` (never reuse it for a
+ different recipe or checkpoint);
+- Ubuntu 22.04 / x86-64 platform assertion;
+- Node 22.19.0 and its upstream archive digest;
+- 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; and
+- the required runtime `networkPolicy=public`.
+
+The named snapshot is not the complete physical coordinate. The snapshot API's
+ready response supplies its immutable `checkpointId`. `snapshot.py create`
+writes that ID to a receipt. Staging and the 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.
+
+## Offline validation
+
+These commands perform no API calls and create nothing:
+
+```bash
+python3 deploy/flue-builder/snapshot.py check
+python3 ci/flue-builder-substrate-probe.py --check
+```
+
+They verify the shell syntax, recipe digests, materialized manifest, memory
+settings, runtime policy, and the installer-emitted attestation. CI runs both.
+
+## Create in isolated staging
+
+Snapshot creation is an explicit, billable platform write. Do not run this
+against production while the feature is under development. Use a staging API
+key that owns the internal snapshot, load it without printing it, and run:
+
+```bash
+export OPENCOMPUTER_API_URL='https://staging.example.invalid'
+export OPENCOMPUTER_API_KEY='...'
+export AGENT_BUILD_SNAPSHOT_ALLOW_CREATE=1
+
+python3 deploy/flue-builder/snapshot.py create \
+ --confirm-name flue-build-node22-19-0-oc-c39b315-r1 \
+ --receipt /secure/operator-state/flue-build-node22-19-0-oc-c39b315-r1.json
+```
+
+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 additionally require the
+separate `AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1` 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:
+
+```text
+AGENT_BUILD_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r1
+AGENT_BUILD_SANDBOX_CHECKPOINT_ID=<receipt checkpointId>
+AGENT_BUILD_NODE_VERSION=22.19.0
+AGENT_BUILD_NETWORK_POLICY=public
+```
+
+Worker readiness must compare the live snapshot's manifest and checkpoint ID
+to these coordinates before claiming repository builds.
+
+## 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 verifies the runtime attestation and exact `oc` digest, 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 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 disposable HTTP(S) canary at a literal RFC1918 or CGNAT address. It
+must be reachable from a normal staging sandbox and return a short, non-secret
+marker. Do not put credentials in its URL or marker. Then run:
+
+```bash
+export OPENCOMPUTER_API_URL='https://staging.example.invalid'
+export OPENCOMPUTER_API_KEY='...'
+export AGENT_BUILD_SANDBOX_SNAPSHOT='flue-build-node22-19-0-oc-c39b315-r1'
+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
+
+python3 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 staging snapshot or run the live proof in
+CI. They require deployed sandbox-policy code, 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 staging run.
diff --git a/deploy/flue-builder/coordinate.json b/deploy/flue-builder/coordinate.json
new file mode 100644
index 00000000..dfbbf864
--- /dev/null
+++ b/deploy/flue-builder/coordinate.json
@@ -0,0 +1,43 @@
+{
+ "schemaVersion": 1,
+ "snapshot": {
+ "name": "flue-build-node22-19-0-oc-c39b315-r1",
+ "networkPolicy": "public",
+ "builderMemoryMB": 4096,
+ "runtimeMemoryMB": 1024
+ },
+ "recipe": {
+ "installer": "install-snapshot.sh",
+ "installerSha256": "1a4e60e0c72a1a2b5333c7456ed4d9e21fa193e446254ea3e4e8b78b8396ad6f",
+ "imageTemplate": "image.json",
+ "imageTemplateSha256": "d1fc4f3cd27fd1248327f52d9d768a99c9a922d4f0fabf8bf0d6913e2d1e7cd2",
+ "materializedManifestSha256": "4363cbdb960c8fceb12afbb87f9460c4e472a715bee3c06029f72b1539f7fa84"
+ },
+ "attestation": {
+ "schemaVersion": 1,
+ "snapshotName": "flue-build-node22-19-0-oc-c39b315-r1",
+ "baseImage": "base",
+ "platform": {
+ "osId": "ubuntu",
+ "osVersionId": "22.04",
+ "architecture": "x86_64"
+ },
+ "node": {
+ "version": "22.19.0",
+ "archiveSha256": "c0649af18e6a24f6fe5535a3e86b341dd49a8e71117c8b68bde973ef834f16f2"
+ },
+ "npm": {
+ "version": "10.9.3"
+ },
+ "oc": {
+ "version": "oc@c39b31560cb78e0d5708a9eda4cfb30ec372eed9",
+ "sourceCommit": "c39b31560cb78e0d5708a9eda4cfb30ec372eed9",
+ "sourceArchiveSha256": "5aaa929e33c54474bfca774c78d6f422168cb0bf24f4ea445b3b0c1bd2a2840e",
+ "binarySha256": "7f7286095aefe78c3027efb79465442070370c6dcf3cda67c9b1315949a42bc1"
+ },
+ "buildToolchain": {
+ "goVersion": "1.25.0",
+ "goArchiveSha256": "2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613"
+ }
+ }
+}
diff --git a/deploy/flue-builder/image.json b/deploy/flue-builder/image.json
new file mode 100644
index 00000000..da46df7d
--- /dev/null
+++ b/deploy/flue-builder/image.json
@@ -0,0 +1,41 @@
+{
+ "base": "base",
+ "builderMemoryMB": 4096,
+ "runtimeMemoryMB": 1024,
+ "steps": [
+ {
+ "type": "add_file",
+ "args": {
+ "path": "/tmp/opencomputer-flue-builder-install.sh",
+ "contentFrom": "install-snapshot.sh",
+ "encoding": "base64"
+ }
+ },
+ {
+ "type": "run",
+ "args": {
+ "commands": [
+ "sudo -n bash /tmp/opencomputer-flue-builder-install.sh node"
+ ]
+ }
+ },
+ {
+ "type": "run",
+ "args": {
+ "commands": [
+ "sudo -n bash /tmp/opencomputer-flue-builder-install.sh oc"
+ ]
+ }
+ },
+ {
+ "type": "run",
+ "args": {
+ "commands": [
+ "sudo -n bash /tmp/opencomputer-flue-builder-install.sh attest",
+ "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.sh
new file mode 100755
index 00000000..5c02e8c1
--- /dev/null
+++ b/deploy/flue-builder/install-snapshot.sh
@@ -0,0 +1,208 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# This script is embedded into the image manifest by snapshot.py. Keep every
+# downloaded input immutable and verified: the resulting checkpoint is trusted
+# to execute arbitrary repository lifecycle code without receiving credentials.
+
+SNAPSHOT_NAME="flue-build-node22-19-0-oc-c39b315-r1"
+BASE_IMAGE="base"
+OS_ID="ubuntu"
+OS_VERSION_ID="22.04"
+ARCHITECTURE="x86_64"
+
+NODE_VERSION="22.19.0"
+NODE_ARCHIVE_SHA256="c0649af18e6a24f6fe5535a3e86b341dd49a8e71117c8b68bde973ef834f16f2"
+NODE_URL="https://nodejs.org/dist/v${NODE_VERSION}/node-v${NODE_VERSION}-linux-x64.tar.xz"
+NPM_VERSION="10.9.3"
+
+GO_VERSION="1.25.0"
+GO_ARCHIVE_SHA256="2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613"
+GO_URL="https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz"
+
+OC_SOURCE_COMMIT="c39b31560cb78e0d5708a9eda4cfb30ec372eed9"
+OC_SOURCE_ARCHIVE_SHA256="5aaa929e33c54474bfca774c78d6f422168cb0bf24f4ea445b3b0c1bd2a2840e"
+OC_SOURCE_URL="https://github.com/diggerhq/opencomputer/archive/${OC_SOURCE_COMMIT}.tar.gz"
+OC_BINARY_SHA256="7f7286095aefe78c3027efb79465442070370c6dcf3cda67c9b1315949a42bc1"
+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"
+
+die() {
+ echo "flue builder snapshot: $*" >&2
+ exit 1
+}
+
+require_root() {
+ [[ "$(id -u)" == "0" ]] || die "this operation must run as root"
+}
+
+assert_platform() {
+ # shellcheck disable=SC1091
+ source /etc/os-release
+ [[ "${ID:-}" == "$OS_ID" ]] || die "expected OS $OS_ID, found ${ID:-unknown}"
+ [[ "${VERSION_ID:-}" == "$OS_VERSION_ID" ]] || die "expected OS version $OS_VERSION_ID, found ${VERSION_ID:-unknown}"
+ [[ "$(uname -m)" == "$ARCHITECTURE" ]] || die "expected architecture $ARCHITECTURE, found $(uname -m)"
+}
+
+download_verified() {
+ local url="$1"
+ local expected_sha="$2"
+ local output="$3"
+
+ curl --fail --location --silent --show-error --proto '=https' --tlsv1.2 \
+ --retry 3 --retry-all-errors --output "$output" "$url"
+ printf '%s %s\n' "$expected_sha" "$output" | sha256sum --check --status \
+ || die "digest mismatch for $url"
+}
+
+write_attestation() {
+ local output="$1"
+ mkdir -p "$(dirname "$output")"
+ cat >"$output" <<EOF
+{
+ "schemaVersion": 1,
+ "snapshotName": "$SNAPSHOT_NAME",
+ "baseImage": "$BASE_IMAGE",
+ "platform": {
+ "osId": "$OS_ID",
+ "osVersionId": "$OS_VERSION_ID",
+ "architecture": "$ARCHITECTURE"
+ },
+ "node": {
+ "version": "$NODE_VERSION",
+ "archiveSha256": "$NODE_ARCHIVE_SHA256"
+ },
+ "npm": {
+ "version": "$NPM_VERSION"
+ },
+ "oc": {
+ "version": "$OC_VERSION",
+ "sourceCommit": "$OC_SOURCE_COMMIT",
+ "sourceArchiveSha256": "$OC_SOURCE_ARCHIVE_SHA256",
+ "binarySha256": "$OC_BINARY_SHA256"
+ },
+ "buildToolchain": {
+ "goVersion": "$GO_VERSION",
+ "goArchiveSha256": "$GO_ARCHIVE_SHA256"
+ }
+}
+EOF
+}
+
+install_node() {
+ require_root
+ assert_platform
+
+ export DEBIAN_FRONTEND=noninteractive
+ apt-get update -qq
+ apt-get install -y -qq --no-install-recommends \
+ ca-certificates curl git iproute2 util-linux xz-utils
+
+ local tmp
+ tmp="$(mktemp -d)"
+ trap 'rm -rf "$tmp"' EXIT
+ download_verified "$NODE_URL" "$NODE_ARCHIVE_SHA256" "$tmp/node.tar.xz"
+
+ rm -rf "$NODE_ROOT"
+ mkdir -p "$NODE_ROOT"
+ tar -xJf "$tmp/node.tar.xz" --strip-components=1 -C "$NODE_ROOT"
+
+ ln -sfn "$NODE_ROOT/bin/node" /usr/local/bin/node
+ ln -sfn "$NODE_ROOT/bin/npm" /usr/local/bin/npm
+ ln -sfn "$NODE_ROOT/bin/npx" /usr/local/bin/npx
+
+ [[ "$(node --version)" == "v${NODE_VERSION}" ]] || die "installed Node version mismatch"
+ [[ "$(npm --version)" == "$NPM_VERSION" ]] || die "installed npm version mismatch"
+
+ rm -rf /var/lib/apt/lists/*
+ trap - EXIT
+ rm -rf "$tmp"
+}
+
+build_oc() {
+ require_root
+ assert_platform
+
+ local tmp go_root source_root cache_root
+ tmp="$(mktemp -d)"
+ go_root="$tmp/go"
+ source_root="$tmp/source"
+ cache_root="$tmp/cache"
+ trap 'rm -rf "$tmp"' EXIT
+
+ download_verified "$GO_URL" "$GO_ARCHIVE_SHA256" "$tmp/go.tar.gz"
+ mkdir -p "$go_root"
+ tar -xzf "$tmp/go.tar.gz" --strip-components=1 -C "$go_root"
+ [[ "$($go_root/bin/go version)" == "go version go${GO_VERSION} linux/amd64" ]] \
+ || die "Go builder version mismatch"
+
+ download_verified "$OC_SOURCE_URL" "$OC_SOURCE_ARCHIVE_SHA256" "$tmp/opencomputer.tar.gz"
+ mkdir -p "$source_root"
+ tar -xzf "$tmp/opencomputer.tar.gz" --strip-components=1 -C "$source_root"
+
+ mkdir -p /opt/opencomputer/bin "$cache_root/mod" "$cache_root/build"
+ (
+ cd "$source_root"
+ env \
+ CGO_ENABLED=0 \
+ GOARCH=amd64 \
+ GOOS=linux \
+ GOMODCACHE="$cache_root/mod" \
+ GOCACHE="$cache_root/build" \
+ GOTOOLCHAIN=local \
+ "$go_root/bin/go" build \
+ -trimpath \
+ -buildvcs=false \
+ -ldflags "-s -w -X github.com/opensandbox/opensandbox/cmd/oc/internal/commands.Version=${OC_SOURCE_COMMIT}" \
+ -o "$OC_BIN" \
+ ./cmd/oc
+ )
+
+ printf '%s %s\n' "$OC_BINARY_SHA256" "$OC_BIN" | sha256sum --check --status \
+ || die "built oc binary digest mismatch"
+ chmod 0755 "$OC_BIN"
+
+ trap - EXIT
+ rm -rf "$tmp"
+}
+
+attest() {
+ require_root
+ write_attestation "$ATTESTATION"
+ chmod 0644 "$ATTESTATION"
+}
+
+verify() {
+ assert_platform
+ [[ "$(node --version)" == "v${NODE_VERSION}" ]] || die "Node verification failed"
+ [[ "$(npm --version)" == "$NPM_VERSION" ]] || die "npm verification failed"
+ printf '%s %s\n' "$OC_BINARY_SHA256" "$OC_BIN" | sha256sum --check --status \
+ || die "oc digest verification failed"
+ [[ -f "$ATTESTATION" ]] || die "snapshot attestation is missing"
+ cmp -s "$ATTESTATION" <(write_attestation /dev/stdout) \
+ || die "snapshot attestation does not match the installer contract"
+}
+
+case "${1:-}" in
+ coordinate)
+ write_attestation /dev/stdout
+ ;;
+ node)
+ install_node
+ ;;
+ oc)
+ build_oc
+ ;;
+ attest)
+ attest
+ ;;
+ verify)
+ verify
+ ;;
+ *)
+ die "usage: $0 {coordinate|node|oc|attest|verify}"
+ ;;
+esac
diff --git a/deploy/flue-builder/snapshot.py b/deploy/flue-builder/snapshot.py
new file mode 100755
index 00000000..3a48f7f8
--- /dev/null
+++ b/deploy/flue-builder/snapshot.py
@@ -0,0 +1,335 @@
+#!/usr/bin/env python3
+"""Validate or explicitly create the immutable Flue builder snapshot."""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import hashlib
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import time
+from typing import Any
+from urllib import error, parse, request
+
+
+ROOT = Path(__file__).resolve().parent
+COORDINATE_PATH = ROOT / "coordinate.json"
+PRODUCTION_HOSTS = {"app.opencomputer.dev", "api.opencomputer.dev"}
+
+
+class SnapshotError(RuntimeError):
+ pass
+
+
+class NoCredentialRedirect(request.HTTPRedirectHandler):
+ """Never forward the operator API key to a redirected origin."""
+
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None:
+ return None
+
+
+def sha256_bytes(value: bytes) -> str:
+ return hashlib.sha256(value).hexdigest()
+
+
+def canonical_json(value: Any) -> bytes:
+ return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()
+
+
+def load_json(path: Path) -> Any:
+ try:
+ return json.loads(path.read_text())
+ except (OSError, json.JSONDecodeError) as exc:
+ raise SnapshotError(f"cannot read valid JSON from {path}: {exc}") from exc
+
+
+def materialize_manifest() -> dict[str, Any]:
+ template_path = ROOT / "image.json"
+ template = load_json(template_path)
+ if not isinstance(template, dict) or not isinstance(template.get("steps"), list):
+ raise SnapshotError("image.json must contain an object with a steps array")
+
+ # Round-trip to make a deep copy composed only of JSON values.
+ manifest = json.loads(json.dumps(template))
+ for index, step in enumerate(manifest["steps"]):
+ if not isinstance(step, dict) or not isinstance(step.get("args"), dict):
+ raise SnapshotError(f"image step {index} must contain an args object")
+ args = step["args"]
+ source_name = args.pop("contentFrom", None)
+ if source_name is None:
+ continue
+ if step.get("type") != "add_file":
+ raise SnapshotError(f"image step {index} uses contentFrom outside add_file")
+ source = (ROOT / str(source_name)).resolve()
+ if source.parent != ROOT or not source.is_file():
+ raise SnapshotError(f"image step {index} contentFrom must name a file in {ROOT}")
+ if "content" in args:
+ raise SnapshotError(f"image step {index} cannot contain content and contentFrom")
+ args["content"] = base64.b64encode(source.read_bytes()).decode("ascii")
+
+ return manifest
+
+
+def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]:
+ coordinate = load_json(COORDINATE_PATH)
+ manifest = materialize_manifest()
+ if not isinstance(coordinate, dict) or coordinate.get("schemaVersion") != 1:
+ raise SnapshotError("coordinate.json schemaVersion must be 1")
+
+ snapshot = coordinate.get("snapshot")
+ recipe = coordinate.get("recipe")
+ expected_attestation = coordinate.get("attestation")
+ if not all(isinstance(value, dict) for value in (snapshot, recipe, expected_attestation)):
+ raise SnapshotError("coordinate.json is missing snapshot, recipe, or attestation")
+
+ installer_name = recipe.get("installer")
+ template_name = recipe.get("imageTemplate")
+ if installer_name != "install-snapshot.sh" or template_name != "image.json":
+ raise SnapshotError("coordinate recipe must use the repository-owned installer and image template")
+
+ installer_path = ROOT / installer_name
+ template_path = ROOT / template_name
+ observed = {
+ "installerSha256": sha256_bytes(installer_path.read_bytes()),
+ "imageTemplateSha256": sha256_bytes(template_path.read_bytes()),
+ "materializedManifestSha256": sha256_bytes(canonical_json(manifest)),
+ }
+ for key, value in observed.items():
+ expected = recipe.get(key)
+ if expected != value:
+ raise SnapshotError(f"coordinate recipe {key} is {expected!r}; expected {value}")
+
+ 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 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}")
+
+ syntax = subprocess.run(
+ ["bash", "-n", str(installer_path)],
+ check=False,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+ if syntax.returncode != 0:
+ raise SnapshotError(f"install-snapshot.sh fails bash -n: {syntax.stderr.strip()}")
+
+ emitted = subprocess.run(
+ ["bash", str(installer_path), "coordinate"],
+ check=False,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ )
+ if emitted.returncode != 0:
+ raise SnapshotError(f"installer coordinate failed: {emitted.stderr.strip()}")
+ try:
+ actual_attestation = json.loads(emitted.stdout)
+ except json.JSONDecodeError as exc:
+ raise SnapshotError("installer coordinate did not emit valid JSON") from exc
+ if actual_attestation != expected_attestation:
+ raise SnapshotError("installer attestation and coordinate.json attestation differ")
+
+ return coordinate, manifest
+
+
+def normalize_api_url(raw: str) -> str:
+ parsed = parse.urlsplit(raw.strip())
+ if parsed.scheme not in {"https", "http"} or not parsed.hostname:
+ raise SnapshotError("API URL must be an absolute HTTP(S) URL")
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
+ raise SnapshotError("API URL must not contain credentials, query, or fragment")
+ path = parsed.path.rstrip("/")
+ if path not in {"", "/api"}:
+ raise SnapshotError("API URL path must be empty or /api")
+ return parse.urlunsplit((parsed.scheme, parsed.netloc, "/api", "", ""))
+
+
+class API:
+ def __init__(self, api_url: str, api_key: str):
+ self.api_url = normalize_api_url(api_url)
+ self.api_key = api_key
+ self.opener = request.build_opener(NoCredentialRedirect())
+
+ def call(
+ self,
+ method: str,
+ path: str,
+ body: Any | None = None,
+ allowed_statuses: set[int] | None = None,
+ timeout: float = 60,
+ ) -> tuple[int, Any]:
+ allowed = allowed_statuses or {200}
+ payload = None if body is None else canonical_json(body)
+ headers = {"Accept": "application/json", "X-API-Key": self.api_key}
+ if payload is not None:
+ headers["Content-Type"] = "application/json"
+ req = request.Request(
+ f"{self.api_url}{path}", data=payload, headers=headers, method=method
+ )
+ try:
+ with self.opener.open(req, timeout=timeout) as response:
+ status = response.status
+ raw = response.read()
+ except error.HTTPError as exc:
+ status = exc.code
+ raw = exc.read()
+ except error.URLError as exc:
+ raise SnapshotError(f"OpenComputer API request failed: {exc.reason}") from exc
+ if status not in allowed:
+ # Snapshot responses never need to echo caller secrets. Bound the
+ # diagnostic anyway so a proxy cannot flood operator output.
+ detail = raw.decode("utf-8", "replace")[:500]
+ if self.api_key:
+ detail = detail.replace(self.api_key, "[REDACTED]")
+ raise SnapshotError(f"OpenComputer API {method} {path} returned {status}: {detail}")
+ if not raw:
+ return status, None
+ try:
+ return status, json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise SnapshotError(f"OpenComputer API {method} {path} returned invalid JSON") from exc
+
+
+def response_manifest(snapshot: dict[str, Any]) -> dict[str, Any]:
+ value = snapshot.get("manifest")
+ if isinstance(value, str):
+ try:
+ value = json.loads(value)
+ except json.JSONDecodeError as exc:
+ raise SnapshotError("snapshot response manifest is invalid JSON") from exc
+ if not isinstance(value, dict):
+ raise SnapshotError("snapshot response is missing an object manifest")
+ return value
+
+
+def assert_snapshot_matches(
+ response: Any, coordinate: dict[str, Any], manifest: dict[str, Any]
+) -> dict[str, Any]:
+ if not isinstance(response, dict):
+ raise SnapshotError("snapshot response must be an object")
+ expected_name = coordinate["snapshot"]["name"]
+ if response.get("name") != expected_name:
+ raise SnapshotError("snapshot response name does not match the pinned coordinate")
+ if canonical_json(response_manifest(response)) != canonical_json(manifest):
+ raise SnapshotError("existing snapshot manifest differs from the pinned recipe; use a new name")
+ return response
+
+
+def write_receipt(path: Path, response: dict[str, Any], coordinate: dict[str, Any]) -> None:
+ checkpoint_id = response.get("checkpointId")
+ if not isinstance(checkpoint_id, str) or not checkpoint_id:
+ raise SnapshotError("ready snapshot response is missing checkpointId")
+ receipt = {
+ "schemaVersion": 1,
+ "snapshotName": coordinate["snapshot"]["name"],
+ "checkpointId": checkpoint_id,
+ "snapshotId": response.get("id"),
+ "materializedManifestSha256": coordinate["recipe"]["materializedManifestSha256"],
+ "observedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ }
+ path = path.resolve()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile("wb", dir=path.parent, delete=False) as handle:
+ handle.write(canonical_json(receipt))
+ temporary = Path(handle.name)
+ os.replace(temporary, path)
+
+
+def create_snapshot(args: argparse.Namespace) -> None:
+ coordinate, manifest = check_recipe()
+ expected_name = coordinate["snapshot"]["name"]
+ if args.confirm_name != expected_name:
+ raise SnapshotError(f"--confirm-name must exactly equal {expected_name}")
+ if os.environ.get("AGENT_BUILD_SNAPSHOT_ALLOW_CREATE") != "1":
+ raise SnapshotError("set AGENT_BUILD_SNAPSHOT_ALLOW_CREATE=1 to permit snapshot creation")
+
+ api_url = args.api_url or os.environ.get("OPENCOMPUTER_API_URL", "")
+ if not api_url:
+ raise SnapshotError("provide --api-url or OPENCOMPUTER_API_URL")
+ normalized = normalize_api_url(api_url)
+ parsed = parse.urlsplit(normalized)
+ if parsed.scheme == "http" and os.environ.get("AGENT_BUILD_SNAPSHOT_ALLOW_HTTP") != "1":
+ raise SnapshotError("HTTP API URLs require AGENT_BUILD_SNAPSHOT_ALLOW_HTTP=1")
+ if parsed.hostname in PRODUCTION_HOSTS and os.environ.get("AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION") != "1":
+ raise SnapshotError("production snapshot creation requires AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1")
+
+ api_key = os.environ.get(args.api_key_env, "")
+ if not api_key:
+ raise SnapshotError(f"{args.api_key_env} is required")
+ api = API(normalized, api_key)
+ quoted_name = parse.quote(expected_name, safe="")
+
+ status, current = api.call("GET", f"/snapshots/{quoted_name}", allowed_statuses={200, 404})
+ if status == 404:
+ print(f"Creating immutable builder snapshot {expected_name}")
+ _, current = api.call(
+ "POST",
+ "/snapshots?async=1",
+ {"name": expected_name, "image": manifest},
+ allowed_statuses={202},
+ )
+ else:
+ print(f"Snapshot {expected_name} already exists; validating it without mutation")
+ current = assert_snapshot_matches(current, coordinate, manifest)
+
+ deadline = time.monotonic() + args.timeout_seconds
+ while current.get("status") == "building":
+ if time.monotonic() >= deadline:
+ raise SnapshotError("timed out waiting for snapshot build")
+ time.sleep(args.poll_seconds)
+ _, current = api.call("GET", f"/snapshots/{quoted_name}", allowed_statuses={200})
+ current = assert_snapshot_matches(current, coordinate, manifest)
+
+ if current.get("status") != "ready":
+ 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.")
+
+
+def parse_args() -> argparse.Namespace:
+ parser = argparse.ArgumentParser(description=__doc__)
+ subparsers = parser.add_subparsers(dest="command", required=True)
+ subparsers.add_parser("check", help="validate all local recipe pins without network access")
+
+ create = subparsers.add_parser("create", help="explicitly create or validate the pinned snapshot")
+ create.add_argument("--api-url", help="OpenComputer URL; defaults to OPENCOMPUTER_API_URL")
+ create.add_argument("--api-key-env", default="OPENCOMPUTER_API_KEY")
+ create.add_argument("--confirm-name", required=True)
+ create.add_argument("--receipt", required=True)
+ create.add_argument("--timeout-seconds", type=int, default=1800)
+ create.add_argument("--poll-seconds", type=float, default=5)
+ return parser.parse_args()
+
+
+def main() -> int:
+ args = parse_args()
+ try:
+ if args.command == "check":
+ coordinate, _ = check_recipe()
+ print(
+ "Flue builder snapshot recipe is pinned: "
+ f"{coordinate['snapshot']['name']} "
+ f"({coordinate['recipe']['materializedManifestSha256']})"
+ )
+ else:
+ create_snapshot(args)
+ except SnapshotError as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())