An open-source, faster Devin alternative
TypeScript
fix(deploy): harden Flue builder runtime
Igor Zalutski711cddf0d470
diff --git a/ci/flue-builder-substrate-probe.py b/ci/flue-builder-substrate-probe.pyindex 85344097..73e310d9 100755--- a/ci/flue-builder-substrate-probe.py+++ b/ci/flue-builder-substrate-probe.py@@ -219,6 +219,22 @@ class LiveProbe:raise ProbeError("exec response is missing exitCode")return response+ def read_guest_file(self, sandbox_id: str, path: str, max_bytes: int = 512 * 1024) -> bytes:+ quoted_id = parse.quote(sandbox_id, safe="")+ quoted_path = parse.quote(path, safe="")+ req = request.Request(+ f"{self.api_url}/sandboxes/{quoted_id}/files?path={quoted_path}",+ headers={"Accept": "application/octet-stream", "X-API-Key": self.api_key},+ )+ try:+ with self.api.opener.open(req, timeout=30) as response:+ value = response.read(max_bytes + 1)+ except (error.HTTPError, error.URLError) as exc:+ raise ProbeError(f"trusted file read could not inspect {path}") from exc+ if len(value) > max_bytes:+ raise ProbeError(f"trusted file read exceeded its bound for {path}")+ return value+@staticmethoddef expect_success(label: str, response: dict[str, Any]) -> str:if response["exitCode"] != 0:@@ -235,6 +251,13 @@ class LiveProbe:f"{label} failed with exit {exit_code}, not a curl connection refusal/timeout")+ @staticmethod+ def expect_sudo_denied(response: dict[str, Any]) -> None:+ if response["exitCode"] != 1:+ raise ProbeError(+ "runtime `sudo -n true` did not return the expected policy-denied exit 1"+ )+@staticmethoddef curl_args(url: str) -> list[str]:return [@@ -251,6 +274,20 @@ class LiveProbe:]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",+ ),+ )+ sudo = self.exec(+ sandbox_id,+ "/usr/bin/sudo",+ ["-n", "/usr/bin/true"],+ )+ self.expect_sudo_denied(sudo)+javascript = r"""const cp = require("child_process");const fs = require("fs");@@ -261,6 +298,15 @@ const result = {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(),+ 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,installerRemoved: !fs.existsSync("/tmp/opencomputer-flue-builder-install.sh"),attestation: JSON.parse(fs.readFileSync("/opt/opencomputer/agent-build-snapshot.json", "utf8"))};@@ -278,6 +324,15 @@ process.stdout.write(JSON.stringify(result));"nodeVersion": attestation["node"]["version"],"npmVersion": attestation["npm"]["version"],"ocSha256": attestation["oc"]["binarySha256"],+ "runtimeUid": attestation["security"]["runtimeUid"],+ "nodeUid": 0,+ "nodeMode": 0o755,+ "ocUid": 0,+ "ocMode": 0o555,+ "verifierUid": 0,+ "verifierMode": 0o555,+ "attestationUid": 0,+ "attestationMode": 0o444,"attestation": attestation,}for key, value in expected.items():@@ -487,7 +542,6 @@ const add = (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",@@ -507,12 +561,7 @@ process.stdout.write(JSON.stringify({""".strip()raw_result = self.expect_success("credential sentinel scan",- self.exec(- sandbox_id,- "/usr/bin/sudo",- ["-n", "node", "-e", javascript],- timeout=30,- ),+ self.exec(sandbox_id, "node", ["-e", javascript], timeout=30),).strip()try:scan = json.loads(raw_result)@@ -520,14 +569,17 @@ process.stdout.write(JSON.stringify({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",- ):+ for required in ("process.env", "/opt/opencomputer/agent-build-snapshot.json"):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()diff --git a/ci/test_flue_builder_substrate_probe.py b/ci/test_flue_builder_substrate_probe.pyindex 20308ae2..12585c91 100644--- a/ci/test_flue_builder_substrate_probe.py+++ b/ci/test_flue_builder_substrate_probe.py@@ -19,7 +19,44 @@ 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(coordinate["snapshot"]["roles"], ["source", "build"])self.assertEqual(manifest["runtimeMemoryMB"], 1024)+ self.assertEqual(+ coordinate["attestation"]["security"],+ {+ "runtimeUser": "sandbox",+ "runtimeUid": 1000,+ "sudoPolicy": "denied",+ "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_private_canary_requires_literal_private_or_cgnat_address(self) -> None:for value in (@@ -71,6 +108,12 @@ class SubstrateProbeTest(unittest.TestCase):with self.subTest(exit_code=exit_code), self.assertRaises(PROBE.ProbeError):PROBE.LiveProbe.expect_transport_block("target", {"exitCode": exit_code})+ def test_runtime_sudo_must_be_policy_denied(self) -> None:+ PROBE.LiveProbe.expect_sudo_denied({"exitCode": 1})+ for exit_code in (0, 2, 126, 127):+ with self.subTest(exit_code=exit_code), self.assertRaises(PROBE.ProbeError):+ PROBE.LiveProbe.expect_sudo_denied({"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"diff --git a/deploy/flue-builder/README.md b/deploy/flue-builder/README.mdindex 89fbad16..e3d89460 100644--- a/deploy/flue-builder/README.md+++ b/deploy/flue-builder/README.md@@ -3,7 +3,9 @@This directory owns the immutable runtime used by the managed Flue repositorybuilder. 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.+OpenComputer, R2, Cloudflare, WfP, or coordinator credentials. It runs as uid+1000 with no passwordless sudo; the pinned toolchain is root-owned while+`/workspace` remains writable.## Pinned coordinate@@ -17,15 +19,17 @@ OpenComputer, R2, Cloudflare, WfP, or coordinator credentials.- 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`.+- raw installer, image-template, and materialized-manifest digests;+- the required runtime `networkPolicy=public`; and+- the hardened runtime contract: `sandbox` uid 1000, `sudo -n true` denied,+ root-owned read-only toolchain, and writable `/workspace`.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. 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.+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 everydownloaded toolchain/source archive, and verifies the built `oc` bytes. The@@ -33,6 +37,14 @@ checkpoint receipt freezes the resulting base and OS-package state. A futurerebuild is a new `rN` snapshot name, coordinate, and receipt even when thetoolchain 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 removes direct sudo grants and administrator-group+membership, locks the account password, makes `/opt/opencomputer` root-owned+and non-writable, preserves the user-owned workspace, installs a read-only+runtime verifier, and removes the installer. The last image step runs that+verifier as the ordinary sandbox user. No privileged step follows finalization.+## Offline validationThese commands perform no API calls and create nothing:@@ -43,29 +55,40 @@ 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.+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-## Create in isolated staging+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.-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:+With that plan approved, load a production operator key without printing it and+run:```bash-export OPENCOMPUTER_API_URL='https://staging.example.invalid'+export OPENCOMPUTER_API_URL='<approved-production-api>'export OPENCOMPUTER_API_KEY='...'export AGENT_BUILD_SNAPSHOT_ALLOW_CREATE=1+export AGENT_BUILD_SNAPSHOT_ALLOW_PRODUCTION=1python3 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`.+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`.Store the receipt in the deployment system's non-secret release metadata. Donot commit environment files or API keys. Configure the build worker from the@@ -78,8 +101,21 @@ AGENT_BUILD_NODE_VERSION=22.19.0AGENT_BUILD_NETWORK_POLICY=public```-Worker readiness must compare the live snapshot's manifest and checkpoint ID-to these coordinates before claiming repository builds.+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:++```text+AGENT_SOURCE_SANDBOX_SNAPSHOT=flue-build-node22-19-0-oc-c39b315-r1+AGENT_SOURCE_SANDBOX_CHECKPOINT_ID=<same receipt checkpointId>+```++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@@ -91,23 +127,27 @@ The live probe creates two short-lived sandboxes from the same checkpoint:2. the final `networkPolicy=public` sandbox, proving public npm registry andtarball 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+It also requires `sudo -n true` to fail as uid 1000, 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. It checks that+the create response has no host port, proves a temporary non-secret server ispublicly reachable through the unrestricted control, then requires previewcreation to return 409 and the equivalent restricted guest server to remainunreachable. Finally it scans guest process environments plus common-configuration files for exact credential sentinel values. The raw adapter+configuration files for exact credential sentinel values; the trusted file API+inspects PID 1 without restoring sudo to repository code. The raw adapterconstructs request bodies from an allowlist and never forwards the coordinatorprocess environment. Both sandboxes are destroyed in `finally`; a teardownfailure makes the probe fail and prints only the sandbox ID for operatorcleanup.-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:+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:```bash-export OPENCOMPUTER_API_URL='https://staging.example.invalid'+export OPENCOMPUTER_API_URL='<approved-production-api>'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>'@@ -115,6 +155,7 @@ 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_PROBE_ALLOW_PRODUCTION=1python3 ci/flue-builder-substrate-probe.py --run```@@ -125,8 +166,9 @@ planes unless `AGENT_BUILD_PROBE_ALLOW_HTTP=1` is set. The unrestricted controlguard is deliberately separate: without it, a policy regression could looklike 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.+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.diff --git a/deploy/flue-builder/coordinate.json b/deploy/flue-builder/coordinate.jsonindex dfbbf864..0bf5adc9 100644--- a/deploy/flue-builder/coordinate.json+++ b/deploy/flue-builder/coordinate.json@@ -2,16 +2,17 @@"schemaVersion": 1,"snapshot": {"name": "flue-build-node22-19-0-oc-c39b315-r1",+ "roles": ["source", "build"],"networkPolicy": "public","builderMemoryMB": 4096,"runtimeMemoryMB": 1024},"recipe": {"installer": "install-snapshot.sh",- "installerSha256": "1a4e60e0c72a1a2b5333c7456ed4d9e21fa193e446254ea3e4e8b78b8396ad6f",+ "installerSha256": "60793ed4e3a481dfd6b9df1e3a2b0ec014c7428259bdfd2a122206e8ff50a087","imageTemplate": "image.json",- "imageTemplateSha256": "d1fc4f3cd27fd1248327f52d9d768a99c9a922d4f0fabf8bf0d6913e2d1e7cd2",- "materializedManifestSha256": "4363cbdb960c8fceb12afbb87f9460c4e472a715bee3c06029f72b1539f7fa84"+ "imageTemplateSha256": "e5e8827412e76e6da94f8c2f9b97ddfe25579637905ef4e6d2f7fa563712683f",+ "materializedManifestSha256": "f334cd2ee291c707fc1c1efff5c6c38263fb78c2b8d8ca326d0d401b06004f32"},"attestation": {"schemaVersion": 1,@@ -38,6 +39,14 @@"buildToolchain": {"goVersion": "1.25.0","goArchiveSha256": "2852af0cb20a13139b3448992e69b868e50ed0f8a1e5940ee1de9e19a123b613"+ },+ "security": {+ "runtimeUser": "sandbox",+ "runtimeUid": 1000,+ "sudoPolicy": "denied",+ "toolchainOwner": "root",+ "workspace": "/workspace",+ "workspaceWritable": true}}}diff --git a/deploy/flue-builder/image.json b/deploy/flue-builder/image.jsonindex da46df7d..06e9a906 100644--- a/deploy/flue-builder/image.json+++ b/deploy/flue-builder/image.json@@ -32,8 +32,23 @@"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"+ "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"]}}diff --git a/deploy/flue-builder/install-snapshot.sh b/deploy/flue-builder/install-snapshot.shindex 5c02e8c1..b7cf7899 100755--- a/deploy/flue-builder/install-snapshot.sh+++ b/deploy/flue-builder/install-snapshot.sh@@ -29,6 +29,10 @@ 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"+WORKSPACE="/workspace"die() {echo "flue builder snapshot: $*" >&2@@ -87,6 +91,14 @@ write_attestation() {"buildToolchain": {"goVersion": "$GO_VERSION","goArchiveSha256": "$GO_ARCHIVE_SHA256"+ },+ "security": {+ "runtimeUser": "$RUNTIME_USER",+ "runtimeUid": $RUNTIME_UID,+ "sudoPolicy": "denied",+ "toolchainOwner": "root",+ "workspace": "$WORKSPACE",+ "workspaceWritable": true}}EOF@@ -186,10 +198,121 @@ 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"+[[ "\$(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"+[[ -x /usr/bin/sudo ]] || fail "sudo executable is missing"+[[ "\$(stat -c '%u:%a' /usr/bin/sudo)" == "0:4755" ]] \+ || fail "sudo executable metadata changed"+sudo_rc=0+/usr/bin/sudo -n /usr/bin/true >/dev/null 2>&1 || sudo_rc=\$?+[[ "\$sudo_rc" == "1" ]] || fail "sudo denial changed (exit \$sudo_rc)"+[[ -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_direct_sudo_grants() {+ local file++ # The base image currently grants `sandbox ALL=(ALL) NOPASSWD:ALL` directly+ # in /etc/sudoers. Remove any direct sandbox rule as well as membership in+ # conventional administrator groups so a future base-image variant fails+ # closed instead of retaining an equivalent grant.+ sed -i -E '/^[[:space:]]*sandbox[[:space:]]+ALL[[:space:]]*=/d' /etc/sudoers+ if [[ -d /etc/sudoers.d ]]; then+ while IFS= read -r -d '' file; do+ sed -i -E '/^[[:space:]]*sandbox[[:space:]]+ALL[[:space:]]*=/d' "$file"+ done < <(find /etc/sudoers.d -maxdepth 1 -type f -print0)+ fi+ for group in sudo admin wheel; do+ if id -nG "$RUNTIME_USER" | tr ' ' '\n' | grep -Fxq "$group"; then+ gpasswd -d "$RUNTIME_USER" "$group" >/dev/null+ fi+ done+ usermod --lock "$RUNTIME_USER"+ rm -rf "/run/sudo/ts/$RUNTIME_USER" "/var/run/sudo/ts/$RUNTIME_USER"+ visudo -cf /etc/sudoers >/dev/null+}++finalize() {+ local sudo_rc=0++ 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++ remove_direct_sudo_grants+ runuser -u "$RUNTIME_USER" -- /usr/bin/sudo -n /usr/bin/true \+ >/dev/null 2>&1 || sudo_rc=$?+ [[ "$sudo_rc" == "1" ]] \+ || die "runtime sudo denial returned unexpected exit $sudo_rc"++ # 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;;@@ -202,7 +325,10 @@ case "${1:-}" inverify)verify;;+ finalize)+ finalize+ ;;*)- die "usage: $0 {coordinate|node|oc|attest|verify}"+ die "usage: $0 {coordinate|runtime-verifier|node|oc|attest|verify|finalize}";;esacdiff --git a/deploy/flue-builder/snapshot.py b/deploy/flue-builder/snapshot.pyindex 3a48f7f8..8b222063 100755--- a/deploy/flue-builder/snapshot.py+++ b/deploy/flue-builder/snapshot.py@@ -108,12 +108,45 @@ def check_recipe() -> tuple[dict[str, Any], dict[str, Any]]: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,+ "sudoPolicy": "denied",+ "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,@@ -140,6 +173,39 @@ 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 (+ "/usr/bin/sudo -n /usr/bin/true",+ "sudo executable metadata changed",+ '[[ "$sudo_rc" == "1" ]]',+ "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}")+return coordinate, manifest