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 7fdbc25..ab5df50 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,9 +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: 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 @@ -78,6 +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: cargo xtask pin-runtime --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* @@ -109,6 +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: cargo xtask pin-runtime --check --require - uses: actions/download-artifact@v4 with: pattern: adapt-* diff --git a/Cargo.lock b/Cargo.lock index 2632399..3badd46 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" @@ -358,6 +429,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -466,6 +538,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 +589,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 +841,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 +924,16 @@ dependencies = [ "base64 0.22.1", "clap", "crossterm", + "flate2", "futures-util", + "hex", "httpdate", "libc", "reqwest", "serde", "serde_json", + "sha2", + "tar", "tempfile", "tokio", "tokio-tungstenite", @@ -1016,6 +1117,7 @@ checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" dependencies = [ "base64 0.22.1", "bytes", + "futures-channel", "futures-core", "futures-util", "http", @@ -1257,7 +1359,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 +1410,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 +1498,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 +2022,30 @@ 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 = "xtask" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "hex", + "reqwest", + "serde", + "serde_json", + "sha2", + "tempfile", +] + [[package]] name = "yoke" version = "0.8.4" @@ -1995,6 +2149,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..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" @@ -27,6 +32,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..65c6687 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,26 @@ 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 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 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 -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,19 +282,19 @@ 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 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 45f37d1..122a483 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 and archive/manifest hashes for both +supported runtime targets. There is no runtime `latest` lookup. Update it with: + +```sh +cargo xtask pin-runtime 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. + +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 +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..30b4ddb --- /dev/null +++ b/runtime-lock.json @@ -0,0 +1,16 @@ +{ + "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 + } + } +} 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..d8e376d 100644 --- a/src/local_runtime.rs +++ b/src/local_runtime.rs @@ -179,7 +179,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 { @@ -214,7 +214,8 @@ mod unix { if let Some(local) = discover(&state, token, timeout).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()?; + let runtime = crate::runtime::resolve(&state, runtime, timeout).await?; + let deadline = Instant::now() + Duration::from_secs(30); let manager = runtime .join("goblind") .canonicalize() 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..cf88762 --- /dev/null +++ b/src/runtime.rs @@ -0,0 +1,117 @@ +//! 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_json::json; +use std::{ + path::{Path, PathBuf}, + time::Duration, +}; + +#[cfg(unix)] +mod bundle; +#[cfg(unix)] +mod install; +#[cfg(test)] +mod tests; + +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/"; + +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..31d774b --- /dev/null +++ b/src/runtime/bundle.rs @@ -0,0 +1,302 @@ +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, + // Existing Goblin bundle metadata; local installation does not gate on it. + 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.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: 7, + guest_protocol: 10, + 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/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 new file mode 100644 index 0000000..e7ec20d --- /dev/null +++ b/src/runtime/tests.rs @@ -0,0 +1,314 @@ +use super::*; + +fn pin() -> Pin { + Pin { + format: 1, + revision: "a".repeat(40), + 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.format = 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}"), + }; + // 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(); + 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()); + } +} 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()); + } +}