From f0cb7311cee48eb4ea7f41c539f1ece79e7adfac Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 13:54:15 -0800 Subject: [PATCH 1/4] Install verified pinned Goblin runtimes on first local use --- .github/workflows/ci.yml | 5 + Cargo.lock | 150 ++++++++++++++++- Cargo.toml | 4 + README.md | 10 +- docs/cli-reference.md | 30 +++- docs/publishing.md | 27 ++++ runtime-lock.json | 1 + scripts/pin_runtime.py | 93 +++++++++++ scripts/pin_runtime_test.py | 50 ++++++ src/cli.rs | 11 ++ src/commands.rs | 5 +- src/local_runtime.rs | 104 +++++++++++- src/main.rs | 1 + src/runtime.rs | 156 ++++++++++++++++++ src/runtime/bundle.rs | 304 ++++++++++++++++++++++++++++++++++ src/runtime/install.rs | 152 +++++++++++++++++ src/runtime/tests.rs | 314 ++++++++++++++++++++++++++++++++++++ tests/backend/mod.rs | 37 +++++ 18 files changed, 1436 insertions(+), 18 deletions(-) create mode 100644 runtime-lock.json create mode 100644 scripts/pin_runtime.py create mode 100644 scripts/pin_runtime_test.py create mode 100644 src/runtime.rs create mode 100644 src/runtime/bundle.rs create mode 100644 src/runtime/install.rs create mode 100644 src/runtime/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fdbc25..b71fa70 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,6 +53,7 @@ jobs: echo "CARGO_TARGET_${target_env}_LINKER=musl-gcc" >> "$GITHUB_ENV" echo "CC_${TARGET//-/_}=musl-gcc" >> "$GITHUB_ENV" - run: python -m unittest discover -s scripts -p '*_test.py' + - run: python scripts/pin_runtime.py --check - run: cargo fmt --all -- --check - run: cargo clippy --locked --all-targets --target ${{ matrix.target }} -- -D warnings - run: cargo test --locked --target ${{ matrix.target }} @@ -78,6 +79,8 @@ jobs: id-token: write steps: - uses: actions/checkout@v4 + - name: Require a published runtime pin before releasing the CLI + run: python3 scripts/pin_runtime.py --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* @@ -109,6 +112,8 @@ jobs: id-token: write steps: - uses: actions/checkout@v4 + - name: Require a published runtime pin before releasing the CLI + run: python3 scripts/pin_runtime.py --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* diff --git a/Cargo.lock b/Cargo.lock index 2632399..bffe9e0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "anstream" version = "1.0.0" @@ -91,6 +97,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -182,6 +197,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "convert_case" version = "0.10.0" @@ -225,6 +246,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + [[package]] name = "crossterm" version = "0.29.0" @@ -262,6 +292,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -296,8 +335,19 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -336,12 +386,33 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -466,6 +537,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + [[package]] name = "http" version = "1.5.0" @@ -511,6 +588,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -754,6 +840,16 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.4" @@ -827,12 +923,16 @@ dependencies = [ "base64 0.22.1", "clap", "crossterm", + "flate2", "futures-util", + "hex", "httpdate", "libc", "reqwest", "serde", "serde_json", + "sha2", + "tar", "tempfile", "tokio", "tokio-tungstenite", @@ -1257,7 +1357,18 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -1297,6 +1408,12 @@ dependencies = [ "libc", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "slab" version = "0.4.12" @@ -1379,6 +1496,17 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -1892,6 +2020,16 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + [[package]] name = "yoke" version = "0.8.4" @@ -1995,6 +2133,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index d5d5b7e..ecfde17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,10 @@ url = "2.5" uuid = { version = "1.27", features = ["v4", "serde"] } [target.'cfg(unix)'.dependencies] +flate2 = "1" +hex = "0.4" +sha2 = "0.11" +tar = "0.4" libc = "0.2" [profile.release] diff --git a/README.md b/README.md index 1027e54..5b49e26 100644 --- a/README.md +++ b/README.md @@ -86,11 +86,10 @@ Use `--no-expiry` to disable automatic expiry. ### Run sandboxes locally -On Apple Silicon macOS or x86_64 Linux with KVM, point Adapt at a compatible -Goblin bundle containing `goblind` and an embedded-firmware `goblin-worker`: +On Apple Silicon macOS or x86_64 Linux with KVM, Adapt downloads and verifies +its pinned Goblin runtime on first local use: ```sh -export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin adapt sandbox sh --local --image ubuntu:24.04 -- uname -m adapt sandbox sh --local adapt --local sandbox create --image ubuntu:24.04 --wait @@ -103,7 +102,10 @@ Adapt starts and reuses a private local manager without Platform login. The shel or command from `sandbox sh` runs in a VM that is deleted when the session ends. `sandbox create` keeps the VM for later commands until you stop or delete it. Existing commands keep their cloud default; `sandbox sh --cloud` selects it explicitly. -This initial local workflow requires a manually supplied runtime bundle. See +Use `adapt runtime install` to download ahead of time and `adapt runtime status` +to inspect the pin and installation path. Local downloads need no login. Developers +can still supply `ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin` or `--runtime-dir`. +See [local sandbox options and limitations](docs/cli-reference.md#local-sandboxes). ## Create a sandbox diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 4374331..24b1115 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -28,6 +28,7 @@ For example, use `adapt org members ls` or `adapt sandbox ls --all`. | Command | Operations | | --- | --- | | `auth` | `login`, `status`, `logout` | +| `runtime` | `install`, `status` (local, no login required) | | `skill` | `install`, `show`, `uninstall` | | `whoami` | Show your account, organization, and permissions | | `org` | `list`, `use`, `current`, `create`, `update`, `delete` | @@ -225,8 +226,28 @@ Shells have a maximum execution timeout of 24 hours. ### Local sandboxes +`adapt runtime install` downloads and verifies this CLI build's pinned Goblin +release without starting a manager. The first supported local operation does the +same automatically when no compatible manager is already running. `adapt runtime +status` is read-only: it shows the pin, path, and whether the expected binaries +are present; installation reuse also verifies their contents. + +Downloads use the public runtime endpoint on `platform.adapt.com`, independently +of cloud profiles and credentials. Archives and their manifests are checked +against hashes embedded in the CLI. Installed files live under +`/runtimes///`, with private directories and +serialized, atomic installation. Cached runtimes work offline; images may still +need to be pulled. Linux releases require glibc 2.36 or newer and access to KVM. + +Installing a new release never replaces old files or restarts the manager. A +compatible running manager is reused. An incompatible or unknown runtime ABI +requires using the original runtime to migrate/recreate sandboxes, or selecting +a fresh `--local-state-dir`. Old release directories remain because VM records +can reference them. `--runtime-dir` / `ADAPT_LOCAL_RUNTIME` explicitly select a +manual development bundle and bypass managed downloads and pin compatibility. + ```sh -export ADAPT_LOCAL_RUNTIME=/path/to/goblin-release/bin +adapt runtime install # optional prefetch adapt sandbox sh --local --image ubuntu:24.04 -- uname -m adapt --local sandbox create --image ubuntu:24.04 --env EDITOR=vim --wait adapt --local sandbox list @@ -263,12 +284,11 @@ and `memoryMiB` fields where available, alongside Goblin's diagnostics. Goblin's `stopped`, `deleted`, `failed`, or `completed`, and respect `--wait-timeout`. Stopping a VM ends its processes; restarting it is not implemented yet. -Supply a compatible Goblin runtime with `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`. +To use a development bundle, set `--runtime-dir` or `ADAPT_LOCAL_RUNTIME`. The directory must contain `goblind` with `--ready-file` and `--unix-socket` support and a native `goblin-worker` with matching embedded firmware. The macOS -worker must be signed with its hypervisor entitlement. Automatic bundle -installation is not included yet. Adapt discovers a running manager before -requiring the bundle path again. +worker must be signed with its hypervisor entitlement. Adapt discovers a running +manager before requiring the bundle path again. State, image cache, the local token, discovery metadata, sandbox environment files, and `goblind.log` live in `ADAPT_CONFIG_DIR/local` (using the usual config diff --git a/docs/publishing.md b/docs/publishing.md index 45f37d1..cf33d51 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -112,3 +112,30 @@ Run `python3 -m unittest discover -s scripts -p '*_test.py'`. Tests cover comple and interrupted publication, stale runs, immutable retries, corrupt manifests, and packaging only the intended executable. The first public build appears after this workflow reaches `main` and its checks pass. + + +## Pinning the local runtime + +`runtime-lock.json` is compiled into every CLI executable. It contains one exact +Goblin revision, its compatibility metadata, and archive/manifest hashes for both +supported runtime targets. There is no runtime `latest` lookup. Update it with: + +```sh +python3 scripts/pin_runtime.py GOBLIN_REVISION +``` + +The command reads the public immutable lock and verifies both archives before +atomically changing the source pin. Review the resulting diff and run CI before +releasing the CLI. `--base-url` supports fetching a pin from another trusted HTTPS +mirror during development; runtime downloads still use the production endpoint. + +The first rollout is ordered: deploy Platform's `/runtime/goblin` route, merge +Goblin's runtime publisher, configure its signing/OIDC environment, publish and +qualify both runtime bundles, then fill this CLI's pin and merge the CLI change. +The initial development lock is `null` until real artifacts exist. Unit tests and +manual `--runtime-dir` operation support that state; both publication jobs reject +it, so a CLI with an unconfigured managed runtime cannot be released. + +Goblin owns Developer ID signing and notarization of the macOS runtime. This +change does not add Developer ID signing to the `adapt` executable. Runtime +upgrades do not restart managers or delete old installations automatically. diff --git a/runtime-lock.json b/runtime-lock.json new file mode 100644 index 0000000..19765bd --- /dev/null +++ b/runtime-lock.json @@ -0,0 +1 @@ +null diff --git a/scripts/pin_runtime.py b/scripts/pin_runtime.py new file mode 100644 index 0000000..db0232d --- /dev/null +++ b/scripts/pin_runtime.py @@ -0,0 +1,93 @@ +"""Verify an immutable published Goblin release and pin it in the CLI source.""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import tempfile +from urllib.parse import urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener + +TARGETS = {"aarch64-apple-darwin", "x86_64-unknown-linux-gnu"} +MAX_ARCHIVE = 512 * 1024 * 1024 +DEFAULT_BASE = "https://platform.adapt.com/runtime/goblin/" + + +def validate(pin, required=True): + if pin is None: + if required: + raise ValueError("Pin a published runtime before releasing this CLI: python scripts/pin_runtime.py REVISION") + return + if (not isinstance(pin, dict) or set(pin) != {"format", "revision", "api_version", "runtime_abi", "guest_protocol", "targets"} + or type(pin["format"]) is not int or pin["format"] != 1 + or type(pin["api_version"]) is not int or pin["api_version"] != 1 + or not re.fullmatch(r"[a-f0-9]{40}", pin["revision"]) + or any(type(pin[k]) is not int or not 0 < pin[k] <= 0xffffffff for k in ("runtime_abi", "guest_protocol")) + or set(pin["targets"]) != TARGETS): + raise ValueError("Invalid runtime lock identity or target set") + for record in pin["targets"].values(): + if (set(record) != {"sha256", "manifest_sha256", "size"} + or any(not re.fullmatch(r"[a-f0-9]{64}", record[k]) for k in ("sha256", "manifest_sha256")) + or type(record["size"]) is not int or not 0 < record["size"] <= MAX_ARCHIVE): + raise ValueError("Invalid runtime artifact pin") + + +class NoRedirects(HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def pin_release(revision, destination, base=DEFAULT_BASE, opener=None): + if not re.fullmatch(r"[a-f0-9]{40}", revision): + raise ValueError("Expected a full Goblin commit SHA") + origin = urlsplit(base) + if (origin.scheme != "https" or not origin.netloc or origin.username or origin.password + or origin.query or origin.fragment or not origin.path.endswith("/")): + raise ValueError("Expected an HTTPS directory URL without credentials") + opener = opener or build_opener(NoRedirects()) + def get(name): + return opener.open(Request(f"{base}{revision}/{name}", headers={"Accept-Encoding": "identity"}), timeout=300) + with get("runtime-lock.json") as response: + encoded = response.read(65537) + if len(encoded) > 65536: + raise ValueError("Oversized runtime lock") + pin = json.loads(encoded) + validate(pin) + if pin["revision"] != revision: + raise ValueError("Published runtime revision mismatch") + for target, record in pin["targets"].items(): + h, size = hashlib.sha256(), 0 + with get(f"{target}.tar.gz") as response: + while chunk := response.read(65536): + size += len(chunk) + if size > record["size"]: + raise ValueError("Runtime download exceeds pinned size") + h.update(chunk) + if size != record["size"] or h.hexdigest() != record["sha256"]: + raise ValueError("Published runtime archive checksum mismatch") + # Update only after both exact artifacts are available and verified. + with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as file: + temporary = Path(file.name) + try: + file.write((json.dumps(pin, sort_keys=True, indent=2) + "\n").encode()) + file.flush() + temporary.replace(destination) + finally: + temporary.unlink(missing_ok=True) + return pin + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("revision", nargs="?") + parser.add_argument("--check", action="store_true") + parser.add_argument("--require", action="store_true") + parser.add_argument("--lock", type=Path, default=Path("runtime-lock.json")) + parser.add_argument("--base-url", default=DEFAULT_BASE) + args = parser.parse_args() + if args.check: + validate(json.loads(args.lock.read_text()), required=args.require) + elif args.revision: + pin_release(args.revision, args.lock, args.base_url) + else: + parser.error("Supply a revision or --check") diff --git a/scripts/pin_runtime_test.py b/scripts/pin_runtime_test.py new file mode 100644 index 0000000..ec389e9 --- /dev/null +++ b/scripts/pin_runtime_test.py @@ -0,0 +1,50 @@ +import hashlib +import io +import json +from pathlib import Path +import tempfile +import unittest +from pin_runtime import TARGETS, pin_release, validate + +REVISION = "a" * 40 +BODY = b"test archive bytes" + +def pin(): + return dict(format=1, revision=REVISION, api_version=1, runtime_abi=7, guest_protocol=10, + targets={target: dict(size=len(BODY), sha256=hashlib.sha256(BODY).hexdigest(), manifest_sha256="b" * 64) for target in TARGETS}) + +class Opener: + def __init__(self, contents): self.contents = list(contents) + def open(self, request, **_): + if not request.full_url.startswith("https://platform.adapt.com/runtime/goblin/" + REVISION + "/"): + raise AssertionError(request.full_url) + return io.BytesIO(self.contents.pop(0)) + +class PinRuntimeTest(unittest.TestCase): + def test_release_requires_a_real_pin(self): + validate(None, required=False) + with self.assertRaises(ValueError): validate(None) + validate(pin()) + bad = pin(); bad["targets"].pop(next(iter(TARGETS))) + with self.assertRaises(ValueError): validate(bad) + + def test_both_targets_verify_before_replacing_existing_pin(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "runtime-lock.json" + path.write_text("null\n") + for bodies in [(BODY, b"bad"), (b"bad", BODY)]: + with self.assertRaises(ValueError): pin_release(REVISION, path, opener=Opener([json.dumps(pin()).encode(), *bodies])) + self.assertEqual(path.read_text(), "null\n") + self.assertEqual(pin_release(REVISION, path, opener=Opener([json.dumps(pin()).encode(), BODY, BODY])), pin()) + self.assertEqual(json.loads(path.read_text()), pin()) + + def test_rejects_untrusted_urls_and_mismatched_identity(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "pin.json" + for base in ["http://localhost/", "https://user:password@example.com/", "https://example.com/?x=1"]: + with self.assertRaises(ValueError): pin_release(REVISION, path, base=base) + wrong = pin(); wrong["revision"] = "c" * 40 + with self.assertRaises(ValueError): pin_release(REVISION, path, opener=Opener([json.dumps(wrong).encode()])) + self.assertFalse(path.exists()) + +if __name__ == "__main__": unittest.main() diff --git a/src/cli.rs b/src/cli.rs index 9f2a7bb..2e02e1b 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -54,6 +54,9 @@ pub enum Command { /// Install or remove the bundled guide for coding agents (works offline) #[command(subcommand)] Skill(SkillCommand), + /// Install or inspect the local sandbox runtime + #[command(subcommand)] + Runtime(RuntimeCommand), /// Show your effective identity and organization permissions Whoami, /// Manage organizations and choose a default @@ -116,6 +119,14 @@ pub enum Command { Api(ApiArgs), } +#[derive(Subcommand)] +pub enum RuntimeCommand { + /// Download and verify this CLI's pinned runtime without starting a daemon + Install, + /// Show the pinned release and installation path without downloading + Status, +} + #[derive(Subcommand)] pub enum SkillCommand { /// Print the bundled skill as Markdown diff --git a/src/commands.rs b/src/commands.rs index 5a2444f..a2ef96b 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -24,6 +24,9 @@ use url::Url; use uuid::Uuid; pub async fn run(cli: Cli) -> Result { + if let Command::Runtime(command) = &cli.command { + return crate::runtime::run(command, &cli).await; + } if let Command::Skill(command) = &cli.command { skill::run(command, cli.json)?; return Ok(0); @@ -100,7 +103,7 @@ pub async fn run(cli: Cli) -> Result { Duration::from_secs(cli.timeout), )?; let result = match cli.command { - Command::Skill(_) => unreachable!("Skill commands run before API configuration"), + Command::Skill(_) | Command::Runtime(_) => unreachable!("Local utility commands run before API configuration"), Command::Auth(AuthCommand::Login { no_browser, token_stdin }) => { let anonymous = Api::new(origin.clone(), None, None, api.timeout)?; let credential = if token_stdin { diff --git a/src/local_runtime.rs b/src/local_runtime.rs index af8d74d..2531df6 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -48,6 +48,10 @@ mod unix { socket_path: std::path::PathBuf, instance_id: Uuid, runtime_version: String, + #[serde(default)] + release_revision: Option, + #[serde(default)] + runtime_abi: Option, } fn private_metadata(path: &Path, directory: bool) -> Result<()> { @@ -94,7 +98,12 @@ mod unix { Ok(bytes) } - async fn discover(state: &Path, token: &str, timeout: Duration) -> Result> { + async fn discover( + state: &Path, + token: &str, + timeout: Duration, + pin: Option<&crate::runtime::Pin>, + ) -> Result> { let path = state.join("ready.json"); let bytes = match read(&path) { Ok(bytes) => bytes, @@ -159,6 +168,9 @@ mod unix { "Local runtime is incompatible or has no embedded image firmware; use a compatible Goblin bundle" ); } + if let Some(pin) = pin { + compatible_identity(&ready, &spec, pin.runtime_abi)?; + } Ok(Some(Goblin::new( ready.socket_path, token, @@ -167,6 +179,36 @@ mod unix { )?)) } + fn compatible_identity(ready: &Ready, spec: &serde_json::Value, abi: u32) -> Result<()> { + if ready.runtime_abi != Some(abi) + || spec["runtime_abi"].as_u64() != Some(u64::from(abi)) + || !ready + .release_revision + .as_ref() + .is_some_and(|r| crate::runtime::hex(r, 40)) + || spec["release_revision"].as_str() != ready.release_revision.as_deref() + { + bail!( + "The running local runtime is incompatible with this CLI's pin. It was left running; use its original CLI/runtime to stop and migrate or recreate sandboxes before changing runtimes" + ); + } + Ok(()) + } + + fn compatible_state(state: &Path, abi: u32) -> Result<()> { + if state.join("ready.json").try_exists()? { + let previous: Ready = serde_json::from_slice(&read(&state.join("ready.json"))?)?; + if previous.runtime_abi == Some(abi) { + return Ok(()); + } + } else if !state.join("vms").try_exists()? && !state.join("sandboxes").try_exists()? { + return Ok(()); + } + bail!( + "Existing local state belongs to a different or unknown runtime ABI; use the original runtime to migrate or recreate its sandboxes, or choose a fresh --local-state-dir" + ) + } + pub async fn connect( state: &Path, runtime: Option<&Path>, @@ -179,7 +221,7 @@ mod unix { private_metadata(state, true)?; let state = state.canonicalize()?; let lock = open(&state.join("bootstrap.lock"), true)?; - let deadline = Instant::now() + Duration::from_secs(30); + let deadline = Instant::now() + Duration::from_secs(300); loop { // SAFETY: the descriptor is live and exclusively owned by this scope. if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { @@ -211,10 +253,20 @@ mod unix { if token.len() < 32 || token.len() > 4096 || token.chars().any(char::is_whitespace) { bail!("Invalid local runtime token file"); } - if let Some(local) = discover(&state, token, timeout).await? { + let pin = if runtime.is_none() { + crate::runtime::configured_pin()? + } else { + None + }; + if let Some(local) = discover(&state, token, timeout, pin.as_ref()).await? { return Ok(local); } - let runtime = runtime.context("Set ADAPT_LOCAL_RUNTIME or --runtime-dir to a directory containing goblind and an embedded-firmware goblin-worker; automatic runtime installation is not available yet")?.canonicalize()?; + if let Some(pin) = &pin { + // Stopped workers and persisted VM records can still reference old binaries. + compatible_state(&state, pin.runtime_abi)?; + } + let runtime = crate::runtime::resolve(&state, runtime, timeout).await?; + let deadline = Instant::now() + Duration::from_secs(30); let manager = runtime .join("goblind") .canonicalize() @@ -263,7 +315,7 @@ mod unix { eprintln!("Starting local runtime; log: {}", log_path.display()); let mut child = command.spawn().context("Cannot start goblind")?; loop { - if let Some(local) = discover(&state, token, timeout).await? { + if let Some(local) = discover(&state, token, timeout, pin.as_ref()).await? { return Ok(local); } if let Some(status) = child.try_wait()? { @@ -283,4 +335,46 @@ mod unix { sleep(Duration::from_millis(50)).await; } } + #[cfg(test)] + mod tests { + use super::*; + use serde_json::json; + use std::os::unix::fs::PermissionsExt; + + fn ready() -> serde_json::Value { + json!({"version":1,"socket_path":"/unused/goblind.sock","instance_id":Uuid::new_v4(), + "runtime_version":"0.1.0","runtime_abi":7,"release_revision":"a".repeat(40)}) + } + #[test] + fn runtime_abi_and_exact_discovery_identity_are_required_for_managed_reuse() { + let metadata = ready(); + let ready: Ready = serde_json::from_value(metadata.clone()).unwrap(); + compatible_identity(&ready, &metadata, 7).unwrap(); + assert!(compatible_identity(&ready, &metadata, 8).is_err()); + let mut other = metadata.clone(); + other["release_revision"] = json!("b".repeat(40)); + assert!(compatible_identity(&ready, &other, 7).is_err()); + let mut old = metadata.clone(); + old.as_object_mut().unwrap().remove("runtime_abi"); + assert!( + compatible_identity(&serde_json::from_value(old.clone()).unwrap(), &old, 7) + .is_err() + ); + } + #[test] + fn unknown_or_incompatible_persisted_state_is_preserved() { + let dir = tempfile::tempdir().unwrap(); + compatible_state(dir.path(), 7).unwrap(); + fs::create_dir(dir.path().join("vms")).unwrap(); + assert!(compatible_state(dir.path(), 7).is_err()); + let path = dir.path().join("ready.json"); + let bytes = serde_json::to_vec(&ready()).unwrap(); + fs::write(&path, &bytes).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + compatible_state(dir.path(), 7).unwrap(); + assert!(compatible_state(dir.path(), 8).is_err()); + assert_eq!(fs::read(path).unwrap(), bytes); + assert!(dir.path().join("vms").is_dir()); + } + } } diff --git a/src/main.rs b/src/main.rs index af14adf..ee4a910 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,6 +8,7 @@ mod input; mod local_runtime; mod mcp; mod output; +mod runtime; mod shell; mod skill; mod stream; diff --git a/src/runtime.rs b/src/runtime.rs new file mode 100644 index 0000000..829b473 --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,156 @@ +//! Immutable Goblin releases selected by this CLI build, independently of cloud profiles. +use crate::{ + cli::{Cli, RuntimeCommand}, + config, output, +}; +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use serde_json::json; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + time::Duration, +}; + +#[cfg(unix)] +mod bundle; +#[cfg(unix)] +mod install; +#[cfg(test)] +mod tests; + +pub const MAX_ARCHIVE: u64 = 512 * 1024 * 1024; +#[cfg(unix)] +const DOWNLOAD_BASE: &str = "https://platform.adapt.com/runtime/goblin/"; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Pin { + pub format: u32, + pub revision: String, + pub api_version: u32, + pub runtime_abi: u32, + pub guest_protocol: u32, + pub targets: BTreeMap, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Artifact { + pub sha256: String, + pub manifest_sha256: String, + pub size: u64, +} +pub fn hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} +impl Pin { + pub fn validate(&self) -> Result<()> { + if self.format != 1 + || self.api_version != 1 + || !hex(&self.revision, 40) + || self.runtime_abi == 0 + || self.guest_protocol == 0 + || self.targets.keys().map(String::as_str).collect::>() + != ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] + || self.targets.values().any(|a| { + !hex(&a.sha256, 64) + || !hex(&a.manifest_sha256, 64) + || a.size == 0 + || a.size > MAX_ARCHIVE + }) + { + bail!("Invalid or unsupported local runtime pin"); + } + Ok(()) + } +} +pub fn configured_pin() -> Result> { + let pin: Option = serde_json::from_str(include_str!("../runtime-lock.json"))?; + if let Some(pin) = &pin { + pin.validate()?; + } + Ok(pin) +} +#[cfg(unix)] +pub fn required_pin() -> Result { + configured_pin()?.context("This development build has no published runtime pin. Set --runtime-dir or ADAPT_LOCAL_RUNTIME to a compatible Goblin bundle") +} +pub fn target() -> Result<&'static str> { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("macos", "aarch64") => Ok("aarch64-apple-darwin"), + ("linux", "x86_64") => Ok("x86_64-unknown-linux-gnu"), + _ => { + bail!("Local sandboxes currently require Apple Silicon macOS or x86_64 Linux with KVM") + } + } +} +fn state_dir(cli: &Cli) -> Result { + cli.local_state_dir + .clone() + .map(Ok) + .unwrap_or_else(|| config::directory(cli.config_dir.as_deref()).map(|p| p.join("local"))) +} +pub async fn run(command: &RuntimeCommand, cli: &Cli) -> Result { + if cli.cloud_target { + bail!("Runtime commands manage the local runtime; --cloud is not supported"); + } + let target = target()?; + let state = state_dir(cli)?; + match command { + RuntimeCommand::Install => { + let path = resolve( + &state, + cli.runtime_dir.as_deref(), + Duration::from_secs(cli.timeout), + ) + .await?; + output::print(&json!({"path":path,"target":target}), cli.json)?; + } + RuntimeCommand::Status => { + let pin = configured_pin()?; + let path = cli.runtime_dir.clone().or_else(|| { + pin.as_ref() + .map(|p| installation(&state, p, target).join("bin")) + }); + let installed = path + .as_ref() + .is_some_and(|p| p.join("goblind").is_file() && p.join("goblin-worker").is_file()); + // Status is read-only and never downloads or starts a manager. + output::print( + &json!({"target":target,"pin":pin,"path":path,"installed":installed,"override":cli.runtime_dir.is_some()}), + cli.json, + )?; + } + } + Ok(0) +} +fn installation(state: &Path, pin: &Pin, target: &str) -> PathBuf { + state.join("runtimes").join(&pin.revision).join(target) +} +pub async fn resolve(state: &Path, explicit: Option<&Path>, timeout: Duration) -> Result { + target()?; + if let Some(path) = explicit { + let path = path + .canonicalize() + .context("Cannot open the local runtime directory")?; + for name in ["goblind", "goblin-worker"] { + if !path.join(name).is_file() { + bail!("Runtime directory is missing {name}"); + } + } + return Ok(path); + } + #[cfg(unix)] + { + let pin = required_pin()?; + install::ensure(state, &pin, target()?, DOWNLOAD_BASE, timeout).await + } + #[cfg(not(unix))] + { + let _ = (state, timeout); + unreachable!() + } +} diff --git a/src/runtime/bundle.rs b/src/runtime/bundle.rs new file mode 100644 index 0000000..82af9ac --- /dev/null +++ b/src/runtime/bundle.rs @@ -0,0 +1,304 @@ +use super::{Artifact, Pin, hex}; +use anyhow::{Context, Result, bail}; +use flate2::bufread::GzDecoder; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs::{self, File}, + io::{Read, Write}, + os::unix::fs::{OpenOptionsExt, PermissionsExt}, + path::Path, +}; + +const MAX_CONTENT: u64 = 1024 * 1024 * 1024; +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Manifest { + format: u32, + release: String, + revision: String, + dirty: bool, + target: String, + runtime_abi: u32, + guest_protocol: u32, + management_protocol: u32, + files: BTreeMap, +} +#[derive(Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct Record { + sha256: String, + size: u64, + mode: u32, +} + +fn names(target: &str) -> BTreeSet { + [ + "bin/goblin", + "bin/goblind", + "bin/goblin-worker", + "bin/goblin-node", + "docs/DEPLOYMENT.md", + "docs/FIRMWARE.md", + "guest/kernel.config", + "guest/kernel-source.json", + "guest/kernel-manifest.json", + "guest/KERNEL-COPYING", + "guest/KERNEL-GPL-2.0", + "guest/KERNEL-Linux-syscall-note", + "guest/initramfs-manifest.json", + "guest/image-builder-manifest.json", + "guest/hello.json", + "guest/BUSYBOX-COPYRIGHT", + "guest/IMAGE-TOOLS-NOTICES", + if target == "aarch64-apple-darwin" { + "packaging/goblin-worker.entitlements" + } else { + "packaging/goblind.service" + }, + ] + .into_iter() + .map(str::to_owned) + .collect() +} +fn manifest(bytes: &[u8], pin: &Pin, target: &str, artifact: &Artifact) -> Result { + if bytes.len() > 65536 || hex::encode(Sha256::digest(bytes)) != artifact.manifest_sha256 { + bail!("Local runtime manifest checksum mismatch"); + } + let m: Manifest = serde_json::from_slice(bytes)?; + if m.format != 2 + || m.dirty + || m.revision != pin.revision + || m.release != pin.revision + || m.target != target + || m.runtime_abi != pin.runtime_abi + || m.guest_protocol != pin.guest_protocol + || m.management_protocol != 1 + || m.files.keys().cloned().collect::>() != names(target) + { + bail!("Local runtime bundle identity or contents do not match the pinned release"); + } + let mut total = 0u64; + for (name, r) in &m.files { + total = total.checked_add(r.size).context("Runtime size overflow")?; + if r.size == 0 + || total > MAX_CONTENT + || !hex(&r.sha256, 64) + || r.mode + != if name.starts_with("bin/") { + 0o755 + } else { + 0o644 + } + { + bail!("Invalid runtime file metadata"); + } + } + Ok(m) +} +fn copy(mut source: impl Read, mut output: Option<&mut File>, record: &Record) -> Result<()> { + let mut hash = Sha256::new(); + let mut size = 0; + let mut buffer = [0; 65536]; + loop { + let n = source.read(&mut buffer)?; + if n == 0 { + break; + } + size += n as u64; + if size > record.size { + bail!("Runtime file exceeds its expected size"); + } + hash.update(&buffer[..n]); + if let Some(file) = output.as_mut() { + file.write_all(&buffer[..n])?; + } + } + if size != record.size || hex::encode(hash.finalize()) != record.sha256 { + bail!("Runtime file checksum mismatch"); + } + Ok(()) +} +pub(super) fn extract(archive: &Path, destination: &Path, pin: &Pin, target: &str) -> Result<()> { + let artifact = &pin.targets[target]; + // The downloader verifies the compressed bytes before this function runs. + fs::create_dir(destination)?; + fs::set_permissions(destination, fs::Permissions::from_mode(0o700))?; + let source = std::io::BufReader::new(File::open(archive)?); + let mut tar = tar::Archive::new(GzDecoder::new(source).take(MAX_CONTENT + 131072)); + let mut entries = tar.entries()?.raw(true); + let mut first = entries.next().context("Missing runtime manifest")??; + if first.path_bytes().as_ref() != b"manifest.json" + || !first.header().entry_type().is_file() + || first.size() > 65536 + { + bail!("Expected a bounded regular manifest.json first"); + } + let mut bytes = Vec::new(); + first.read_to_end(&mut bytes)?; + let m = manifest(&bytes, pin, target, artifact)?; + fs::write(destination.join("manifest.json"), bytes)?; + let mut seen = BTreeSet::new(); + for entry in entries { + let mut entry = entry?; + let name = String::from_utf8(entry.path_bytes().into_owned())?; + let record = m + .files + .get(&name) + .context("Unexpected runtime archive path")?; + if !seen.insert(name.clone()) + || !entry.header().entry_type().is_file() + || entry.size() != record.size + || entry.header().mode()? != record.mode + { + bail!("Invalid or duplicate runtime archive entry"); + } + let path = destination.join(name); + fs::create_dir_all(path.parent().unwrap())?; + let mut file = File::options() + .write(true) + .create_new(true) + .mode(record.mode) + .open(&path)?; + copy(&mut entry, Some(&mut file), record)?; + file.set_permissions(fs::Permissions::from_mode(record.mode))?; + file.sync_all()?; + } + if seen.len() != m.files.len() { + bail!("Missing runtime archive files"); + } + let mut decoder = tar.into_inner(); + let mut tail = Vec::new(); + decoder.by_ref().take(65537).read_to_end(&mut tail)?; + let mut compressed = decoder.into_inner().into_inner(); + let mut extra = [0; 1]; + if tail.len() > 65536 || tail.iter().any(|b| *b != 0) || compressed.read(&mut extra)? != 0 { + bail!("Unexpected runtime archive trailer"); + } + File::open(destination.join("manifest.json"))?.sync_all()?; + Ok(()) +} +pub(super) fn verify(path: &Path, pin: &Pin, target: &str) -> Result<()> { + for directory in [ + path.to_owned(), + path.join("bin"), + path.join("guest"), + path.join("docs"), + path.join("packaging"), + ] { + if !fs::symlink_metadata(directory)?.is_dir() { + bail!("Runtime directories must not be symlinks"); + } + } + let mut source = File::options() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path.join("manifest.json"))?; + if !source.metadata()?.is_file() { + bail!("Runtime manifest is not a regular file"); + } + let mut bytes = Vec::new(); + Read::by_ref(&mut source) + .take(65537) + .read_to_end(&mut bytes)?; + let m = manifest(&bytes, pin, target, &pin.targets[target])?; + for (name, record) in m.files { + let file = File::options() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path.join(name))?; + let meta = file.metadata()?; + if !meta.is_file() + || meta.len() != record.size + || meta.permissions().mode() & 0o7777 != record.mode + { + bail!("Installed runtime file metadata changed"); + } + copy(file, None, &record)?; + } + Ok(()) +} + +#[cfg(test)] +pub(super) fn fixture( + pin: &mut Pin, + target: &str, + extra: Option<(&str, tar::EntryType)>, +) -> Vec { + let payload = b"test executable\n"; + let files = names(target) + .into_iter() + .map(|name| { + let record = Record { + sha256: hex::encode(Sha256::digest(payload)), + size: payload.len() as u64, + mode: if name.starts_with("bin/") { + 0o755 + } else { + 0o644 + }, + }; + (name, record) + }) + .collect(); + let m = Manifest { + format: 2, + release: pin.revision.clone(), + revision: pin.revision.clone(), + dirty: false, + target: target.into(), + runtime_abi: pin.runtime_abi, + guest_protocol: pin.guest_protocol, + management_protocol: 1, + files, + }; + let bytes = serde_json::to_vec(&m).unwrap(); + let mut tar = tar::Builder::new(flate2::write::GzEncoder::new( + Vec::new(), + flate2::Compression::default(), + )); + fn add( + tar: &mut tar::Builder, + name: &str, + mode: u32, + bytes: &[u8], + kind: tar::EntryType, + ) { + let mut h = tar::Header::new_ustar(); + h.set_size(bytes.len() as u64); + h.set_mode(mode); + h.set_entry_type(kind); + h.set_cksum(); + tar.append_data(&mut h, name, bytes).unwrap(); + } + add( + &mut tar, + "manifest.json", + 0o644, + &bytes, + tar::EntryType::Regular, + ); + for (name, record) in &m.files { + add( + &mut tar, + name, + record.mode, + payload, + tar::EntryType::Regular, + ); + } + if let Some((name, kind)) = extra { + add(&mut tar, name, 0o755, payload, kind); + } + let data = tar.into_inner().unwrap().finish().unwrap(); + pin.targets.insert( + target.into(), + Artifact { + sha256: hex::encode(Sha256::digest(&data)), + manifest_sha256: hex::encode(Sha256::digest(bytes)), + size: data.len() as u64, + }, + ); + data +} diff --git a/src/runtime/install.rs b/src/runtime/install.rs new file mode 100644 index 0000000..a15978f --- /dev/null +++ b/src/runtime/install.rs @@ -0,0 +1,152 @@ +use super::{Pin, bundle, installation}; +use anyhow::{Context, Result, bail}; +use sha2::{Digest, Sha256}; +use std::{ + fs::{self, File}, + io::Write, + os::{ + fd::AsRawFd, + unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}, + }, + path::{Path, PathBuf}, + time::Duration, +}; +use tokio::time::{Instant, sleep}; + +pub(super) fn private(path: &Path, directory: bool) -> Result<()> { + let m = fs::symlink_metadata(path)?; + // SAFETY: geteuid has no arguments or memory effects. + if m.uid() != unsafe { libc::geteuid() } + || m.mode() & 0o077 != 0 + || (directory && !m.is_dir()) + || (!directory && !m.is_file()) + { + bail!( + "{} must be private, user-owned, and not a symlink", + path.display() + ); + } + Ok(()) +} +fn directory(path: &Path) -> Result<()> { + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path)?; + private(path, true) +} +pub(super) async fn ensure( + state: &Path, + pin: &Pin, + target: &str, + base: &str, + timeout: Duration, +) -> Result { + pin.validate()?; + let artifact = pin + .targets + .get(target) + .context("No runtime bundle for this host")? + .clone(); + let base = url::Url::parse(base)?; + if (base.scheme() != "https" + && !(cfg!(test) && base.scheme() == "http" && base.host_str() == Some("127.0.0.1"))) + || !base.username().is_empty() + || base.password().is_some() + || base.query().is_some() + || base.fragment().is_some() + || !base.path().ends_with('/') + { + bail!("Runtime downloads require an HTTPS directory URL without credentials"); + } + directory(state)?; + let root = state.join("runtimes"); + directory(&root)?; + let lock_path = root.join("install.lock"); + let lock = File::options() + .read(true) + .write(true) + .create(true) + .truncate(false) + .mode(0o600) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(&lock_path)?; + private(&lock_path, false)?; + let deadline = Instant::now() + timeout; + loop { + // SAFETY: lock owns the live descriptor throughout installation. + if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } == 0 { + break; + } + let error = std::io::Error::last_os_error(); + if error.kind() != std::io::ErrorKind::WouldBlock { + return Err(error.into()); + } + if Instant::now() >= deadline { + bail!("Timed out waiting for another runtime installation"); + } + sleep(Duration::from_millis(50)).await; + } + let installed = installation(state, pin, target); + let parent = installed.parent().unwrap(); + directory(parent)?; + if installed.try_exists()? || fs::symlink_metadata(&installed).is_ok() { + private(&installed, true)?; + bundle::verify(&installed, pin, target).context("Installed runtime is corrupt; its files were preserved because sandboxes may reference them")?; + return Ok(installed.join("bin")); + } + let url = base.join(&format!("{}/{target}.tar.gz", pin.revision))?; + eprintln!( + "Downloading local runtime {} ({target}, {} bytes)…", + &pin.revision[..12], + artifact.size + ); + let client = reqwest::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(timeout) + .build()?; + let mut response = client + .get(url) + .send() + .await + .context("Cannot download the pinned local runtime")?; + if response.status() != reqwest::StatusCode::OK { + bail!("Runtime download returned HTTP {}", response.status()); + } + if response + .content_length() + .is_some_and(|size| size != artifact.size) + { + bail!("Runtime download size differs from its pin"); + } + let mut archive = tempfile::NamedTempFile::new_in(&root)?; + let mut hash = Sha256::new(); + let mut received = 0u64; + while let Some(chunk) = response.chunk().await? { + received += chunk.len() as u64; + if received > artifact.size { + bail!("Runtime download exceeds its pinned size"); + } + hash.update(&chunk); + archive.write_all(&chunk)?; + } + if received != artifact.size || hex::encode(hash.finalize()) != artifact.sha256 { + bail!("Runtime download checksum or size mismatch"); + } + archive.as_file().sync_all()?; + let pin = pin.clone(); + let target = target.to_owned(); + // Keep the lock and temporary files in the blocking task, even if the user + // interrupts the async caller. Incomplete directories are never published. + tokio::task::spawn_blocking(move || -> Result { + let _lock = lock; + let parent = installed.parent().unwrap(); + let staging = tempfile::tempdir_in(parent)?; + let unpacked = staging.path().join("bundle"); + bundle::extract(archive.path(), &unpacked, &pin, &target)?; + fs::rename(&unpacked, &installed)?; + File::open(parent)?.sync_all()?; + Ok(installed.join("bin")) + }) + .await? +} diff --git a/src/runtime/tests.rs b/src/runtime/tests.rs new file mode 100644 index 0000000..530e1ff --- /dev/null +++ b/src/runtime/tests.rs @@ -0,0 +1,314 @@ +use super::*; + +fn pin() -> Pin { + Pin { + format: 1, + revision: "a".repeat(40), + api_version: 1, + runtime_abi: 7, + guest_protocol: 10, + targets: ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] + .into_iter() + .map(|target| { + ( + target.into(), + Artifact { + sha256: "b".repeat(64), + manifest_sha256: "c".repeat(64), + size: 1, + }, + ) + }) + .collect(), + } +} +#[test] +fn pins_require_exact_targets_hashes_and_supported_format() { + let original = pin(); + original.validate().unwrap(); + let mut bad = pin(); + bad.revision = "../other".into(); + assert!(bad.validate().is_err()); + let mut bad = pin(); + bad.targets.remove("aarch64-apple-darwin"); + assert!(bad.validate().is_err()); + let mut bad = pin(); + bad.targets.values_mut().next().unwrap().size = MAX_ARCHIVE + 1; + assert!(bad.validate().is_err()); + let mut bad = pin(); + bad.api_version = 2; + assert!(bad.validate().is_err()); + let mut bad = pin(); + bad.targets.values_mut().next().unwrap().manifest_sha256 = "B".repeat(64); + assert!(bad.validate().is_err()); + configured_pin().unwrap(); +} + +#[cfg(unix)] +mod unix { + use super::*; + use std::{ + fs, + io::{Read, Write}, + net::TcpListener, + os::unix::fs::{PermissionsExt, symlink}, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + thread, + }; + + fn private_temp() -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700)).unwrap(); + dir + } + const TARGET: &str = "aarch64-apple-darwin"; + async fn ensure( + state: &std::path::Path, + pin: &Pin, + target: &str, + base: &str, + ) -> anyhow::Result { + install::ensure(state, pin, target, base, std::time::Duration::from_secs(5)).await + } + #[tokio::test] + async fn downloads_honor_the_request_deadline() { + let dir = private_temp(); + let mut pin = pin(); + let body = bundle::fixture(&mut pin, TARGET, None); + let server = Server::new(body, 200, None, true); + assert!( + install::ensure( + dir.path(), + &pin, + TARGET, + &server.base, + std::time::Duration::from_millis(10) + ) + .await + .is_err() + ); + assert!(!installation(dir.path(), &pin, TARGET).exists()); + } + + struct Server { + base: String, + requests: Arc, + done: Arc, + join: Option>, + } + impl Server { + fn new(body: Vec, status: u16, declared: Option, delay: bool) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let base = format!("http://{}/runtime/goblin/", listener.local_addr().unwrap()); + let requests = Arc::new(AtomicUsize::new(0)); + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let count = requests.clone(); + let stop = done.clone(); + let join = thread::spawn(move || { + while !stop.load(Ordering::SeqCst) { + let (mut socket, _) = match listener.accept() { + Ok(pair) => pair, + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(std::time::Duration::from_millis(5)); + continue; + } + Err(e) => panic!("{e}"), + }; + socket + .set_read_timeout(Some(std::time::Duration::from_secs(5))) + .unwrap(); + count.fetch_add(1, Ordering::SeqCst); + let mut request = Vec::new(); + let mut byte = [0]; + while !request.ends_with(b"\r\n\r\n") { + if socket.read_exact(&mut byte).is_err() { + break; + } + request.push(byte[0]); + } + if !request.ends_with(b"\r\n\r\n") { + continue; + } + let request = String::from_utf8(request).unwrap(); + assert!(request.starts_with("GET /runtime/goblin/")); + assert!(request.contains(&format!("/{TARGET}.tar.gz HTTP/1.1"))); + assert!(!request.to_ascii_lowercase().contains("authorization:")); + if delay { + thread::sleep(std::time::Duration::from_millis(100)); + } + let header = format!( + "HTTP/1.1 {status} Test\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + declared.unwrap_or(body.len()) + ); + let _ = socket.write_all(header.as_bytes()); + let _ = socket.write_all(&body); + } + }); + Self { + base, + requests, + done, + join: Some(join), + } + } + } + impl Drop for Server { + fn drop(&mut self) { + self.done.store(true, Ordering::SeqCst); + self.join.take().unwrap().join().unwrap(); + } + } + + #[tokio::test] + async fn concurrent_installs_download_once_and_cached_reuse_is_offline() { + let dir = private_temp(); + let mut pin = pin(); + let body = bundle::fixture(&mut pin, TARGET, None); + let server = Server::new(body, 200, None, true); + let (first, second) = tokio::join!( + ensure(dir.path(), &pin, TARGET, &server.base), + ensure(dir.path(), &pin, TARGET, &server.base) + ); + let path = first.unwrap(); + assert_eq!(second.unwrap(), path); + assert_eq!(server.requests.load(Ordering::SeqCst), 1); + assert_eq!( + fs::metadata(path.join("goblind")) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o755 + ); + drop(server); + assert_eq!( + ensure( + dir.path(), + &pin, + TARGET, + "http://127.0.0.1:1/runtime/goblin/" + ) + .await + .unwrap(), + path + ); + fs::write(path.join("goblind"), b"corrupt").unwrap(); + let error = ensure( + dir.path(), + &pin, + TARGET, + "http://127.0.0.1:1/runtime/goblin/", + ) + .await + .unwrap_err(); + assert!(error.to_string().contains("corrupt")); + assert_eq!(fs::read(path.join("goblind")).unwrap(), b"corrupt"); + } + + #[tokio::test] + async fn corrupt_truncated_wrong_size_or_redirected_downloads_never_install() { + for case in 0..4 { + let dir = private_temp(); + let mut pin = pin(); + let mut body = bundle::fixture(&mut pin, TARGET, None); + let length = body.len(); + let mut declared = None; + let mut status = 200; + match case { + 0 => body[10] ^= 1, + 1 => { + body.truncate(length / 2); + declared = Some(length); + } + 2 => declared = Some(length + 1), + _ => status = 302, + } + let server = Server::new(body, status, declared, false); + assert!( + ensure(dir.path(), &pin, TARGET, &server.base) + .await + .is_err() + ); + assert!(!installation(dir.path(), &pin, TARGET).exists()); + assert_eq!( + fs::read_dir(dir.path().join("runtimes")).unwrap().count(), + 2 + ); // lock and revision; no downloads remain + } + } + + #[tokio::test] + async fn unexpected_duplicate_and_link_entries_fail_without_publishing() { + for extra in [ + ("unexpected", tar::EntryType::Regular), + ("bin/goblind", tar::EntryType::Regular), + ("bin/goblind", tar::EntryType::Symlink), + ("manifest.json", tar::EntryType::Regular), + ] { + let dir = private_temp(); + let mut pin = pin(); + let body = bundle::fixture(&mut pin, TARGET, Some(extra)); + let server = Server::new(body, 200, None, false); + assert!( + ensure(dir.path(), &pin, TARGET, &server.base) + .await + .is_err() + ); + assert!(!installation(dir.path(), &pin, TARGET).exists()); + assert_eq!( + fs::read_dir(dir.path().join("runtimes").join(&pin.revision)) + .unwrap() + .count(), + 0 + ); + } + } + + #[tokio::test] + async fn manifest_pin_mismatch_and_symlink_caches_are_rejected() { + let dir = private_temp(); + let mut pin = pin(); + let body = bundle::fixture(&mut pin, TARGET, None); + pin.targets.get_mut(TARGET).unwrap().manifest_sha256 = "d".repeat(64); + let server = Server::new(body, 200, None, false); + assert!( + ensure(dir.path(), &pin, TARGET, &server.base) + .await + .is_err() + ); + let outside = tempfile::tempdir().unwrap(); + symlink(outside.path(), installation(dir.path(), &pin, TARGET)).unwrap(); + assert!( + ensure(dir.path(), &pin, TARGET, &server.base) + .await + .is_err() + ); + assert_eq!(server.requests.load(Ordering::SeqCst), 1); + assert_eq!(fs::read_dir(outside.path()).unwrap().count(), 0); + } + + #[tokio::test] + async fn separate_releases_preserve_old_executables() { + let dir = private_temp(); + let mut pin = pin(); + let body = bundle::fixture(&mut pin, TARGET, None); + let server = Server::new(body, 200, None, false); + let first = ensure(dir.path(), &pin, TARGET, &server.base) + .await + .unwrap(); + let bytes = fs::read(first.join("goblin-worker")).unwrap(); + pin.revision = "e".repeat(40); + let body = bundle::fixture(&mut pin, TARGET, None); + let second_server = Server::new(body, 200, None, false); + let second = ensure(dir.path(), &pin, TARGET, &second_server.base) + .await + .unwrap(); + assert_ne!(second, first); + assert!(second.join("goblind").is_file()); + assert_eq!(fs::read(first.join("goblin-worker")).unwrap(), bytes); + } +} diff --git a/tests/backend/mod.rs b/tests/backend/mod.rs index 950241d..f976774 100644 --- a/tests/backend/mod.rs +++ b/tests/backend/mod.rs @@ -179,3 +179,40 @@ fn invalid_local_environments_fail_before_starting_a_manager_or_creating_state() } } } + +#[test] +fn runtime_utilities_do_not_load_cloud_profiles_or_start_a_manager() { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("uncreated"); + std::fs::write(dir.path().join("config.json"), "invalid cloud config").unwrap(); + for name in ["goblind", "goblin-worker"] { + std::fs::write(dir.path().join(name), "not an executable").unwrap(); + } + for operation in ["status", "install"] { + let output = command(dir.path(), "invalid-cloud-origin") + .args(["runtime", operation, "--json", "--local-state-dir"]) + .arg(&state) + .arg("--runtime-dir") + .arg(dir.path()) + .output() + .unwrap(); + if cfg!(any( + all(target_os = "macos", target_arch = "aarch64"), + all(target_os = "linux", target_arch = "x86_64") + )) { + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap(); + assert!(result["path"].is_string()); + } else { + assert!( + String::from_utf8_lossy(&output.stderr) + .contains("Local sandboxes currently require") + ); + } + assert!(!state.exists()); + } +} From 7f5040a5fbd43ded93ef6880be5ee20b36c8f5a6 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 13:54:59 -0800 Subject: [PATCH 2/4] Close runtime pin files before replacing them on Windows --- scripts/pin_runtime.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/scripts/pin_runtime.py b/scripts/pin_runtime.py index db0232d..1fd2c56 100644 --- a/scripts/pin_runtime.py +++ b/scripts/pin_runtime.py @@ -66,14 +66,15 @@ def get(name): if size != record["size"] or h.hexdigest() != record["sha256"]: raise ValueError("Published runtime archive checksum mismatch") # Update only after both exact artifacts are available and verified. - with tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) as file: - temporary = Path(file.name) - try: + file = tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) + temporary = Path(file.name) + try: + with file: file.write((json.dumps(pin, sort_keys=True, indent=2) + "\n").encode()) - file.flush() - temporary.replace(destination) - finally: - temporary.unlink(missing_ok=True) + # Close before replacement so this also works on Windows. + temporary.replace(destination) + finally: + temporary.unlink(missing_ok=True) return pin From 691536b9f72f4cacd4ed55208ac486df7bc72d35 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 14:13:11 -0800 Subject: [PATCH 3/4] Pin runtimes with xtask and defer local compatibility checks --- .cargo/config.toml | 2 + .github/workflows/ci.yml | 12 +- Cargo.lock | 16 +++ Cargo.toml | 5 + docs/cli-reference.md | 12 +- docs/publishing.md | 4 +- scripts/pin_runtime.py | 94 ------------- scripts/pin_runtime_test.py | 50 ------- src/local_runtime.rs | 99 +------------- src/runtime.rs | 55 ++------ src/runtime/bundle.rs | 8 +- src/runtime/pin.rs | 45 +++++++ src/runtime/tests.rs | 8 +- xtask/Cargo.toml | 15 +++ xtask/src/main.rs | 256 ++++++++++++++++++++++++++++++++++++ 15 files changed, 371 insertions(+), 310 deletions(-) create mode 100644 .cargo/config.toml delete mode 100644 scripts/pin_runtime.py delete mode 100644 scripts/pin_runtime_test.py create mode 100644 src/runtime/pin.rs create mode 100644 xtask/Cargo.toml create mode 100644 xtask/src/main.rs diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..856707a --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,2 @@ +[alias] +xtask = "run --locked --package xtask --" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b71fa70..ab5df50 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,10 +53,10 @@ jobs: echo "CARGO_TARGET_${target_env}_LINKER=musl-gcc" >> "$GITHUB_ENV" echo "CC_${TARGET//-/_}=musl-gcc" >> "$GITHUB_ENV" - run: python -m unittest discover -s scripts -p '*_test.py' - - run: python scripts/pin_runtime.py --check + - run: cargo xtask pin-runtime --check - run: cargo fmt --all -- --check - - run: cargo clippy --locked --all-targets --target ${{ matrix.target }} -- -D warnings - - run: cargo test --locked --target ${{ matrix.target }} + - run: cargo clippy --workspace --locked --all-targets --target ${{ matrix.target }} -- -D warnings + - run: cargo test --workspace --locked --target ${{ matrix.target }} - run: cargo build --locked --release --target ${{ matrix.target }} - run: python scripts/package_release.py ${{ matrix.target }} - uses: actions/upload-artifact@v4 @@ -79,8 +79,9 @@ jobs: id-token: write steps: - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable - name: Require a published runtime pin before releasing the CLI - run: python3 scripts/pin_runtime.py --check --require + run: cargo xtask pin-runtime --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* @@ -112,8 +113,9 @@ jobs: id-token: write steps: - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable - name: Require a published runtime pin before releasing the CLI - run: python3 scripts/pin_runtime.py --check --require + run: cargo xtask pin-runtime --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* diff --git a/Cargo.lock b/Cargo.lock index bffe9e0..3badd46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -429,6 +429,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1116,6 +1117,7 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "futures-channel", "futures-core", "futures-util", "http", @@ -2030,6 +2032,20 @@ dependencies = [ "rustix", ] +[[package]] +name = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "hex", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", +] + [[package]] name = "yoke" version = "0.8.4" diff --git a/Cargo.toml b/Cargo.toml index ecfde17..2197053 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,8 @@ +[workspace] +members = [".", "xtask"] +default-members = ["."] +resolver = "3" + [package] name = "platform-cli" version = "0.1.0" diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 24b1115..edf18ef 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -228,7 +228,7 @@ Shells have a maximum execution timeout of 24 hours. `adapt runtime install` downloads and verifies this CLI build's pinned Goblin release without starting a manager. The first supported local operation does the -same automatically when no compatible manager is already running. `adapt runtime +same automatically when no manager is already running. `adapt runtime status` is read-only: it shows the pin, path, and whether the expected binaries are present; installation reuse also verifies their contents. @@ -239,12 +239,10 @@ against hashes embedded in the CLI. Installed files live under serialized, atomic installation. Cached runtimes work offline; images may still need to be pulled. Linux releases require glibc 2.36 or newer and access to KVM. -Installing a new release never replaces old files or restarts the manager. A -compatible running manager is reused. An incompatible or unknown runtime ABI -requires using the original runtime to migrate/recreate sandboxes, or selecting -a fresh `--local-state-dir`. Old release directories remain because VM records -can reference them. `--runtime-dir` / `ADAPT_LOCAL_RUNTIME` explicitly select a -manual development bundle and bypass managed downloads and pin compatibility. +Installing a new release never replaces old files or restarts the manager. +A running manager is reused without runtime ABI or persisted-state compatibility +checks. Old release directories remain because VM records can reference them. +`--runtime-dir` / `ADAPT_LOCAL_RUNTIME` explicitly select a manual development bundle. ```sh adapt runtime install # optional prefetch diff --git a/docs/publishing.md b/docs/publishing.md index cf33d51..c476e62 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -117,11 +117,11 @@ after this workflow reaches `main` and its checks pass. ## Pinning the local runtime `runtime-lock.json` is compiled into every CLI executable. It contains one exact -Goblin revision, its compatibility metadata, and archive/manifest hashes for both +Goblin revision and archive/manifest hashes for both supported runtime targets. There is no runtime `latest` lookup. Update it with: ```sh -python3 scripts/pin_runtime.py GOBLIN_REVISION +cargo xtask pin-runtime GOBLIN_REVISION ``` The command reads the public immutable lock and verifies both archives before diff --git a/scripts/pin_runtime.py b/scripts/pin_runtime.py deleted file mode 100644 index 1fd2c56..0000000 --- a/scripts/pin_runtime.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Verify an immutable published Goblin release and pin it in the CLI source.""" -import argparse -import hashlib -import json -from pathlib import Path -import re -import tempfile -from urllib.parse import urlsplit -from urllib.request import HTTPRedirectHandler, Request, build_opener - -TARGETS = {"aarch64-apple-darwin", "x86_64-unknown-linux-gnu"} -MAX_ARCHIVE = 512 * 1024 * 1024 -DEFAULT_BASE = "https://platform.adapt.com/runtime/goblin/" - - -def validate(pin, required=True): - if pin is None: - if required: - raise ValueError("Pin a published runtime before releasing this CLI: python scripts/pin_runtime.py REVISION") - return - if (not isinstance(pin, dict) or set(pin) != {"format", "revision", "api_version", "runtime_abi", "guest_protocol", "targets"} - or type(pin["format"]) is not int or pin["format"] != 1 - or type(pin["api_version"]) is not int or pin["api_version"] != 1 - or not re.fullmatch(r"[a-f0-9]{40}", pin["revision"]) - or any(type(pin[k]) is not int or not 0 < pin[k] <= 0xffffffff for k in ("runtime_abi", "guest_protocol")) - or set(pin["targets"]) != TARGETS): - raise ValueError("Invalid runtime lock identity or target set") - for record in pin["targets"].values(): - if (set(record) != {"sha256", "manifest_sha256", "size"} - or any(not re.fullmatch(r"[a-f0-9]{64}", record[k]) for k in ("sha256", "manifest_sha256")) - or type(record["size"]) is not int or not 0 < record["size"] <= MAX_ARCHIVE): - raise ValueError("Invalid runtime artifact pin") - - -class NoRedirects(HTTPRedirectHandler): - def redirect_request(self, req, fp, code, msg, headers, newurl): - return None - - -def pin_release(revision, destination, base=DEFAULT_BASE, opener=None): - if not re.fullmatch(r"[a-f0-9]{40}", revision): - raise ValueError("Expected a full Goblin commit SHA") - origin = urlsplit(base) - if (origin.scheme != "https" or not origin.netloc or origin.username or origin.password - or origin.query or origin.fragment or not origin.path.endswith("/")): - raise ValueError("Expected an HTTPS directory URL without credentials") - opener = opener or build_opener(NoRedirects()) - def get(name): - return opener.open(Request(f"{base}{revision}/{name}", headers={"Accept-Encoding": "identity"}), timeout=300) - with get("runtime-lock.json") as response: - encoded = response.read(65537) - if len(encoded) > 65536: - raise ValueError("Oversized runtime lock") - pin = json.loads(encoded) - validate(pin) - if pin["revision"] != revision: - raise ValueError("Published runtime revision mismatch") - for target, record in pin["targets"].items(): - h, size = hashlib.sha256(), 0 - with get(f"{target}.tar.gz") as response: - while chunk := response.read(65536): - size += len(chunk) - if size > record["size"]: - raise ValueError("Runtime download exceeds pinned size") - h.update(chunk) - if size != record["size"] or h.hexdigest() != record["sha256"]: - raise ValueError("Published runtime archive checksum mismatch") - # Update only after both exact artifacts are available and verified. - file = tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) - temporary = Path(file.name) - try: - with file: - file.write((json.dumps(pin, sort_keys=True, indent=2) + "\n").encode()) - # Close before replacement so this also works on Windows. - temporary.replace(destination) - finally: - temporary.unlink(missing_ok=True) - return pin - - -if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("revision", nargs="?") - parser.add_argument("--check", action="store_true") - parser.add_argument("--require", action="store_true") - parser.add_argument("--lock", type=Path, default=Path("runtime-lock.json")) - parser.add_argument("--base-url", default=DEFAULT_BASE) - args = parser.parse_args() - if args.check: - validate(json.loads(args.lock.read_text()), required=args.require) - elif args.revision: - pin_release(args.revision, args.lock, args.base_url) - else: - parser.error("Supply a revision or --check") diff --git a/scripts/pin_runtime_test.py b/scripts/pin_runtime_test.py deleted file mode 100644 index ec389e9..0000000 --- a/scripts/pin_runtime_test.py +++ /dev/null @@ -1,50 +0,0 @@ -import hashlib -import io -import json -from pathlib import Path -import tempfile -import unittest -from pin_runtime import TARGETS, pin_release, validate - -REVISION = "a" * 40 -BODY = b"test archive bytes" - -def pin(): - return dict(format=1, revision=REVISION, api_version=1, runtime_abi=7, guest_protocol=10, - targets={target: dict(size=len(BODY), sha256=hashlib.sha256(BODY).hexdigest(), manifest_sha256="b" * 64) for target in TARGETS}) - -class Opener: - def __init__(self, contents): self.contents = list(contents) - def open(self, request, **_): - if not request.full_url.startswith("https://platform.adapt.com/runtime/goblin/" + REVISION + "/"): - raise AssertionError(request.full_url) - return io.BytesIO(self.contents.pop(0)) - -class PinRuntimeTest(unittest.TestCase): - def test_release_requires_a_real_pin(self): - validate(None, required=False) - with self.assertRaises(ValueError): validate(None) - validate(pin()) - bad = pin(); bad["targets"].pop(next(iter(TARGETS))) - with self.assertRaises(ValueError): validate(bad) - - def test_both_targets_verify_before_replacing_existing_pin(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "runtime-lock.json" - path.write_text("null\n") - for bodies in [(BODY, b"bad"), (b"bad", BODY)]: - with self.assertRaises(ValueError): pin_release(REVISION, path, opener=Opener([json.dumps(pin()).encode(), *bodies])) - self.assertEqual(path.read_text(), "null\n") - self.assertEqual(pin_release(REVISION, path, opener=Opener([json.dumps(pin()).encode(), BODY, BODY])), pin()) - self.assertEqual(json.loads(path.read_text()), pin()) - - def test_rejects_untrusted_urls_and_mismatched_identity(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "pin.json" - for base in ["http://localhost/", "https://user:password@example.com/", "https://example.com/?x=1"]: - with self.assertRaises(ValueError): pin_release(REVISION, path, base=base) - wrong = pin(); wrong["revision"] = "c" * 40 - with self.assertRaises(ValueError): pin_release(REVISION, path, opener=Opener([json.dumps(wrong).encode()])) - self.assertFalse(path.exists()) - -if __name__ == "__main__": unittest.main() diff --git a/src/local_runtime.rs b/src/local_runtime.rs index 2531df6..d8e376d 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -48,10 +48,6 @@ mod unix { socket_path: std::path::PathBuf, instance_id: Uuid, runtime_version: String, - #[serde(default)] - release_revision: Option, - #[serde(default)] - runtime_abi: Option, } fn private_metadata(path: &Path, directory: bool) -> Result<()> { @@ -98,12 +94,7 @@ mod unix { Ok(bytes) } - async fn discover( - state: &Path, - token: &str, - timeout: Duration, - pin: Option<&crate::runtime::Pin>, - ) -> Result> { + async fn discover(state: &Path, token: &str, timeout: Duration) -> Result> { let path = state.join("ready.json"); let bytes = match read(&path) { Ok(bytes) => bytes, @@ -168,9 +159,6 @@ mod unix { "Local runtime is incompatible or has no embedded image firmware; use a compatible Goblin bundle" ); } - if let Some(pin) = pin { - compatible_identity(&ready, &spec, pin.runtime_abi)?; - } Ok(Some(Goblin::new( ready.socket_path, token, @@ -179,36 +167,6 @@ mod unix { )?)) } - fn compatible_identity(ready: &Ready, spec: &serde_json::Value, abi: u32) -> Result<()> { - if ready.runtime_abi != Some(abi) - || spec["runtime_abi"].as_u64() != Some(u64::from(abi)) - || !ready - .release_revision - .as_ref() - .is_some_and(|r| crate::runtime::hex(r, 40)) - || spec["release_revision"].as_str() != ready.release_revision.as_deref() - { - bail!( - "The running local runtime is incompatible with this CLI's pin. It was left running; use its original CLI/runtime to stop and migrate or recreate sandboxes before changing runtimes" - ); - } - Ok(()) - } - - fn compatible_state(state: &Path, abi: u32) -> Result<()> { - if state.join("ready.json").try_exists()? { - let previous: Ready = serde_json::from_slice(&read(&state.join("ready.json"))?)?; - if previous.runtime_abi == Some(abi) { - return Ok(()); - } - } else if !state.join("vms").try_exists()? && !state.join("sandboxes").try_exists()? { - return Ok(()); - } - bail!( - "Existing local state belongs to a different or unknown runtime ABI; use the original runtime to migrate or recreate its sandboxes, or choose a fresh --local-state-dir" - ) - } - pub async fn connect( state: &Path, runtime: Option<&Path>, @@ -253,18 +211,9 @@ mod unix { if token.len() < 32 || token.len() > 4096 || token.chars().any(char::is_whitespace) { bail!("Invalid local runtime token file"); } - let pin = if runtime.is_none() { - crate::runtime::configured_pin()? - } else { - None - }; - if let Some(local) = discover(&state, token, timeout, pin.as_ref()).await? { + if let Some(local) = discover(&state, token, timeout).await? { return Ok(local); } - if let Some(pin) = &pin { - // Stopped workers and persisted VM records can still reference old binaries. - compatible_state(&state, pin.runtime_abi)?; - } let runtime = crate::runtime::resolve(&state, runtime, timeout).await?; let deadline = Instant::now() + Duration::from_secs(30); let manager = runtime @@ -315,7 +264,7 @@ mod unix { eprintln!("Starting local runtime; log: {}", log_path.display()); let mut child = command.spawn().context("Cannot start goblind")?; loop { - if let Some(local) = discover(&state, token, timeout, pin.as_ref()).await? { + if let Some(local) = discover(&state, token, timeout).await? { return Ok(local); } if let Some(status) = child.try_wait()? { @@ -335,46 +284,4 @@ mod unix { sleep(Duration::from_millis(50)).await; } } - #[cfg(test)] - mod tests { - use super::*; - use serde_json::json; - use std::os::unix::fs::PermissionsExt; - - fn ready() -> serde_json::Value { - json!({"version":1,"socket_path":"/unused/goblind.sock","instance_id":Uuid::new_v4(), - "runtime_version":"0.1.0","runtime_abi":7,"release_revision":"a".repeat(40)}) - } - #[test] - fn runtime_abi_and_exact_discovery_identity_are_required_for_managed_reuse() { - let metadata = ready(); - let ready: Ready = serde_json::from_value(metadata.clone()).unwrap(); - compatible_identity(&ready, &metadata, 7).unwrap(); - assert!(compatible_identity(&ready, &metadata, 8).is_err()); - let mut other = metadata.clone(); - other["release_revision"] = json!("b".repeat(40)); - assert!(compatible_identity(&ready, &other, 7).is_err()); - let mut old = metadata.clone(); - old.as_object_mut().unwrap().remove("runtime_abi"); - assert!( - compatible_identity(&serde_json::from_value(old.clone()).unwrap(), &old, 7) - .is_err() - ); - } - #[test] - fn unknown_or_incompatible_persisted_state_is_preserved() { - let dir = tempfile::tempdir().unwrap(); - compatible_state(dir.path(), 7).unwrap(); - fs::create_dir(dir.path().join("vms")).unwrap(); - assert!(compatible_state(dir.path(), 7).is_err()); - let path = dir.path().join("ready.json"); - let bytes = serde_json::to_vec(&ready()).unwrap(); - fs::write(&path, &bytes).unwrap(); - fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); - compatible_state(dir.path(), 7).unwrap(); - assert!(compatible_state(dir.path(), 8).is_err()); - assert_eq!(fs::read(path).unwrap(), bytes); - assert!(dir.path().join("vms").is_dir()); - } - } } diff --git a/src/runtime.rs b/src/runtime.rs index 829b473..cf88762 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -4,10 +4,8 @@ use crate::{ config, output, }; use anyhow::{Context, Result, bail}; -use serde::{Deserialize, Serialize}; use serde_json::json; use std::{ - collections::BTreeMap, path::{Path, PathBuf}, time::Duration, }; @@ -19,54 +17,17 @@ mod install; #[cfg(test)] mod tests; -pub const MAX_ARCHIVE: u64 = 512 * 1024 * 1024; +mod pin; +#[cfg(any(unix, test))] +pub use pin::Artifact; +#[cfg(test)] +pub use pin::MAX_ARCHIVE; +pub use pin::Pin; +#[cfg(unix)] +pub use pin::hex; #[cfg(unix)] const DOWNLOAD_BASE: &str = "https://platform.adapt.com/runtime/goblin/"; -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct Pin { - pub format: u32, - pub revision: String, - pub api_version: u32, - pub runtime_abi: u32, - pub guest_protocol: u32, - pub targets: BTreeMap, -} -#[derive(Clone, Debug, Deserialize, Serialize)] -#[serde(deny_unknown_fields)] -pub struct Artifact { - pub sha256: String, - pub manifest_sha256: String, - pub size: u64, -} -pub fn hex(value: &str, length: usize) -> bool { - value.len() == length - && value - .bytes() - .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) -} -impl Pin { - pub fn validate(&self) -> Result<()> { - if self.format != 1 - || self.api_version != 1 - || !hex(&self.revision, 40) - || self.runtime_abi == 0 - || self.guest_protocol == 0 - || self.targets.keys().map(String::as_str).collect::>() - != ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] - || self.targets.values().any(|a| { - !hex(&a.sha256, 64) - || !hex(&a.manifest_sha256, 64) - || a.size == 0 - || a.size > MAX_ARCHIVE - }) - { - bail!("Invalid or unsupported local runtime pin"); - } - Ok(()) - } -} pub fn configured_pin() -> Result> { let pin: Option = serde_json::from_str(include_str!("../runtime-lock.json"))?; if let Some(pin) = &pin { diff --git a/src/runtime/bundle.rs b/src/runtime/bundle.rs index 82af9ac..31d774b 100644 --- a/src/runtime/bundle.rs +++ b/src/runtime/bundle.rs @@ -20,6 +20,7 @@ struct Manifest { revision: String, dirty: bool, target: String, + // Existing Goblin bundle metadata; local installation does not gate on it. runtime_abi: u32, guest_protocol: u32, management_protocol: u32, @@ -72,9 +73,6 @@ fn manifest(bytes: &[u8], pin: &Pin, target: &str, artifact: &Artifact) -> Resul || m.revision != pin.revision || m.release != pin.revision || m.target != target - || m.runtime_abi != pin.runtime_abi - || m.guest_protocol != pin.guest_protocol - || m.management_protocol != 1 || m.files.keys().cloned().collect::>() != names(target) { bail!("Local runtime bundle identity or contents do not match the pinned release"); @@ -248,8 +246,8 @@ pub(super) fn fixture( revision: pin.revision.clone(), dirty: false, target: target.into(), - runtime_abi: pin.runtime_abi, - guest_protocol: pin.guest_protocol, + runtime_abi: 7, + guest_protocol: 10, management_protocol: 1, files, }; diff --git a/src/runtime/pin.rs b/src/runtime/pin.rs new file mode 100644 index 0000000..7c4abc5 --- /dev/null +++ b/src/runtime/pin.rs @@ -0,0 +1,45 @@ +//! Shared runtime lock contract for the CLI and its release tooling. +use anyhow::{Result, bail}; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +pub const MAX_ARCHIVE: u64 = 512 * 1024 * 1024; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Pin { + pub format: u32, + pub revision: String, + pub targets: BTreeMap, +} +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Artifact { + pub sha256: String, + pub manifest_sha256: String, + pub size: u64, +} +pub fn hex(value: &str, length: usize) -> bool { + value.len() == length + && value + .bytes() + .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) +} +impl Pin { + pub fn validate(&self) -> Result<()> { + if self.format != 1 + || !hex(&self.revision, 40) + || self.targets.keys().map(String::as_str).collect::>() + != ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] + || self.targets.values().any(|a| { + !hex(&a.sha256, 64) + || !hex(&a.manifest_sha256, 64) + || a.size == 0 + || a.size > MAX_ARCHIVE + }) + { + bail!("Invalid or unsupported local runtime pin"); + } + Ok(()) + } +} diff --git a/src/runtime/tests.rs b/src/runtime/tests.rs index 530e1ff..e7ec20d 100644 --- a/src/runtime/tests.rs +++ b/src/runtime/tests.rs @@ -4,9 +4,6 @@ fn pin() -> Pin { Pin { format: 1, revision: "a".repeat(40), - api_version: 1, - runtime_abi: 7, - guest_protocol: 10, targets: ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] .into_iter() .map(|target| { @@ -36,7 +33,7 @@ fn pins_require_exact_targets_hashes_and_supported_format() { bad.targets.values_mut().next().unwrap().size = MAX_ARCHIVE + 1; assert!(bad.validate().is_err()); let mut bad = pin(); - bad.api_version = 2; + bad.format = 2; assert!(bad.validate().is_err()); let mut bad = pin(); bad.targets.values_mut().next().unwrap().manifest_sha256 = "B".repeat(64); @@ -118,6 +115,9 @@ mod unix { } Err(e) => panic!("{e}"), }; + // macOS inherits O_NONBLOCK from the listener. These test + // connections use blocking reads with a deadline on every OS. + socket.set_nonblocking(false).unwrap(); socket .set_read_timeout(Some(std::time::Duration::from_secs(5))) .unwrap(); diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml new file mode 100644 index 0000000..cfc2969 --- /dev/null +++ b/xtask/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "xtask" +version = "0.1.0" +edition = "2024" +publish = false + +[dependencies] +anyhow = "1" +clap = { version = "4.6", features = ["derive"] } +hex = "0.4" +reqwest = { version = "0.12", default-features = false, features = ["blocking", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.11" +tempfile = "3.27" diff --git a/xtask/src/main.rs b/xtask/src/main.rs new file mode 100644 index 0000000..57fc38e --- /dev/null +++ b/xtask/src/main.rs @@ -0,0 +1,256 @@ +//! Repository release tasks, sharing the runtime pin contract with adapt. +use anyhow::{Context, Result, bail}; +use clap::{Parser, Subcommand}; +use reqwest::{Url, blocking::Client}; +use sha2::{Digest, Sha256}; +use std::{ + fs, + io::{Read, Write}, + path::{Path, PathBuf}, + time::Duration, +}; +#[path = "../../src/runtime/pin.rs"] +mod pin; +use pin::Pin; + +#[derive(Parser)] +struct Args { + #[command(subcommand)] + task: Task, +} +#[derive(Subcommand)] +enum Task { + /// Verify both published Goblin archives, then atomically update the CLI pin. + PinRuntime { + #[arg(required_unless_present = "check", conflicts_with = "check")] + revision: Option, + /// Validate the checked-in lock without downloading. + #[arg(long)] + check: bool, + /// Reject an empty development pin (required for CLI publication). + #[arg(long, requires = "check")] + require: bool, + #[arg(long, default_value = "runtime-lock.json")] + lock: PathBuf, + #[arg(long, default_value = "https://platform.adapt.com/runtime/goblin/")] + base_url: String, + }, +} +fn parse_pin(encoded: &[u8], required: bool) -> Result> { + let pin: Option = serde_json::from_slice(encoded)?; + if let Some(pin) = &pin { + pin.validate()?; + } else if required { + bail!( + "Pin a published runtime before releasing this CLI: cargo xtask pin-runtime REVISION" + ); + } + Ok(pin) +} +fn base_url(base: &str) -> Result { + let base = Url::parse(base)?; + if base.scheme() != "https" + || base.host_str().is_none() + || !base.username().is_empty() + || base.password().is_some() + || base.query().is_some() + || base.fragment().is_some() + || !base.path().ends_with('/') + { + bail!("Expected an HTTPS directory URL without credentials"); + } + Ok(base) +} +fn update_pin( + revision: &str, + destination: &Path, + mut get: impl FnMut(&str) -> Result>, +) -> Result<()> { + if !pin::hex(revision, 40) { + bail!("Expected a full Goblin commit SHA"); + } + let mut encoded = Vec::new(); + get(&format!("{revision}/runtime-lock.json"))? + .take(65537) + .read_to_end(&mut encoded)?; + if encoded.len() > 65536 { + bail!("Oversized runtime lock"); + } + let pin = parse_pin(&encoded, true)?.context("Missing runtime pin")?; + if pin.revision != revision { + bail!("Published runtime revision mismatch"); + } + for (target, artifact) in &pin.targets { + let mut source = get(&format!("{revision}/{target}.tar.gz"))?; + let mut hash = Sha256::new(); + let mut size = 0u64; + let mut buffer = [0; 65536]; + loop { + let read = source.read(&mut buffer)?; + if read == 0 { + break; + } + size += read as u64; + if size > artifact.size { + bail!("Runtime download exceeds pinned size"); + } + hash.update(&buffer[..read]); + } + if size != artifact.size || hex::encode(hash.finalize()) != artifact.sha256 { + bail!("Published runtime archive checksum or size mismatch"); + } + } + // Close before atomic replacement, including on Windows. An interrupted or + // failed download leaves the old pin untouched; TempPath cleans up failures. + let parent = destination + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + let mut file = tempfile::NamedTempFile::new_in(parent)?; + serde_json::to_writer_pretty(&mut file, &pin)?; + file.write_all(b"\n")?; + file.as_file().sync_all()?; + file.into_temp_path().persist(destination)?; + Ok(()) +} +fn main() -> Result<()> { + match Args::parse().task { + Task::PinRuntime { + revision, + check, + require, + lock, + base_url: base, + } => { + if check { + parse_pin(&fs::read(lock)?, require)?; + } else { + let base = base_url(&base)?; + let client = Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(300)) + .build()?; + update_pin( + revision + .as_deref() + .context("Supply a revision or --check")?, + &lock, + |name| { + let response = client + .get(base.join(name)?) + .header("Accept-Encoding", "identity") + .send()?; + if response.status() != reqwest::StatusCode::OK { + bail!("Runtime download returned HTTP {}", response.status()); + } + Ok(Box::new(response)) + }, + )?; + println!("Pinned Goblin runtime in {}", lock.display()); + } + } + } + Ok(()) +} +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + const REVISION: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const BODY: &[u8] = b"fixture archive bytes"; + fn encoded() -> Vec { + let targets = ["aarch64-apple-darwin", "x86_64-unknown-linux-gnu"] + .into_iter() + .map(|t| { + ( + t, + serde_json::json!({ + "size": BODY.len(), "sha256": hex::encode(Sha256::digest(BODY)), + "manifest_sha256": "b".repeat(64) + }), + ) + }) + .collect::>(); + serde_json::to_vec(&serde_json::json!({"format":1,"revision":REVISION, + "targets":targets})) + .unwrap() + } + fn fetch(bodies: Vec>) -> impl FnMut(&str) -> Result> { + let mut bodies = bodies.into_iter(); + move |name| { + assert!(name.starts_with(&format!("{REVISION}/"))); + Ok(Box::new(Cursor::new( + bodies.next().expect("unexpected download"), + ))) + } + } + #[test] + fn release_requires_a_valid_pin() { + assert!(parse_pin(b"null", false).unwrap().is_none()); + assert!(parse_pin(b"null", true).is_err()); + assert!(parse_pin(&encoded(), true).unwrap().is_some()); + let mut pin: serde_json::Value = serde_json::from_slice(&encoded()).unwrap(); + pin["targets"] + .as_object_mut() + .unwrap() + .remove("aarch64-apple-darwin"); + assert!(parse_pin(&serde_json::to_vec(&pin).unwrap(), true).is_err()); + } + #[test] + fn both_targets_verify_before_replacing_existing_pin() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("runtime-lock.json"); + fs::write(&path, b"null\n").unwrap(); + for bodies in [ + vec![encoded(), BODY.to_vec(), b"bad".to_vec()], + vec![encoded(), b"bad".to_vec(), BODY.to_vec()], + ] { + assert!(update_pin(REVISION, &path, fetch(bodies)).is_err()); + assert_eq!(fs::read(&path).unwrap(), b"null\n"); + } + update_pin( + REVISION, + &path, + fetch(vec![encoded(), BODY.to_vec(), BODY.to_vec()]), + ) + .unwrap(); + assert_eq!( + parse_pin(&fs::read(path).unwrap(), true) + .unwrap() + .unwrap() + .revision, + REVISION + ); + } + #[test] + fn bounds_and_identity_errors_preserve_the_old_pin() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("runtime-lock.json"); + fs::write(&path, b"null\n").unwrap(); + let mut wrong: serde_json::Value = serde_json::from_slice(&encoded()).unwrap(); + wrong["revision"] = "b".repeat(40).into(); + for lock in [vec![b' '; 65537], serde_json::to_vec(&wrong).unwrap()] { + assert!(update_pin(REVISION, &path, fetch(vec![lock])).is_err()); + } + assert!( + update_pin("../other", &path, |_| panic!( + "invalid revision must not download" + )) + .is_err() + ); + assert_eq!(fs::read(path).unwrap(), b"null\n"); + } + #[test] + fn only_https_directory_origins_are_allowed() { + for base in [ + "http://localhost/", + "https://user:password@example.com/", + "https://example.com/?x=1", + "https://example.com/#x", + "https://example.com/file", + ] { + assert!(base_url(base).is_err()); + } + assert!(base_url("https://platform.adapt.com/runtime/goblin/").is_ok()); + } +} From e25d8e0b634cbe4d0a1fafaca859e0f53f4e4a12 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 23 Nov 2026 16:17:27 -0800 Subject: [PATCH 4/4] Pin the first published Goblin runtime --- docs/cli-reference.md | 5 +++-- docs/publishing.md | 12 ++++++------ runtime-lock.json | 17 ++++++++++++++++- 3 files changed, 25 insertions(+), 9 deletions(-) diff --git a/docs/cli-reference.md b/docs/cli-reference.md index edf18ef..65c6687 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -292,8 +292,9 @@ State, image cache, the local token, discovery metadata, sandbox environment files, and `goblind.log` live in `ADAPT_CONFIG_DIR/local` (using the usual config directory default). Override this with `--local-state-dir` or `ADAPT_LOCAL_STATE_DIR`; use the same directory on subsequent commands. It must -be private and owned by the current user. The manager runs independently of the -terminal, listens on a private `goblind.sock` Unix socket, and uses a separate +be private and owned by the current user. Keep the path short: Goblin's per-VM +Unix sockets must fit the host's socket path limit. The manager runs independently +of the terminal, listens on a private `goblind.sock` Unix socket, and uses a separate token. Adapt validates socket ownership and permissions before sending credentials; HTTP and WebSocket requests bypass proxies. Stale TCP discovery records are rejected. Concurrent commands reuse one manager. diff --git a/docs/publishing.md b/docs/publishing.md index c476e62..122a483 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -129,12 +129,12 @@ atomically changing the source pin. Review the resulting diff and run CI before releasing the CLI. `--base-url` supports fetching a pin from another trusted HTTPS mirror during development; runtime downloads still use the production endpoint. -The first rollout is ordered: deploy Platform's `/runtime/goblin` route, merge -Goblin's runtime publisher, configure its signing/OIDC environment, publish and -qualify both runtime bundles, then fill this CLI's pin and merge the CLI change. -The initial development lock is `null` until real artifacts exist. Unit tests and -manual `--runtime-dir` operation support that state; both publication jobs reject -it, so a CLI with an unconfigured managed runtime cannot be released. +Goblin must publish both runtime bundles through Platform's `/runtime/goblin` +route before updating the CLI pin. Publication requires Linux VM checks and Mac +signing/notarization; Mac VM tests are separate and do not block publication. +Development builds may use a `null` lock. Unit tests and manual `--runtime-dir` +operation support that state; both publication jobs reject it, so a CLI with an +unconfigured managed runtime cannot be released. Goblin owns Developer ID signing and notarization of the macOS runtime. This change does not add Developer ID signing to the `adapt` executable. Runtime diff --git a/runtime-lock.json b/runtime-lock.json index 19765bd..30b4ddb 100644 --- a/runtime-lock.json +++ b/runtime-lock.json @@ -1 +1,16 @@ -null +{ + "format": 1, + "revision": "4125721e6a9697f2ff16fb4a2bc263a6e80821bb", + "targets": { + "aarch64-apple-darwin": { + "sha256": "6f1bd5d2338da77d5a8a8d82c2f38bb75c7a33fc0f7ec09ab2fdfc2ecf05b614", + "manifest_sha256": "4e9a3748aa002161d59c1542cfef17d81fc64f9c3cd6694de75f52bfb58e8849", + "size": 16989503 + }, + "x86_64-unknown-linux-gnu": { + "sha256": "4deb688d8a121fd8ca7675c6e64acc870299acf0a2422fbdf7e38c132d85f836", + "manifest_sha256": "ba77de4a7fc08bd4bce9c318153cf2ca23bb2612ecbb4e681381a9ad92b84b82", + "size": 18749494 + } + } +}