diff --git a/.github/workflows/build-binaries-linux.yml b/.github/workflows/build-binaries-linux.yml index e8bda65b6b..983e45531e 100644 --- a/.github/workflows/build-binaries-linux.yml +++ b/.github/workflows/build-binaries-linux.yml @@ -92,6 +92,22 @@ jobs: timeout-minutes: 60 steps: *build_steps + podman-driver: + name: openshell-driver-podman (${{ matrix.triple }}) + env: + PACKAGE: openshell-driver-podman + BINARY: openshell-driver-podman + strategy: + matrix: + include: + - triple: x86_64-unknown-linux-gnu + runner: linux-amd64-cpu8 + - triple: aarch64-unknown-linux-gnu + runner: linux-arm64-cpu8 + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + steps: *build_steps + runtimes: name: ${{ matrix.binary }} (${{ matrix.triple }}) env: diff --git a/.github/workflows/build-binaries-macos.yml b/.github/workflows/build-binaries-macos.yml index e5f7d09648..dba1693c87 100644 --- a/.github/workflows/build-binaries-macos.yml +++ b/.github/workflows/build-binaries-macos.yml @@ -43,6 +43,9 @@ jobs: - package: openshell-supervisor binary: openshell-supervisor triple: aarch64-apple-darwin + - package: openshell-driver-podman + binary: openshell-driver-podman + triple: aarch64-apple-darwin runs-on: macos-15-xlarge timeout-minutes: 60 steps: diff --git a/.github/workflows/build-rpm.yml b/.github/workflows/build-rpm.yml index 5050372df0..62e76fb89c 100644 --- a/.github/workflows/build-rpm.yml +++ b/.github/workflows/build-rpm.yml @@ -90,10 +90,16 @@ jobs: name: openshell-prover-${{ inputs.prover-target }} path: package-binaries/ + - name: Download Podman driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-podman-${{ inputs.gateway-target }} + path: package-binaries/ + - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway,-prover} + chmod +x package-binaries/openshell{,-gateway,-prover,-driver-podman} ls -lah package-binaries - name: Mark workspace safe for git diff --git a/.github/workflows/deb-package.yml b/.github/workflows/deb-package.yml index c3ebabedb6..5857203266 100644 --- a/.github/workflows/deb-package.yml +++ b/.github/workflows/deb-package.yml @@ -63,10 +63,16 @@ jobs: name: openshell-driver-vm-${{ matrix.gnu_target }} path: package-binaries/ + - name: Download Podman driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-podman-${{ matrix.gnu_target }} + path: package-binaries/ + - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway,-prover,-driver-vm} + chmod +x package-binaries/openshell{,-gateway,-prover,-driver-vm,-driver-podman} ls -lah package-binaries - name: Build Debian package @@ -76,6 +82,7 @@ jobs: OPENSHELL_GATEWAY_BINARY="${PWD}/package-binaries/openshell-gateway" \ OPENSHELL_PROVER_BINARY="${PWD}/package-binaries/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${PWD}/package-binaries/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="${PWD}/package-binaries/openshell-driver-podman" \ OPENSHELL_DEB_VERSION="${INPUTS_DEB_VERSION}" \ OPENSHELL_DEB_ARCH="${{ matrix.deb_arch }}" \ OPENSHELL_OUTPUT_DIR=artifacts \ diff --git a/.github/workflows/package-release-binaries.yml b/.github/workflows/package-release-binaries.yml index 429e98db19..981cbf1904 100644 --- a/.github/workflows/package-release-binaries.yml +++ b/.github/workflows/package-release-binaries.yml @@ -63,6 +63,9 @@ jobs: - artifact: openshell-driver-vm-aarch64-apple-darwin binary: openshell-driver-vm package: driver-vm-macos + - artifact: openshell-driver-podman-aarch64-apple-darwin + binary: openshell-driver-podman + package: driver-podman-macos - artifact: openshell-prover-x86_64-unknown-linux-musl binary: openshell-prover package: prover-binary-linux-amd64 diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 21de33825b..ce52d43ed9 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -330,6 +330,13 @@ jobs: path: release/ merge-multiple: true + - name: Download Podman driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-podman-* + path: release/ + merge-multiple: true + - name: Download prover binary artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -400,6 +407,7 @@ jobs: openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-apple-darwin.tar.gz \ + openshell-driver-podman-aarch64-apple-darwin.tar.gz \ *.deb \ openshell-*.rpm > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt @@ -433,6 +441,7 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz - name: Prune managed assets from dev release uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 @@ -526,6 +535,7 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz release/openshell-prover-x86_64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 5e101f77ce..a8ea8f4008 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -95,6 +95,13 @@ jobs: path: release/ merge-multiple: true + - name: Download Podman driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-podman-* + path: release/ + merge-multiple: true + - name: Download prover binary artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -140,6 +147,7 @@ jobs: openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-apple-darwin.tar.gz \ + openshell-driver-podman-aarch64-apple-darwin.tar.gz \ openshell_*.deb \ openshell-*.rpm > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt @@ -399,6 +407,7 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz release/openshell-prover-x86_64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz @@ -462,6 +471,7 @@ jobs: release/openshell-aarch64-apple-darwin.tar.gz release/openshell-gateway-aarch64-apple-darwin.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz release/openshell.rb release/openshell-checksums-sha256.txt diff --git a/AGENTS.md b/AGENTS.md index 20c8d5ac0a..735bf2b2d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,7 @@ Do not rely on this file for a full inventory. The detailed public and contribut | `crates/openshell-supervisor/` | Supervisor runtime | Gateway session, policy evaluation, credentials, and upstream networking | | `crates/openshell-supervisor-control/` | Shared supervisor control | Gateway-owned assignment controller, launch registrations, recovery coordination, and host observations for a supervisor shared by many sandboxes | | `crates/openshell-binary-identity/` | Binary identity | Shared trusted procfs executable identity resolution for isolation backends | +| `crates/openshell-driver-sdk/` | Driver SDK | Versioned startup document the gateway passes to launched compute drivers | | `crates/openshell-isolation-interface/` | Isolation backend interface | Shared data and validation for the Isolation Backend RPC contracts | | `crates/openshell-sandbox-backend/` | OpenShell sandbox backend | Concrete Isolation Backend RPC client and authenticated Sandbox Protocol shared with `openshell-sandbox` | | `crates/openshell-policy/` | Policy engine | Filesystem, network, and process constraints | diff --git a/Cargo.lock b/Cargo.lock index 9260c5bc89..c43a0b4008 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4756,6 +4756,7 @@ dependencies = [ "nix 0.29.0", "openshell-core", "openshell-crypto", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -4774,6 +4775,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "toml", "tonic", "tower-http 0.6.8", "tracing", @@ -4783,6 +4785,21 @@ dependencies = [ "uuid", ] +[[package]] +name = "openshell-driver-sdk" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "clap", + "libc", + "openshell-core", + "openshell-crypto", + "serde", + "serde_json", + "thiserror 2.0.20", + "toml", +] + [[package]] name = "openshell-driver-vault" version = "0.0.0" @@ -4827,6 +4844,7 @@ dependencies = [ "openshell-core", "openshell-crypto", "openshell-driver-podman", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -4848,6 +4866,7 @@ dependencies = [ "tempfile", "tokio", "tokio-stream", + "toml", "tonic", "tower-http 0.6.8", "tracing", @@ -4888,7 +4907,7 @@ dependencies = [ "openshell-driver-docker", "openshell-driver-kubernetes", "openshell-driver-mxc", - "openshell-driver-podman", + "openshell-driver-sdk", "openshell-otel", "openshell-policy", "openshell-server", diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index c691642904..0645a62d3e 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -109,7 +109,8 @@ impl From for openshell_otel::Protocol { } /// One OTLP collector that a supervisor exports to. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] pub struct OtlpExport { pub endpoint: String, pub protocol: OtlpProtocol, diff --git a/crates/openshell-driver-podman/Cargo.toml b/crates/openshell-driver-podman/Cargo.toml index 3fb3c51b5d..3d53f94665 100644 --- a/crates/openshell-driver-podman/Cargo.toml +++ b/crates/openshell-driver-podman/Cargo.toml @@ -17,6 +17,7 @@ path = "src/main.rs" [dependencies] openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] } openshell-otel = { path = "../openshell-otel" } +openshell-driver-sdk = { path = "../openshell-driver-sdk", features = ["clap"] } openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } tar = "0.4" @@ -32,6 +33,7 @@ hyper-util = { workspace = true } http-body-util = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +toml = { workspace = true } prost-types = { workspace = true } clap = { workspace = true } nix = { workspace = true } diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index 87a617069e..bb21520dd8 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -164,3 +164,24 @@ When `[openshell.gateway.otlp.agent]` is enabled, the driver sets `OPENSHELL_OTLP_AGENT_PROTOCOL` for a non-gRPC collector, which starts the agent trace relay. On Podman Machine it rewrites a loopback agent endpoint to the desktop host, as it does for the supervisor's trace endpoint. + +## Launch by the gateway + +The gateway runs this driver as a separate process and does not link it. It +starts `openshell-driver-podman --config `; the document carries +the gateway's resolved values and the operator's `[openshell.drivers.podman]` +table, which the driver deserializes and validates before it binds its socket. +With `--config`, any other flag is an error. The driver ignores +`expected_peer_pid` and accepts any connection from its own user, on a socket +in a private directory. + +Two subcommands take part in gateway decisions and start nothing: + +- `openshell-driver-podman probe` prints `{"available": bool, "reason": "..."}`. + Gateway auto-detection runs it. +- `openshell-driver-podman preflight --config ` validates a startup + document and prints `{"ok": bool, "error": "..."}`. `openshell-gateway config + preflight` runs it. + +The binary must be installed beside the gateway or in a libexec directory. See +[Launched Compute Drivers](../../docs/how-it-works/gateways/configuration.mdx#launched-compute-drivers). diff --git a/crates/openshell-driver-podman/src/lib.rs b/crates/openshell-driver-podman/src/lib.rs index fa06cf4864..3e31d1c7fc 100644 --- a/crates/openshell-driver-podman/src/lib.rs +++ b/crates/openshell-driver-podman/src/lib.rs @@ -9,6 +9,7 @@ pub mod grpc; mod isolation; pub mod otel_tracing; mod socket_discovery; +pub mod startup_config; #[cfg(test)] pub(crate) mod test_utils; pub(crate) mod watcher; diff --git a/crates/openshell-driver-podman/src/main.rs b/crates/openshell-driver-podman/src/main.rs index df5f05a1a3..fc80d57fa8 100644 --- a/crates/openshell-driver-podman/src/main.rs +++ b/crates/openshell-driver-podman/src/main.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use clap::Parser; +use clap::{CommandFactory, FromArgMatches, Parser}; use miette::{IntoDiagnostic, Result}; use std::future::Future; use std::net::SocketAddr; @@ -13,12 +13,19 @@ use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServ use openshell_core::sandbox_env::SupervisorOtlpArgs; use openshell_core::{AppArmorProfile, ImagePullPolicy, VERSION}; use openshell_driver_podman::config::{DEFAULT_NETWORK_NAME, DEFAULT_PODMAN_STOP_TIMEOUT_SECS}; +use openshell_driver_podman::startup_config::config_from_document; use openshell_driver_podman::{ComputeDriverService, PodmanComputeConfig, PodmanComputeDriver}; +use openshell_driver_sdk::StartupDocument; #[derive(Parser)] #[command(name = "openshell-driver-podman")] #[command(version = VERSION)] struct Args { + /// Gateway startup document (TOML). A driver started with it takes all of + /// its settings from the document and accepts no other flag. + #[arg(long)] + config: Option, + /// Operator-owned JSON policy; omitted means driver config disabled and labels required. #[arg( long, @@ -203,9 +210,87 @@ struct Args { enable_bind_mounts: bool, } +/// Parse the command line. With `--config` the document supplies everything +/// the gateway used to pass as flags, so any other flag is an error. +fn parse_args() -> std::result::Result<(Args, Option), String> { + let command = Args::command(); + let matches = command + .clone() + .try_get_matches_from(std::env::args_os()) + .unwrap_or_else(|error| error.exit()); + let mut args = Args::from_arg_matches(&matches).unwrap_or_else(|error| error.exit()); + let Some(path) = args.config.clone() else { + return Ok((args, None)); + }; + if let Some(flag) = openshell_driver_sdk::cli::first_flag_besides(&command, &matches, "config") + { + return Err(format!( + "--{flag} cannot be combined with --config; the startup document supplies it" + )); + } + let document = StartupDocument::read(&path)?; + apply_gateway_context(&mut args, &document); + Ok((args, Some(document))) +} + +/// Set the values the driver needs before it builds its configuration: +/// tracing, the listening socket, and the gateway's identity. +fn apply_gateway_context(args: &mut Args, document: &StartupDocument) { + let gateway = &document.gateway; + args.bind_socket = Some(gateway.bind_socket.clone()); + args.log_level.clone_from(&gateway.log_level); + args.gateway_name = Some(gateway.gateway_name.clone()); + gateway.telemetry.apply_to(&mut args.otlp); +} + +/// `probe` reports on stdout whether Podman is usable on this host. It takes +/// no other arguments and starts nothing. +fn run_probe() -> ! { + let result = if openshell_driver_podman::driver::is_available() { + openshell_driver_sdk::probe::ProbeResult::available() + } else { + openshell_driver_sdk::probe::ProbeResult::unavailable( + "no responsive Podman API socket found; set OPENSHELL_PODMAN_SOCKET or start the Podman service", + ) + }; + println!("{}", result.to_json()); + std::process::exit(0); +} + +/// `preflight --config ` validates the startup document's configuration +/// and reports on stdout. It starts nothing. +fn run_preflight(arguments: &[std::ffi::OsString]) -> ! { + use openshell_driver_sdk::preflight::PreflightResult; + + let result = match arguments { + [flag, path] if flag == "--config" => StartupDocument::read(std::path::Path::new(path)) + .and_then(|document| config_from_document(&document)) + .map_or_else(PreflightResult::rejected, |_| PreflightResult::ok()), + _ => PreflightResult::rejected("usage: preflight --config "), + }; + println!("{}", result.to_json()); + std::process::exit(0); +} + #[tokio::main] async fn main() -> Result<()> { - let args = Args::parse(); + let arguments: Vec<_> = std::env::args_os().skip(1).collect(); + if arguments.first().is_some_and(|arg| arg == "preflight") { + run_preflight(&arguments[1..]); + } + if std::env::args_os().nth(1).is_some_and(|arg| arg == "probe") { + if std::env::args_os().len() > 2 { + return Err(miette::miette!("probe takes no arguments")); + } + run_probe(); + } + let (args, document) = parse_args().map_err(|err| miette::miette!("{err}"))?; + // A gateway that is killed must not leave this driver running. + if document.is_some() + && let Err(error) = openshell_driver_sdk::parent::die_with_parent() + { + eprintln!("warning: {error}; a gateway crash may orphan this driver"); + } let _tracing = openshell_otel::install_driver_tracing( openshell_driver_podman::otel_tracing::TRACING, openshell_otel::DriverTracingConfig { @@ -222,55 +307,61 @@ async fn main() -> Result<()> { ); args.otlp.warn_deprecated(); - let supervisor_otlp = args.otlp.supervisor_otlp(); - // External drivers have no gateway-local staged artifact. Do not accept - // a path or silently emulate destination-CA delivery outside the gateway. - let driver = PodmanComputeDriver::new( - PodmanComputeConfig { - allow_driver_config: args.admission_config_json.allow_driver_config, - resource_admission: args.admission_config_json.resource_admission.clone(), - socket_path: args.podman_socket, - default_image: args.sandbox_image.unwrap_or_default(), - image_pull_policy: args.sandbox_image_pull_policy, - grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), - supervisor_otlp, - supervisor_gateway_name: args.gateway_name.clone(), - gateway_port: args.gateway_port, - host_gateway_ip: args - .host_gateway_ip - .unwrap_or_else(PodmanComputeConfig::default_host_gateway_ip), - ssh_socket_path: args.sandbox_ssh_socket_path, - network_name: args.network_name, - stop_timeout_secs: args.stop_timeout, - sandbox_runtime_image: args - .sandbox_runtime_image - .unwrap_or_else(openshell_core::config::default_sandbox_runtime_image), - supervisor_image: args - .supervisor_image - .unwrap_or_else(openshell_core::config::default_supervisor_image), - guest_tls_ca: args.podman_tls_ca, - guest_tls_cert: args.podman_tls_cert, - guest_tls_key: args.podman_tls_key, - provider_spiffe_workload_api_socket: args.provider_spiffe_workload_api_socket, - app_armor_profile: args.app_armor_profile, - sandbox_pids_limit: args.sandbox_pids_limit, - health_check_interval_secs: args.health_check_interval_secs, - https_proxy: args.sandbox_https_proxy, - no_proxy: args.sandbox_no_proxy, - proxy_auth_file: args.sandbox_proxy_auth_file, - proxy_auth_allow_insecure: args.sandbox_proxy_auth_allow_insecure, - proxy_connect_by_hostname: args.sandbox_proxy_connect_by_hostname, - proxy_ca_bundle: args.sandbox_proxy_ca_bundle, - additional_ca_bundle: args.sandbox_additional_ca_bundle, - userns: args.userns, - uidmap: args.uidmap, - gidmap: args.gidmap, - enable_bind_mounts: args.enable_bind_mounts, - }, - None, - ) - .await - .into_diagnostic()?; + let (config, network_trust) = if let Some(document) = document.as_ref() { + config_from_document(document).map_err(|err| miette::miette!("{err}"))? + } else { + let supervisor_otlp = args.otlp.supervisor_otlp(); + // Without a startup document there is no gateway-local staged + // artifact. Do not accept a path or silently emulate + // destination-CA delivery outside the gateway. + ( + PodmanComputeConfig { + allow_driver_config: args.admission_config_json.allow_driver_config, + resource_admission: args.admission_config_json.resource_admission.clone(), + socket_path: args.podman_socket, + default_image: args.sandbox_image.unwrap_or_default(), + image_pull_policy: args.sandbox_image_pull_policy, + grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), + supervisor_otlp, + supervisor_gateway_name: args.gateway_name.clone(), + gateway_port: args.gateway_port, + host_gateway_ip: args + .host_gateway_ip + .unwrap_or_else(PodmanComputeConfig::default_host_gateway_ip), + ssh_socket_path: args.sandbox_ssh_socket_path, + network_name: args.network_name, + stop_timeout_secs: args.stop_timeout, + sandbox_runtime_image: args + .sandbox_runtime_image + .unwrap_or_else(openshell_core::config::default_sandbox_runtime_image), + supervisor_image: args + .supervisor_image + .unwrap_or_else(openshell_core::config::default_supervisor_image), + guest_tls_ca: args.podman_tls_ca, + guest_tls_cert: args.podman_tls_cert, + guest_tls_key: args.podman_tls_key, + provider_spiffe_workload_api_socket: args.provider_spiffe_workload_api_socket, + app_armor_profile: args.app_armor_profile, + sandbox_pids_limit: args.sandbox_pids_limit, + health_check_interval_secs: args.health_check_interval_secs, + https_proxy: args.sandbox_https_proxy, + no_proxy: args.sandbox_no_proxy, + proxy_auth_file: args.sandbox_proxy_auth_file, + proxy_auth_allow_insecure: args.sandbox_proxy_auth_allow_insecure, + proxy_connect_by_hostname: args.sandbox_proxy_connect_by_hostname, + proxy_ca_bundle: args.sandbox_proxy_ca_bundle, + additional_ca_bundle: args.sandbox_additional_ca_bundle, + userns: args.userns, + uidmap: args.uidmap, + gidmap: args.gidmap, + enable_bind_mounts: args.enable_bind_mounts, + }, + None, + ) + }; + let driver = PodmanComputeDriver::new(config, network_trust) + .await + .into_diagnostic()?; let service = ComputeDriverServer::new(ComputeDriverService::new(driver)); if let Some(socket_path) = args.bind_socket { diff --git a/crates/openshell-driver-podman/src/startup_config.rs b/crates/openshell-driver-podman/src/startup_config.rs new file mode 100644 index 0000000000..055a3f44ca --- /dev/null +++ b/crates/openshell-driver-podman/src/startup_config.rs @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Building the Podman driver configuration from the gateway startup document. +//! +//! The document's `[driver_config]` table is the operator's +//! `[openshell.drivers.podman]` table, passed through unchanged. The driver +//! deserializes it into [`PodmanComputeConfig`], applies the gateway context, +//! and validates the result before it starts. + +use openshell_core::NetworkSupervisorTrustBundle; +use openshell_driver_sdk::StartupDocument; + +use crate::PodmanComputeConfig; + +/// Environment variable that overrides the Podman API socket path. +pub const PODMAN_SOCKET_ENV: &str = "OPENSHELL_PODMAN_SOCKET"; + +/// Build and validate the driver configuration and the network trust bundle +/// from a startup document. +/// +/// # Errors +/// +/// Returns a message when `driver_config` is invalid, validation fails, or the +/// staged network trust artifact cannot be loaded and verified. +pub fn config_from_document( + document: &StartupDocument, +) -> Result<(PodmanComputeConfig, Option), String> { + let gateway = &document.gateway; + let mut config: PodmanComputeConfig = toml::Value::Table(document.driver_config.clone()) + .try_into() + .map_err(|error: toml::de::Error| { + format!("invalid [driver_config] in startup document: {error}") + })?; + + config.gateway_port = gateway.gateway_port; + config.supervisor_otlp = gateway.telemetry.supervisor_otlp(); + config.supervisor_gateway_name = Some(gateway.gateway_name.clone()); + if config.guest_tls_ca.is_none() { + config.guest_tls_ca.clone_from(&gateway.tls_ca); + } + apply_environment(&mut config, |name| std::env::var(name).ok()); + config + .validate_configuration() + .map_err(|error| error.to_string())?; + + let trust = gateway + .network_trust + .as_ref() + .map(|trust| { + let count = usize::try_from(trust.certificate_count) + .map_err(|_| "network trust certificate count is too large".to_string())?; + openshell_driver_sdk::network_trust::load_staged_bundle( + &trust.path, + &trust.digest, + count, + ) + }) + .transpose()?; + Ok((config, trust)) +} + +/// Environment overrides the gateway applied to an in-process driver. A +/// launched driver inherits the gateway's environment, so it applies them here. +fn apply_environment( + config: &mut PodmanComputeConfig, + environment: impl Fn(&str) -> Option, +) { + if let Some(image) = environment(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV) { + config.sandbox_runtime_image = image; + } + if let Some(image) = environment(openshell_core::config::SUPERVISOR_IMAGE_ENV) { + config.supervisor_image = image; + } + if let Some(path) = environment(PODMAN_SOCKET_ENV) { + config.socket_path = Some(path.into()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &str = include_str!("../tests/fixtures/startup-podman.toml"); + + fn document() -> StartupDocument { + StartupDocument::parse(FIXTURE).unwrap() + } + + #[test] + fn the_fixture_builds_a_validated_configuration() { + let (config, trust) = { + // The trust artifact does not exist here, so exercise the driver + // configuration without it. + let mut document = document(); + document.gateway.network_trust = None; + config_from_document(&document).unwrap() + }; + assert!(trust.is_none()); + assert_eq!(config.gateway_port, 8080); + assert_eq!(config.supervisor_gateway_name.as_deref(), Some("gateway-a")); + assert_eq!(config.network_name, "openshell-test"); + assert!(config.allow_driver_config); + assert_eq!( + config + .supervisor_otlp + .traces + .as_ref() + .map(|t| t.endpoint.as_str()), + Some("https://collector.example:4317") + ); + assert!(config.guest_tls_ca.is_none()); + } + + #[test] + fn the_gateway_ca_is_used_when_the_driver_table_sets_none() { + let dir = tempfile::tempdir().unwrap(); + let ca = dir.path().join("ca.pem"); + std::fs::write(&ca, "ca").unwrap(); + let mut document = document(); + document.gateway.network_trust = None; + document.gateway.tls_ca = Some(ca.clone()); + let (config, _) = config_from_document(&document).unwrap(); + assert_eq!(config.guest_tls_ca.as_deref(), Some(ca.as_path())); + } + + #[test] + fn unknown_driver_config_keys_are_rejected() { + let mut document = document(); + document.gateway.network_trust = None; + document.driver_config = toml::from_str("surprise = 1").unwrap(); + let error = config_from_document(&document).unwrap_err(); + assert!(error.contains("surprise"), "{error}"); + } + + #[test] + fn the_environment_overrides_configured_images_and_socket() { + let mut config = PodmanComputeConfig::default(); + apply_environment(&mut config, |name| match name { + openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV => Some("runtime:env".into()), + openshell_core::config::SUPERVISOR_IMAGE_ENV => Some("supervisor:env".into()), + PODMAN_SOCKET_ENV => Some("/run/podman.sock".into()), + _ => None, + }); + assert_eq!(config.sandbox_runtime_image, "runtime:env"); + assert_eq!(config.supervisor_image, "supervisor:env"); + assert_eq!( + config.socket_path.as_deref(), + Some(std::path::Path::new("/run/podman.sock")) + ); + } +} diff --git a/crates/openshell-driver-podman/tests/fixtures/startup-podman.toml b/crates/openshell-driver-podman/tests/fixtures/startup-podman.toml new file mode 100644 index 0000000000..9edbec251b --- /dev/null +++ b/crates/openshell-driver-podman/tests/fixtures/startup-podman.toml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Startup document the gateway writes for the Podman driver. The gateway's +# conversion test and the driver's configuration test both read this file. + +schema_version = 1 + +[gateway] +bind_socket = "/var/lib/openshell/podman-driver/run/compute-driver.sock" +expected_peer_pid = 4242 +log_level = "debug" +gateway_name = "gateway-a" +gateway_port = 8080 + +[gateway.telemetry.traces] +endpoint = "https://collector.example:4317" +protocol = "grpc" + +[gateway.network_trust] +path = "/var/lib/openshell/trust/bundle.pem" +digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +certificate_count = 3 + +[driver_config] +allow_driver_config = true +default_image = "openshell/sandbox:default" +network_name = "openshell-test" +stop_timeout_secs = 20 +enable_bind_mounts = true diff --git a/crates/openshell-driver-sdk/Cargo.toml b/crates/openshell-driver-sdk/Cargo.toml new file mode 100644 index 0000000000..d1abb3aa24 --- /dev/null +++ b/crates/openshell-driver-sdk/Cargo.toml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-sdk" +description = "Startup document contract between the OpenShell gateway and launched compute drivers" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +clap = { workspace = true, optional = true } +base64 = { workspace = true } +openshell-crypto = { workspace = true } +openshell-core = { path = "../openshell-core", default-features = false } +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +toml = { workspace = true } + +[target.'cfg(unix)'.dependencies] +libc = "0.2" + +[features] +## Helpers for drivers that parse their command line with clap. +clap = ["dep:clap", "openshell-core/clap"] + +[lints] +workspace = true diff --git a/crates/openshell-driver-sdk/README.md b/crates/openshell-driver-sdk/README.md new file mode 100644 index 0000000000..d23bd28b49 --- /dev/null +++ b/crates/openshell-driver-sdk/README.md @@ -0,0 +1,50 @@ +# openshell-driver-sdk + +Contract between the gateway and the compute drivers it launches. + +The gateway writes one TOML startup document and starts the driver with +`--config `. The document has a `schema_version`, a `[gateway]` table with +a fixed schema, and a `[driver_config]` table that is the operator's +`driver_config` for the selected driver. The gateway does not interpret +`driver_config`; the driver deserializes and validates it. + +This crate owns the document types, bounded parsing, and the schema version +check. Where `openshell-core` already defines a type the gateway and drivers +share (OTLP exports), the document +uses it directly, so there is one definition. Those types' serialized form is +part of the contract, and changing it is a schema change. Creating the file with +restrictive permissions and launching the driver belong to the gateway. + +## Versioning + +A driver accepts exactly the `SCHEMA_VERSION` it was built with and refuses any +other, naming both versions. Bump `SCHEMA_VERSION` for any change that makes an +existing document fail to parse or changes its meaning, including removing or +renaming a field or changing its type. + +`tests/fixtures/startup-v1.toml` lists every field the schema defines. A test +parses and re-serializes it and compares the result, so a removed or renamed +field changes the fixture and shows in review. Keep every optional field +populated in it. Machine-checked breaking-change detection is not in place yet. + +## Contents + +- Network trust is passed as the staged artifact's path, digest, and + certificate count. The certificate bytes do not cross the process boundary. +- OTLP export headers are secrets and are not in the document. +- `[gateway]` holds only values that come from the gateway itself. Settings an + operator puts in a driver's table, such as admission, proxy, and the endpoint + override, stay in `[driver_config]` for the driver to read and validate. +- `gateway_port` lets a driver derive the endpoint sandboxes use to reach the + gateway. +- Proxy credentials are referenced by file path, not included. + +## Subcommands + +`probe` and `preflight` print one bounded JSON object on stdout; the result +types are in `probe` and `preflight`. `probe` reports whether the driver is +usable on this host, takes no startup document, and the gateway gives it five +seconds and 4 KiB. `preflight --config ` validates a startup document +without starting the driver and gets ten seconds and 16 KiB. The gateway treats +a failure, a timeout, or oversized output as "not available" or a failed +preflight. diff --git a/crates/openshell-driver-sdk/src/cli.rs b/crates/openshell-driver-sdk/src/cli.rs new file mode 100644 index 0000000000..6441f60605 --- /dev/null +++ b/crates/openshell-driver-sdk/src/cli.rs @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Command-line helpers for drivers started with `--config`. + +use clap::parser::ValueSource; +use clap::{ArgMatches, Command}; + +/// The first flag other than `config_id` that was given on the command line. +/// +/// A driver started from a startup document takes everything from it, so any +/// other flag would make precedence ambiguous. Values from the environment do +/// not count: the document is authoritative over them. +#[must_use] +pub fn first_flag_besides( + command: &Command, + matches: &ArgMatches, + config_id: &str, +) -> Option { + command + .get_arguments() + .filter(|arg| arg.get_id().as_str() != config_id) + .find(|arg| matches.value_source(arg.get_id().as_str()) == Some(ValueSource::CommandLine)) + .map(|arg| { + arg.get_long() + .map_or_else(|| arg.get_id().to_string(), str::to_string) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Args { + #[arg(long)] + config: Option, + #[arg(long, env = "TEST_SDK_CLI_VCPUS", default_value_t = 2)] + vcpus: u8, + } + + fn first_flag(arguments: &[&str]) -> Option { + let command = ::command(); + let matches = command.clone().try_get_matches_from(arguments).unwrap(); + first_flag_besides(&command, &matches, "config") + } + + #[test] + fn only_the_config_flag_is_allowed() { + assert_eq!(first_flag(&["driver", "--config", "x"]), None); + assert_eq!( + first_flag(&["driver", "--config", "x", "--vcpus", "8"]).as_deref(), + Some("vcpus") + ); + } +} diff --git a/crates/openshell-driver-sdk/src/lib.rs b/crates/openshell-driver-sdk/src/lib.rs new file mode 100644 index 0000000000..5f55be1444 --- /dev/null +++ b/crates/openshell-driver-sdk/src/lib.rs @@ -0,0 +1,376 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Contract between the `OpenShell` gateway and the compute drivers it launches. +//! +//! The gateway writes one [`StartupDocument`] and passes its path to the driver +//! with `--config `. The document has a `schema_version`, a fixed +//! [`GatewayContext`], and the operator's `driver_config` table, which the +//! gateway does not interpret. +//! +//! Where `openshell-core` already defines a type the gateway and drivers share +//! (OTLP exports), the document uses it directly, so there is one definition +//! to keep in step. Those types' serialized form is +//! part of the contract: changing it is a schema change. +//! +//! # Versioning +//! +//! [`SCHEMA_VERSION`] must change whenever a change would make an existing +//! document fail to parse or change its meaning. A driver accepts exactly the +//! version it was built with, and [`StartupDocument::parse`] checks the version +//! before decoding the rest, so a mismatch reports both versions instead of an +//! unrelated field error. + +#[cfg(feature = "clap")] +pub mod cli; +pub mod network_trust; +pub mod parent; +pub mod preflight; +pub mod probe; + +use std::path::PathBuf; + +use openshell_core::sandbox_env::OtlpExport; +use serde::{Deserialize, Serialize}; + +/// Schema version this crate reads and writes. +pub const SCHEMA_VERSION: u32 = 1; + +/// Largest document [`StartupDocument::parse`] accepts, in bytes. +pub const MAX_DOCUMENT_BYTES: usize = 1024 * 1024; + +/// Reasons a startup document cannot be read or written. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DocumentError { + #[error("startup document is {size} bytes, over the {limit} byte limit")] + TooLarge { size: usize, limit: usize }, + #[error("startup document is not valid TOML: {0}")] + Syntax(String), + #[error("startup document has no integer `schema_version`")] + MissingSchemaVersion, + #[error("startup document schema version {document}, this driver supports {supported}")] + UnsupportedSchemaVersion { document: i64, supported: u32 }, + #[error("startup document is invalid: {0}")] + Invalid(String), + #[error("startup document cannot be serialized: {0}")] + Serialize(String), +} + +/// The document the gateway passes to a launched driver. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct StartupDocument { + pub schema_version: u32, + pub gateway: GatewayContext, + /// The selected driver's `driver_config` table, opaque to the gateway. + /// The driver deserializes and validates it. + #[serde(default)] + pub driver_config: toml::Table, +} + +impl StartupDocument { + /// Build a document at the current [`SCHEMA_VERSION`]. + #[must_use] + pub fn new(gateway: GatewayContext, driver_config: toml::Table) -> Self { + Self { + schema_version: SCHEMA_VERSION, + gateway, + driver_config, + } + } + + /// Parse a document, refusing oversized input and any schema version other + /// than [`SCHEMA_VERSION`]. + /// + /// # Errors + /// + /// Returns [`DocumentError`] when the input is too large, is not TOML, + /// names an unsupported version, or does not match the schema. + pub fn parse(text: &str) -> Result { + if text.len() > MAX_DOCUMENT_BYTES { + return Err(DocumentError::TooLarge { + size: text.len(), + limit: MAX_DOCUMENT_BYTES, + }); + } + let table: toml::Table = + toml::from_str(text).map_err(|error| DocumentError::Syntax(error.to_string()))?; + let document = table + .get("schema_version") + .and_then(toml::Value::as_integer) + .ok_or(DocumentError::MissingSchemaVersion)?; + if document != i64::from(SCHEMA_VERSION) { + return Err(DocumentError::UnsupportedSchemaVersion { + document, + supported: SCHEMA_VERSION, + }); + } + toml::Value::Table(table) + .try_into() + .map_err(|error: toml::de::Error| DocumentError::Invalid(error.to_string())) + } + + /// Read and parse the document at `path`, reading no more than + /// [`MAX_DOCUMENT_BYTES`]. + /// + /// # Errors + /// + /// Returns a message that names the file for read failures, an oversized + /// document, a schema version this driver does not accept, or invalid + /// content. + pub fn read(path: &std::path::Path) -> Result { + use std::io::Read as _; + + let mut text = String::new(); + std::fs::File::open(path) + .and_then(|file| { + file.take(MAX_DOCUMENT_BYTES as u64 + 1) + .read_to_string(&mut text) + }) + .map_err(|error| format!("read startup document {}: {error}", path.display()))?; + Self::parse(&text).map_err(|error| format!("startup document {}: {error}", path.display())) + } + + /// Render the document as TOML. + /// + /// # Errors + /// + /// Returns [`DocumentError::Serialize`] when the document cannot be + /// represented as TOML. + pub fn to_toml(&self) -> Result { + toml::to_string(self).map_err(|error| DocumentError::Serialize(error.to_string())) + } +} + +/// Settings the gateway resolves for every launched driver. +/// +/// Scalars come before tables so the value serializes as valid TOML. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct GatewayContext { + /// Unix socket the driver binds for the gateway's `ComputeDriver` channel. + pub bind_socket: PathBuf, + /// Process id of the gateway, which the driver expects on its socket. + pub expected_peer_pid: u32, + pub log_level: String, + pub gateway_name: String, + /// Port the gateway serves on. A driver that derives the endpoint + /// sandboxes use to reach the gateway needs it. + pub gateway_port: u16, + /// CA certificate the supervisors use to authenticate the gateway, when + /// the gateway has one for the driver. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub tls_ca: Option, + #[serde(default, skip_serializing_if = "Telemetry::is_empty")] + pub telemetry: Telemetry, + /// Staged network trust artifact. Only its location and identity cross the + /// process boundary, never the certificate bytes. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub network_trust: Option, +} + +/// OTLP exports the driver and the supervisors it starts must use. +/// +/// Export headers are secrets and are not part of the document. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Telemetry { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub traces: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ocsf: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub agent: Option, + /// TLS material for the trace collector. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub collector: Option, +} + +impl Telemetry { + #[must_use] + pub fn is_empty(&self) -> bool { + *self == Self::default() + } + + /// The exports a driver passes to the supervisors it starts. + #[must_use] + pub fn supervisor_otlp(&self) -> openshell_core::sandbox_env::SupervisorOtlp { + openshell_core::sandbox_env::SupervisorOtlp { + traces: self.traces.clone(), + ocsf: self.ocsf.clone(), + agent: self.agent.clone(), + } + } + + /// Set a driver's OTLP command-line settings from the document. + #[cfg(feature = "clap")] + pub fn apply_to(&self, args: &mut openshell_core::sandbox_env::SupervisorOtlpArgs) { + if let Some(export) = &self.traces { + args.endpoint = Some(export.endpoint.clone()); + args.protocol = export.protocol; + } + if let Some(export) = &self.ocsf { + args.ocsf_endpoint = Some(export.endpoint.clone()); + args.ocsf_protocol = export.protocol; + } + if let Some(export) = &self.agent { + args.agent_endpoint = Some(export.endpoint.clone()); + args.agent_protocol = export.protocol; + } + if let Some(collector) = &self.collector { + args.ca_file.clone_from(&collector.ca_file); + args.cert_file.clone_from(&collector.cert_file); + args.key_file.clone_from(&collector.key_file); + } + } +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorTls { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ca_file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cert_file: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub key_file: Option, +} + +/// Location and identity of the staged network trust bundle. +/// +/// The driver reads the file, verifies it against `digest` and +/// `certificate_count`, and keeps its own snapshot. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct NetworkTrust { + pub path: PathBuf, + pub digest: String, + pub certificate_count: u32, +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &str = include_str!("../tests/fixtures/startup-v1.toml"); + + fn minimal_gateway() -> GatewayContext { + GatewayContext { + bind_socket: "/run/driver.sock".into(), + expected_peer_pid: 1, + log_level: "info".into(), + gateway_name: "gateway".into(), + gateway_port: 8080, + tls_ca: None, + telemetry: Telemetry::default(), + network_trust: None, + } + } + + /// Removing or renaming a field fails here: the fixture lists every field, + /// and `deny_unknown_fields` rejects any the types no longer define. A + /// field the types define but the fixture omits does not fail this test, so + /// the fixture must keep every optional field populated. + #[test] + fn fixture_round_trips_without_losing_fields() { + let document = StartupDocument::parse(FIXTURE).expect("fixture parses"); + let written = document.to_toml().expect("document serializes"); + + let original: toml::Table = toml::from_str(FIXTURE).unwrap(); + let round_tripped: toml::Table = toml::from_str(&written).unwrap(); + assert_eq!(original, round_tripped); + assert_eq!(StartupDocument::parse(&written).unwrap(), document); + } + + #[test] + fn driver_config_passes_through_unchanged() { + let document = StartupDocument::parse(FIXTURE).unwrap(); + assert_eq!(document.driver_config["vcpus"].as_integer(), Some(2)); + assert_eq!( + document.driver_config["nested"]["key"].as_str(), + Some("value") + ); + } + + #[test] + fn minimal_document_omits_unset_optional_tables() { + let text = StartupDocument::new(minimal_gateway(), toml::Table::new()) + .to_toml() + .unwrap(); + for absent in ["telemetry", "network_trust", "tls_ca"] { + assert!( + !text.contains(absent), + "{absent} should be omitted:\n{text}" + ); + } + assert_eq!( + StartupDocument::parse(&text).unwrap().gateway, + minimal_gateway() + ); + } + + #[test] + fn refuses_other_schema_version_naming_both() { + let text = FIXTURE.replace("schema_version = 1", "schema_version = 2"); + let error = StartupDocument::parse(&text).unwrap_err(); + assert_eq!( + error, + DocumentError::UnsupportedSchemaVersion { + document: 2, + supported: SCHEMA_VERSION + } + ); + let message = error.to_string(); + assert!(message.contains('2') && message.contains(&SCHEMA_VERSION.to_string())); + } + + #[test] + fn version_is_checked_before_the_rest_is_decoded() { + let text = "schema_version = 99\n[gateway]\nfuture_field = true\n"; + assert!(matches!( + StartupDocument::parse(text), + Err(DocumentError::UnsupportedSchemaVersion { document: 99, .. }) + )); + } + + #[test] + fn refuses_missing_schema_version() { + assert_eq!( + StartupDocument::parse("[gateway]\n").unwrap_err(), + DocumentError::MissingSchemaVersion + ); + } + + #[test] + fn refuses_unknown_gateway_field() { + let text = FIXTURE.replace("[gateway]\n", "[gateway]\nsurprise = true\n"); + assert!(matches!( + StartupDocument::parse(&text), + Err(DocumentError::Invalid(_)) + )); + } + + #[test] + fn refuses_oversized_document() { + let text = format!("# {}\n", "x".repeat(MAX_DOCUMENT_BYTES)); + assert!(matches!( + StartupDocument::parse(&text), + Err(DocumentError::TooLarge { .. }) + )); + } + + #[test] + fn a_missing_file_names_the_path() { + let error = + StartupDocument::read(std::path::Path::new("/nonexistent/startup.toml")).unwrap_err(); + assert!(error.contains("/nonexistent/startup.toml"), "{error}"); + } + + #[test] + fn refuses_invalid_toml() { + assert!(matches!( + StartupDocument::parse("schema_version = ["), + Err(DocumentError::Syntax(_)) + )); + } +} diff --git a/crates/openshell-driver-sdk/src/network_trust.rs b/crates/openshell-driver-sdk/src/network_trust.rs new file mode 100644 index 0000000000..fb73dbe1fd --- /dev/null +++ b/crates/openshell-driver-sdk/src/network_trust.rs @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Loading the gateway's staged network trust artifact in a launched driver. +//! +//! The startup document carries only the artifact's path, digest, and +//! certificate count. The driver reads the bounded artifact once, checks it +//! against those values, and keeps its own immutable copy. + +use std::fmt::Write as _; +use std::fs; +use std::io::Read; +use std::path::Path; + +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; +use openshell_core::NetworkSupervisorTrustBundle; +use openshell_core::network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES; +#[cfg(unix)] +use std::os::unix::fs::{OpenOptionsExt as _, PermissionsExt}; + +/// Read the staged artifact at `path`, verify it against the expected digest +/// and certificate count, and return a bundle that owns the verified bytes. +/// +/// The returned bundle's artifact path records provenance only. Do not call +/// `verify_artifact` on it to re-read the mutable gateway-host path. +/// +/// # Errors +/// +/// Returns a message when the path, digest, or count is invalid, the artifact +/// is unreadable, oversized, not read-only, a symlink, or not canonical PEM, or +/// it does not match the digest or count. +pub fn load_staged_bundle( + path: &Path, + expected_digest: &str, + expected_certificate_count: usize, +) -> Result { + if path.as_os_str().is_empty() { + return Err("additional CA artifact path must not be empty".to_string()); + } + if expected_certificate_count == 0 { + return Err("additional CA certificate count must be greater than zero".to_string()); + } + let expected_digest = normalized_additional_ca_digest(expected_digest)?; + let pem = read_gateway_additional_ca_artifact(path)?; + // Deterministic destination-trust generation label, not an + // authenticity proof: the equality check below only detects + // staged-artifact drift; trust comes from the gateway's + // normalization and TLS verification. Classified as a non-security + // identity hash in openshell-crypto/README.md. + let digest = openshell_crypto::sha256(&pem) + .map_err(|error| format!("failed to hash additional CA artifact: {error}"))?; + let actual_digest = digest + .iter() + .fold(String::from("sha256:"), |mut text, byte| { + let _ = write!(text, "{byte:02x}"); + text + }); + if actual_digest != expected_digest { + return Err(format!( + "additional CA artifact '{}' does not match expected digest {}", + path.display(), + expected_digest + )); + } + let actual_certificate_count = + normalized_additional_ca_certificate_count(&pem).map_err(|error| { + format!( + "additional CA artifact '{}' is not a normalized certificate bundle: {error}", + path.display() + ) + })?; + if actual_certificate_count != expected_certificate_count { + return Err(format!( + "additional CA artifact '{}' has certificate count {}, expected {}", + path.display(), + actual_certificate_count, + expected_certificate_count + )); + } + Ok(NetworkSupervisorTrustBundle::new( + pem, + actual_certificate_count, + expected_digest, + path.to_path_buf(), + )) +} + +/// Require the generation form emitted by gateway normalization. +fn normalized_additional_ca_digest(digest: &str) -> Result { + let Some(hex) = digest.strip_prefix("sha256:") else { + return Err("additional CA digest must use the sha256: prefix".to_string()); + }; + if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err("additional CA digest must be a SHA-256 digest".to_string()); + } + if hex.bytes().any(|byte| byte.is_ascii_uppercase()) { + return Err("additional CA digest must use normalized lowercase hexadecimal".to_string()); + } + Ok(format!("sha256:{hex}")) +} + +/// Read a normalized gateway artifact once without following symlinks. +fn read_gateway_additional_ca_artifact(path: &Path) -> Result, String> { + let metadata = fs::symlink_metadata(path).map_err(|error| { + format!( + "inspect additional CA artifact '{}': {error}", + path.display() + ) + })?; + if !metadata.file_type().is_file() { + return Err(format!( + "additional CA artifact '{}' is not a regular file", + path.display() + )); + } + validate_gateway_additional_ca_artifact_metadata(path, &metadata)?; + + let mut options = fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + // The pre-open metadata check gives portable diagnostics, while these + // flags ensure an attacker cannot replace it with a symlink, FIFO, or + // blocking special file before the actual one-time read. + options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let mut file = options + .open(path) + .map_err(|error| format!("open additional CA artifact '{}': {error}", path.display()))?; + let opened_metadata = file.metadata().map_err(|error| { + format!( + "inspect additional CA artifact '{}': {error}", + path.display() + ) + })?; + if !opened_metadata.file_type().is_file() { + return Err(format!( + "additional CA artifact '{}' is not a regular file", + path.display() + )); + } + validate_gateway_additional_ca_artifact_metadata(path, &opened_metadata)?; + + let capacity = usize::try_from(opened_metadata.len()).map_err(|_| { + format!( + "additional CA artifact '{}' exceeds the {}-byte limit", + path.display(), + MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + ) + })?; + let mut pem = Vec::with_capacity(capacity); + Read::by_ref(&mut file) + .take((MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + 1) as u64) + .read_to_end(&mut pem) + .map_err(|error| format!("read additional CA artifact '{}': {error}", path.display()))?; + if pem.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES { + return Err(format!( + "additional CA artifact '{}' exceeds the {}-byte limit", + path.display(), + MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + )); + } + Ok(pem) +} + +fn validate_gateway_additional_ca_artifact_metadata( + path: &Path, + metadata: &fs::Metadata, +) -> Result<(), String> { + if metadata.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES as u64 { + return Err(format!( + "additional CA artifact '{}' exceeds the {}-byte limit", + path.display(), + MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + )); + } + #[cfg(unix)] + if metadata.permissions().mode() & 0o7777 != 0o444 { + return Err(format!( + "additional CA artifact '{}' does not have the required read-only permissions", + path.display() + )); + } + Ok(()) +} + +/// Verify that the bytes are exactly the canonical PEM representation emitted +/// by the gateway's destination-trust normalization boundary, and return its +/// number of certificate blocks. +fn normalized_additional_ca_certificate_count(pem: &[u8]) -> Result { + let text = std::str::from_utf8(pem).map_err(|_| "bundle is not UTF-8 PEM text")?; + let mut remainder = text; + let mut normalized = Vec::with_capacity(pem.len()); + let mut certificate_count = 0_usize; + + while !remainder.is_empty() { + let Some(after_begin) = remainder.strip_prefix("-----BEGIN CERTIFICATE-----\n") else { + return Err("bundle contains material outside canonical certificate blocks"); + }; + remainder = after_begin; + let mut encoded = String::new(); + loop { + let Some(newline) = remainder.find('\n') else { + return Err("certificate block is missing its terminating newline"); + }; + let line = &remainder[..newline]; + remainder = &remainder[newline + 1..]; + if line == "-----END CERTIFICATE-----" { + break; + } + if line.is_empty() || line.len() > 64 { + return Err("certificate block has a non-canonical base64 line"); + } + encoded.push_str(line); + } + let decoded = BASE64_STANDARD + .decode(encoded.as_bytes()) + .map_err(|_| "certificate block contains invalid base64")?; + if decoded.is_empty() { + return Err("certificate block is empty"); + } + normalized.extend_from_slice(b"-----BEGIN CERTIFICATE-----\n"); + let canonical = BASE64_STANDARD.encode(decoded); + for line in canonical.as_bytes().chunks(64) { + normalized.extend_from_slice(line); + normalized.push(b'\n'); + } + normalized.extend_from_slice(b"-----END CERTIFICATE-----\n"); + certificate_count += 1; + } + + if certificate_count == 0 { + return Err("bundle contains no certificate blocks"); + } + if normalized != pem { + return Err("bundle is not canonical normalized PEM"); + } + Ok(certificate_count) +} diff --git a/crates/openshell-driver-sdk/src/parent.rs b/crates/openshell-driver-sdk/src/parent.rs new file mode 100644 index 0000000000..9ca91ed541 --- /dev/null +++ b/crates/openshell-driver-sdk/src/parent.rs @@ -0,0 +1,65 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Ending a launched driver when its gateway disappears. +//! +//! The gateway launches a driver and removes its socket on the next launch. A +//! gateway that is killed outside its init system would otherwise leave the +//! driver running, and the next launch would start a second one. + +#[cfg(unix)] +use std::time::Duration; + +/// Exit this process when its parent process ends. +/// +/// The check polls the parent process id once a second, so the driver ends +/// within about a second of the gateway. It works on every unix and needs no +/// platform-specific kernel interface. +/// +/// # Errors +/// +/// Returns a message when the parent is already gone or the watcher cannot +/// start. +#[cfg(unix)] +pub fn die_with_parent() -> Result<(), String> { + die_with_parent_polling(Duration::from_secs(1), || std::process::exit(1)) +} + +#[cfg(unix)] +fn die_with_parent_polling( + interval: Duration, + on_orphaned: impl FnOnce() + Send + 'static, +) -> Result<(), String> { + let parent = std::os::unix::process::parent_id(); + if parent == 1 { + return Err("the parent process has already ended".to_string()); + } + std::thread::Builder::new() + .name("parent-guard".to_string()) + .spawn(move || { + loop { + std::thread::sleep(interval); + if std::os::unix::process::parent_id() != parent { + on_orphaned(); + return; + } + } + }) + .map(|_| ()) + .map_err(|error| format!("failed to start the parent guard: {error}")) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + #[test] + fn a_running_parent_is_not_reported() { + let (sender, receiver) = std::sync::mpsc::channel(); + die_with_parent_polling(Duration::from_millis(10), move || { + let _ = sender.send(()); + }) + .unwrap(); + assert!(receiver.recv_timeout(Duration::from_millis(200)).is_err()); + } +} diff --git a/crates/openshell-driver-sdk/src/preflight.rs b/crates/openshell-driver-sdk/src/preflight.rs new file mode 100644 index 0000000000..d186189f80 --- /dev/null +++ b/crates/openshell-driver-sdk/src/preflight.rs @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Result of a driver's `preflight` subcommand. +//! +//! `openshell-driver- preflight --config ` validates the driver's +//! configuration from a startup document without starting the driver, opening +//! sockets, or changing runtime state, and reports on stdout, as one JSON +//! object, whether the configuration is acceptable. The gateway treats a +//! failure, a timeout, or output larger than [`MAX_PREFLIGHT_OUTPUT_BYTES`] as +//! a failed preflight. + +use serde::{Deserialize, Serialize}; + +/// Largest preflight output the gateway accepts. +pub const MAX_PREFLIGHT_OUTPUT_BYTES: usize = 16 * 1024; + +/// What a driver reports about a startup document. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PreflightResult { + pub ok: bool, + /// Why the configuration was rejected, for the operator. Omitted when ok. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +impl PreflightResult { + #[must_use] + pub const fn ok() -> Self { + Self { + ok: true, + error: None, + } + } + + #[must_use] + pub fn rejected(error: impl Into) -> Self { + Self { + ok: false, + error: Some(error.into()), + } + } + + /// Serialize as the single JSON line a driver prints. + #[must_use] + pub fn to_json(&self) -> String { + serde_json::to_string(self).expect("a preflight result always serializes") + } + + /// Parse a driver's preflight output. + /// + /// # Errors + /// + /// Returns a message when the output is too large or is not a result. + pub fn parse(output: &[u8]) -> Result { + if output.len() > MAX_PREFLIGHT_OUTPUT_BYTES { + return Err(format!( + "preflight output exceeds {MAX_PREFLIGHT_OUTPUT_BYTES} bytes" + )); + } + serde_json::from_slice(output).map_err(|error| format!("invalid preflight output: {error}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn results_round_trip_and_omit_the_error_when_ok() { + let ok = PreflightResult::ok(); + assert_eq!(ok.to_json(), r#"{"ok":true}"#); + assert_eq!(PreflightResult::parse(ok.to_json().as_bytes()), Ok(ok)); + + let rejected = PreflightResult::rejected("vcpus must be positive"); + assert_eq!( + PreflightResult::parse(rejected.to_json().as_bytes()), + Ok(rejected) + ); + } + + #[test] + fn oversized_or_malformed_output_is_rejected() { + let large = vec![b' '; MAX_PREFLIGHT_OUTPUT_BYTES + 1]; + assert!( + PreflightResult::parse(&large) + .unwrap_err() + .contains("exceeds") + ); + assert!( + PreflightResult::parse(b"fine") + .unwrap_err() + .contains("invalid") + ); + } +} diff --git a/crates/openshell-driver-sdk/src/probe.rs b/crates/openshell-driver-sdk/src/probe.rs new file mode 100644 index 0000000000..a10b13451f --- /dev/null +++ b/crates/openshell-driver-sdk/src/probe.rs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Result of a driver's `probe` subcommand. +//! +//! `openshell-driver- probe` reports on stdout, as one JSON object, +//! whether the driver is usable on this host. The gateway runs it during +//! auto-detection and treats a failure, a timeout, or output larger than +//! [`MAX_PROBE_OUTPUT_BYTES`] as "not available". The probe reports +//! availability only. Which available driver is selected stays with the +//! gateway. + +use serde::{Deserialize, Serialize}; + +/// Largest probe output the gateway accepts. +pub const MAX_PROBE_OUTPUT_BYTES: usize = 4096; + +/// What a driver reports about the host. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProbeResult { + pub available: bool, + /// Why the driver is not usable, for the operator. Omitted when available. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +impl ProbeResult { + #[must_use] + pub const fn available() -> Self { + Self { + available: true, + reason: None, + } + } + + #[must_use] + pub fn unavailable(reason: impl Into) -> Self { + Self { + available: false, + reason: Some(reason.into()), + } + } + + /// Serialize as the single JSON line a driver prints. + #[must_use] + pub fn to_json(&self) -> String { + serde_json::to_string(self).expect("a probe result always serializes") + } + + /// Parse a driver's probe output. + /// + /// # Errors + /// + /// Returns a message when the output is too large or is not a probe result. + pub fn parse(output: &[u8]) -> Result { + if output.len() > MAX_PROBE_OUTPUT_BYTES { + return Err(format!( + "probe output exceeds {MAX_PROBE_OUTPUT_BYTES} bytes" + )); + } + serde_json::from_slice(output).map_err(|error| format!("invalid probe output: {error}")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn results_round_trip_and_omit_the_reason_when_available() { + let available = ProbeResult::available(); + assert_eq!(available.to_json(), r#"{"available":true}"#); + assert_eq!( + ProbeResult::parse(available.to_json().as_bytes()), + Ok(available) + ); + + let missing = ProbeResult::unavailable("no socket"); + assert_eq!( + ProbeResult::parse(missing.to_json().as_bytes()), + Ok(missing) + ); + } + + #[test] + fn oversized_or_malformed_output_is_rejected() { + let large = vec![b' '; MAX_PROBE_OUTPUT_BYTES + 1]; + assert!(ProbeResult::parse(&large).unwrap_err().contains("exceeds")); + assert!(ProbeResult::parse(b"yes").unwrap_err().contains("invalid")); + assert!(ProbeResult::parse(br#"{"available":true,"extra":1}"#).is_err()); + } +} diff --git a/crates/openshell-driver-sdk/tests/fixtures/startup-v1.toml b/crates/openshell-driver-sdk/tests/fixtures/startup-v1.toml new file mode 100644 index 0000000000..d8de427333 --- /dev/null +++ b/crates/openshell-driver-sdk/tests/fixtures/startup-v1.toml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Golden fixture for startup document schema version 1. +# +# Every field the schema defines, optional ones included, must appear here so +# that removing or renaming a field changes this file and shows up in review. + +schema_version = 1 + +[gateway] +bind_socket = "/var/lib/openshell/run/compute-driver.sock" +expected_peer_pid = 4242 +log_level = "info" +gateway_name = "gateway-a" +gateway_port = 8080 +tls_ca = "/etc/openshell/tls/ca.pem" + +[gateway.telemetry.traces] +endpoint = "https://collector.example:4317" +protocol = "grpc" + +[gateway.telemetry.ocsf] +endpoint = "https://collector.example:4318" +protocol = "http/protobuf" + +[gateway.telemetry.agent] +endpoint = "https://collector.example:4319" +protocol = "grpc" + +[gateway.telemetry.collector] +ca_file = "/etc/openshell/otlp/ca.pem" +cert_file = "/etc/openshell/otlp/cert.pem" +key_file = "/etc/openshell/otlp/key.pem" + +[gateway.network_trust] +path = "/var/lib/openshell/trust/bundle.pem" +digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +certificate_count = 3 + +[driver_config] +state_dir = "/var/lib/openshell/vm" +vcpus = 2 + +[driver_config.nested] +key = "value" diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index 57921d4b9a..b96d5b661b 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -54,6 +54,8 @@ openshell-crypto = { workspace = true, optional = true } url = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } +toml = { workspace = true } +openshell-driver-sdk = { path = "../openshell-driver-sdk", features = ["clap"] } oci-client = { version = "0.16", optional = true } libc = "0.2" rustix = { workspace = true, features = ["fs"] } diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index cb9433d08e..c429cfcaa9 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -174,7 +174,7 @@ Select the VM driver with `--compute-driver vm`, `OPENSHELL_COMPUTE_DRIVER=vm`, | `mem_mib` | `2048` | Memory per sandbox, in MiB. | | `overlay_disk_mib` | `4096` | Sparse writable overlay disk size per sandbox, in MiB. | | `krun_log_level` | `1` | libkrun verbosity (0-5). | -| `guest_tls_ca` | unset | Historical key name for the host supervisor's gateway CA certificate. Required when `grpc_endpoint` uses `https://`; never copied into the guest. | +| `guest_tls_ca` | rejected | Not accepted in this table. Set `guest_tls_ca` under `[openshell.gateway]`; the gateway passes it to the driver, which uses it as the host supervisor's gateway CA certificate when the endpoint is `https://`. It is never copied into the guest. | | `https_proxy` | unset | Corporate forward proxy (`http://host:port` or `https://host:port`) that host control chains policy-approved TLS CONNECT egress through. Host-loopback proxy URLs work because control runs on the gateway host. | | `no_proxy` | unset | Comma-separated bypass list for the corporate proxy only. OpenShell policy evaluation still applies. | | `proxy_auth_file` | unset | Gateway-host path to a validated `user:pass` credential file. Staged root-only into the per-sandbox overlay and removed with the sandbox; credentials never enter logs or process arguments. | @@ -339,5 +339,5 @@ so driver choice remains automatic unless the user explicitly overrides it. ## TODOs -- The gateway still configures the driver via CLI args; this will move to a gRPC bootstrap call so the driver interface is uniform across backends. See the `TODO(driver-abstraction)` note in `crates/openshell-gateway/src/vm.rs`. +- The gateway configures the driver with a startup document passed as `--config `; see `crates/openshell-driver-sdk`. The driver validates its own `[openshell.drivers.vm]` table. `openshell-driver-vm preflight --config ` validates a document without starting the driver. - macOS local builds are codesigned by `tasks/scripts/gateway-vm.sh`; the generated Homebrew formula signs the release tarball driver for local installs. diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 528c786b60..24a3550055 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -27,7 +27,6 @@ use crate::rootfs::{ validate_host_supervisor, write_rootfs_image_file, }; use crate::runtime::VmBackend; -use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; use bollard::Docker; use bollard::errors::Error as BollardError; use bollard::models::ContainerCreateBody; @@ -44,6 +43,7 @@ use oci_client::manifest::{ }; use oci_client::secrets::RegistryAuth; use oci_client::{Reference, RegistryOperation}; +use openshell_core::NetworkSupervisorTrustBundle; use openshell_core::UpstreamProxyConfig; use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS; use openshell_core::driver_mounts; @@ -72,9 +72,6 @@ use openshell_core::proto::compute::v1::{ use openshell_core::proto_struct::{ deserialize_optional_non_empty_string_list, struct_to_json_value, }; -use openshell_core::{ - NetworkSupervisorTrustBundle, network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES, -}; use openshell_sandbox_backend::boundary_protocol::{ BoundaryConfig, BoundaryListener, GatewayVerificationKey, SandboxRuntimeDescriptor, SandboxTlsClientConfig, SandboxTlsMaterial, SandboxTlsServerConfig, SandboxTransport, @@ -687,53 +684,16 @@ fn initialize_additional_ca_snapshot(config: &mut VmDriverConfig) -> Result<(), ) { (None, None, None) => None, (Some(path), Some(expected_digest), Some(expected_certificate_count)) => { - if path.as_os_str().is_empty() { - return Err("additional CA artifact path must not be empty".to_string()); - } - if expected_certificate_count == 0 { - return Err("additional CA certificate count must be greater than zero".to_string()); - } - let expected_digest = normalized_additional_ca_digest(expected_digest)?; - let pem = read_gateway_additional_ca_artifact(path)?; - // Deterministic destination-trust generation label, not an - // authenticity proof: the equality check below only detects - // staged-artifact drift; trust comes from the gateway's - // normalization and TLS verification. Classified as a non-security - // identity hash in openshell-crypto/README.md. - let actual_digest = format!("sha256:{:x}", Sha256::digest(&pem)); - if actual_digest != expected_digest { - return Err(format!( - "additional CA artifact '{}' does not match expected digest {}", - path.display(), - expected_digest - )); - } - let actual_certificate_count = normalized_additional_ca_certificate_count(&pem) - .map_err(|error| { - format!( - "additional CA artifact '{}' is not a normalized certificate bundle: {error}", - path.display() - ) - })?; - if actual_certificate_count != expected_certificate_count { - return Err(format!( - "additional CA artifact '{}' has certificate count {}, expected {}", - path.display(), - actual_certificate_count, - expected_certificate_count - )); - } + // The bundle's artifact path records provenance only. Never call + // `verify_artifact` on this retained value: all later launches + // must use these captured immutable bytes rather than rereading + // the mutable gateway-host source path. Some(VmNetworkSupervisorTrustSnapshot { - // The bundle's artifact path records provenance only. Never - // call `verify_artifact` on this retained value: all later - // launches must use these captured immutable bytes rather - // than rereading the mutable gateway-host source path. - bundle: NetworkSupervisorTrustBundle::new( - pem, - actual_certificate_count, + bundle: openshell_driver_sdk::network_trust::load_staged_bundle( + path, expected_digest, - path.clone(), - ), + expected_certificate_count, + )?, }) } _ => { @@ -754,159 +714,6 @@ fn initialize_additional_ca_snapshot(config: &mut VmDriverConfig) -> Result<(), Ok(()) } -/// Require the generation form emitted by gateway normalization. -fn normalized_additional_ca_digest(digest: &str) -> Result { - let Some(hex) = digest.strip_prefix("sha256:") else { - return Err("additional CA digest must use the sha256: prefix".to_string()); - }; - if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err("additional CA digest must be a SHA-256 digest".to_string()); - } - if hex.bytes().any(|byte| byte.is_ascii_uppercase()) { - return Err("additional CA digest must use normalized lowercase hexadecimal".to_string()); - } - Ok(format!("sha256:{hex}")) -} - -/// Read a normalized gateway artifact once without following symlinks. -fn read_gateway_additional_ca_artifact(path: &Path) -> Result, String> { - let metadata = fs::symlink_metadata(path).map_err(|error| { - format!( - "inspect additional CA artifact '{}': {error}", - path.display() - ) - })?; - if !metadata.file_type().is_file() { - return Err(format!( - "additional CA artifact '{}' is not a regular file", - path.display() - )); - } - validate_gateway_additional_ca_artifact_metadata(path, &metadata)?; - - let mut options = fs::OpenOptions::new(); - options.read(true); - #[cfg(unix)] - { - // The pre-open metadata check gives portable diagnostics, while these - // flags ensure an attacker cannot replace it with a symlink, FIFO, or - // blocking special file before the actual one-time read. - options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK); - } - let mut file = options - .open(path) - .map_err(|error| format!("open additional CA artifact '{}': {error}", path.display()))?; - let opened_metadata = file.metadata().map_err(|error| { - format!( - "inspect additional CA artifact '{}': {error}", - path.display() - ) - })?; - if !opened_metadata.file_type().is_file() { - return Err(format!( - "additional CA artifact '{}' is not a regular file", - path.display() - )); - } - validate_gateway_additional_ca_artifact_metadata(path, &opened_metadata)?; - - let capacity = usize::try_from(opened_metadata.len()).map_err(|_| { - format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - ) - })?; - let mut pem = Vec::with_capacity(capacity); - Read::by_ref(&mut file) - .take((MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES + 1) as u64) - .read_to_end(&mut pem) - .map_err(|error| format!("read additional CA artifact '{}': {error}", path.display()))?; - if pem.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES { - return Err(format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - )); - } - Ok(pem) -} - -fn validate_gateway_additional_ca_artifact_metadata( - path: &Path, - metadata: &fs::Metadata, -) -> Result<(), String> { - if metadata.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES as u64 { - return Err(format!( - "additional CA artifact '{}' exceeds the {}-byte limit", - path.display(), - MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES - )); - } - #[cfg(unix)] - if metadata.permissions().mode() & 0o7777 != 0o444 { - return Err(format!( - "additional CA artifact '{}' does not have the required read-only permissions", - path.display() - )); - } - Ok(()) -} - -/// Verify that the bytes are exactly the canonical PEM representation emitted -/// by the gateway's destination-trust normalization boundary, and return its -/// number of certificate blocks. -fn normalized_additional_ca_certificate_count(pem: &[u8]) -> Result { - let text = std::str::from_utf8(pem).map_err(|_| "bundle is not UTF-8 PEM text")?; - let mut remainder = text; - let mut normalized = Vec::with_capacity(pem.len()); - let mut certificate_count = 0_usize; - - while !remainder.is_empty() { - let Some(after_begin) = remainder.strip_prefix("-----BEGIN CERTIFICATE-----\n") else { - return Err("bundle contains material outside canonical certificate blocks"); - }; - remainder = after_begin; - let mut encoded = String::new(); - loop { - let Some(newline) = remainder.find('\n') else { - return Err("certificate block is missing its terminating newline"); - }; - let line = &remainder[..newline]; - remainder = &remainder[newline + 1..]; - if line == "-----END CERTIFICATE-----" { - break; - } - if line.is_empty() || line.len() > 64 { - return Err("certificate block has a non-canonical base64 line"); - } - encoded.push_str(line); - } - let decoded = BASE64_STANDARD - .decode(encoded.as_bytes()) - .map_err(|_| "certificate block contains invalid base64")?; - if decoded.is_empty() { - return Err("certificate block is empty"); - } - normalized.extend_from_slice(b"-----BEGIN CERTIFICATE-----\n"); - let canonical = BASE64_STANDARD.encode(decoded); - for line in canonical.as_bytes().chunks(64) { - normalized.extend_from_slice(line); - normalized.push(b'\n'); - } - normalized.extend_from_slice(b"-----END CERTIFICATE-----\n"); - certificate_count += 1; - } - - if certificate_count == 0 { - return Err("bundle contains no certificate blocks"); - } - if normalized != pem { - return Err("bundle is not canonical normalized PEM"); - } - Ok(certificate_count) -} - /// Write or remove the host-only per-sandbox trust artifact. /// /// The snapshot has already authenticated the bytes against the gateway's @@ -8311,6 +8118,7 @@ fn pulling_layer_detail(metadata: &HashMap) -> Option { mod tests { use super::*; use crate::gpu::allocate_vsock_cid; + use openshell_core::network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES; use openshell_core::progress::{ PROGRESS_ACTIVE_DETAIL_KEY, PROGRESS_ACTIVE_STEP_KEY, PROGRESS_COMPLETE_LABEL_KEY, PROGRESS_COMPLETE_STEP_KEY, diff --git a/crates/openshell-driver-vm/src/lib.rs b/crates/openshell-driver-vm/src/lib.rs index 66041ea034..2dfb666bec 100644 --- a/crates/openshell-driver-vm/src/lib.rs +++ b/crates/openshell-driver-vm/src/lib.rs @@ -37,6 +37,9 @@ mod rootfs; #[cfg(feature = "compute-driver")] mod runtime; +#[cfg(feature = "compute-driver")] +pub mod startup_config; + #[cfg(feature = "compute-driver")] pub use driver::{VmDriver, VmDriverConfig}; #[cfg(feature = "compute-driver")] diff --git a/crates/openshell-driver-vm/src/main.rs b/crates/openshell-driver-vm/src/main.rs index 56f7c9a5d8..c5035781e1 100644 --- a/crates/openshell-driver-vm/src/main.rs +++ b/crates/openshell-driver-vm/src/main.rs @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use clap::Parser; +use clap::parser::ValueSource; +use clap::{ArgMatches, CommandFactory, FromArgMatches, Parser}; use futures::Stream; use miette::{IntoDiagnostic, Result}; use openshell_core::VERSION; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; use openshell_core::sandbox_env::SupervisorOtlpArgs; +use openshell_driver_sdk::StartupDocument; +use openshell_driver_vm::startup_config::VmComputeConfig; #[cfg(target_os = "macos")] use openshell_driver_vm::{VM_RUNTIME_DIR_ENV, configured_runtime_dir}; use openshell_driver_vm::{ @@ -26,6 +29,11 @@ use tracing::info; #[command(version = VERSION)] #[allow(clippy::struct_excessive_bools)] struct Args { + /// Gateway startup document (TOML). It supplies the settings the gateway + /// otherwise passes as flags, and flags it covers cannot be combined with it. + #[arg(long)] + config: Option, + /// Operator-owned JSON policy; omitted means driver config disabled and labels required. #[arg( long, @@ -275,9 +283,35 @@ struct Args { vm_mount: Vec, } +/// `preflight --config ` validates the startup document's configuration +/// and reports on stdout. It starts nothing and creates no state. +fn run_preflight(arguments: &[std::ffi::OsString]) -> ! { + use openshell_driver_sdk::preflight::PreflightResult; + + let result = match arguments { + [flag, path] if flag == "--config" => { + match parse_args_from([ + std::ffi::OsString::from("openshell-driver-vm"), + flag.clone(), + path.clone(), + ]) { + Ok(_) => PreflightResult::ok(), + Err(error) => PreflightResult::rejected(error.message()), + } + } + _ => PreflightResult::rejected("usage: preflight --config "), + }; + println!("{}", result.to_json()); + std::process::exit(0); +} + #[tokio::main] async fn main() -> Result<()> { - let args = Args::parse(); + let arguments: Vec<_> = std::env::args_os().skip(1).collect(); + if arguments.first().is_some_and(|arg| arg == "preflight") { + run_preflight(&arguments[1..]); + } + let args = parse_args().map_err(|err| miette::miette!("{err}"))?; if let Some(request) = args.internal_prepare_image { openshell_driver_vm::driver::run_image_preparation_worker(&request) .await @@ -409,6 +443,191 @@ async fn main() -> Result<()> { result } +/// Flags the startup document supplies. Giving one on the command line +/// together with `--config` is an error, so precedence is never ambiguous. +const FLAGS_COVERED_BY_CONFIG: &[&str] = &[ + "admission_config_json", + "bind_socket", + "expected_peer_pid", + "log_level", + "gateway_name", + "grpc_endpoint", + "guest_tls_ca", + "upstream_proxy", + "upstream_no_proxy", + "upstream_proxy_auth_file", + "upstream_proxy_auth_allow_insecure", + "upstream_proxy_connect_by_hostname", + "upstream_proxy_ca_bundle", + "additional_ca_bundle", + "additional_ca_digest", + "additional_ca_certificate_count", + "endpoint", + "protocol", + "ca_file", + "cert_file", + "key_file", + "ocsf_endpoint", + "ocsf_protocol", + "agent_endpoint", + "agent_protocol", + "state_dir", + "default_image", + "bootstrap_image", + "krun_log_level", + "vcpus", + "mem_mib", + "overlay_disk_mib", + "sandbox_uid", + "sandbox_gid", + "rootfs_tar_staging_dir", + "rootfs_tar_max_bytes", + "enable_bind_mounts", + "provider_spiffe_workload_api_tcp_endpoint", + "provider_spiffe_allow_guest_tcp", +]; + +#[derive(Debug)] +enum ArgsError { + /// A command-line error, including `--help` and `--version`, which clap + /// prints and exits for. + Clap(clap::Error), + /// A problem with the startup document or its combination with flags. + Config(String), +} + +impl ArgsError { + fn message(&self) -> String { + match self { + Self::Clap(error) => error.to_string(), + Self::Config(message) => message.clone(), + } + } +} + +fn parse_args() -> std::result::Result { + parse_args_from(std::env::args_os()).map_err(|error| match error { + ArgsError::Clap(error) => error.exit(), + ArgsError::Config(message) => message, + }) +} + +fn parse_args_from(arguments: I) -> std::result::Result +where + I: IntoIterator, + T: Into + Clone, +{ + let command = Args::command(); + let matches = command + .clone() + .try_get_matches_from(arguments) + .map_err(ArgsError::Clap)?; + let mut args = Args::from_arg_matches(&matches).map_err(ArgsError::Clap)?; + if let Some(path) = args.config.clone() { + if let Some(flag) = flag_covered_by_config(&command, &matches) { + return Err(ArgsError::Config(format!( + "--{flag} cannot be combined with --config; the startup document supplies it" + ))); + } + let document = StartupDocument::read(&path).map_err(ArgsError::Config)?; + apply_startup_document(&mut args, &document).map_err(ArgsError::Config)?; + } + Ok(args) +} + +/// The first flag given on the command line that the startup document covers. +fn flag_covered_by_config(command: &clap::Command, matches: &ArgMatches) -> Option { + command + .get_arguments() + .filter(|arg| FLAGS_COVERED_BY_CONFIG.contains(&arg.get_id().as_str())) + .find(|arg| matches.value_source(arg.get_id().as_str()) == Some(ValueSource::CommandLine)) + .map(|arg| { + arg.get_long() + .map_or_else(|| arg.get_id().to_string(), str::to_string) + }) +} + +/// Overlay the startup document onto the parsed flags. The document is +/// authoritative for everything it carries; a driver setting it leaves out +/// keeps its flag, environment, or default value. +fn apply_startup_document( + args: &mut Args, + document: &StartupDocument, +) -> std::result::Result<(), String> { + let gateway = &document.gateway; + args.bind_socket = Some(gateway.bind_socket.clone()); + args.expected_peer_pid = Some(gateway.expected_peer_pid); + args.log_level.clone_from(&gateway.log_level); + args.gateway_name = Some(gateway.gateway_name.clone()); + args.guest_tls_ca.clone_from(&gateway.tls_ca); + + gateway.telemetry.apply_to(&mut args.otlp); + + if let Some(trust) = &gateway.network_trust { + args.additional_ca_bundle = Some(trust.path.clone()); + args.additional_ca_digest = Some(trust.digest.clone()); + args.additional_ca_certificate_count = Some( + usize::try_from(trust.certificate_count) + .map_err(|_| "network trust certificate count is too large".to_string())?, + ); + } + + let mut config = VmComputeConfig::from_document(document)?; + if config.state_dir.as_os_str().is_empty() { + config.state_dir = VmComputeConfig::default_state_dir(); + } + // The gateway's own listener is the default endpoint for sandboxes. It has + // a gateway CA exactly when it serves TLS. + if config.grpc_endpoint.trim().is_empty() { + let scheme = if gateway.tls_ca.is_some() { + "https" + } else { + "http" + }; + config.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", gateway.gateway_port); + } + config + .validate_configuration() + .map_err(|error| error.to_string())?; + // The CA authenticates the gateway for an https endpoint only. + if !config.grpc_endpoint.starts_with("https://") { + args.guest_tls_ca = None; + } + + args.admission_config_json = openshell_core::resource_admission::DriverAdmissionConfig { + allow_driver_config: config.allow_driver_config, + resource_admission: config.resource_admission.clone(), + }; + args.grpc_endpoint = Some(config.grpc_endpoint); + let proxy = config.upstream_proxy; + args.upstream_proxy = proxy.https_proxy; + args.upstream_no_proxy = proxy.no_proxy; + args.upstream_proxy_auth_file = proxy.proxy_auth_file; + args.upstream_proxy_auth_allow_insecure = proxy.proxy_auth_allow_insecure == Some(true); + args.upstream_proxy_connect_by_hostname = proxy.proxy_connect_by_hostname == Some(true); + args.upstream_proxy_ca_bundle = config.proxy_ca_bundle; + args.state_dir = config.state_dir; + if !config.default_image.trim().is_empty() { + args.default_image = config.default_image; + } + if !config.bootstrap_image.trim().is_empty() { + args.bootstrap_image = config.bootstrap_image; + } + args.krun_log_level = config.krun_log_level; + args.vcpus = config.vcpus; + args.mem_mib = config.mem_mib; + args.overlay_disk_mib = config.overlay_disk_mib; + args.sandbox_uid = config.sandbox_uid; + args.sandbox_gid = config.sandbox_gid; + args.rootfs_tar_staging_dir = config.rootfs_tar_staging_dir; + args.rootfs_tar_max_bytes = config.rootfs_tar_max_bytes; + args.enable_bind_mounts = config.enable_bind_mounts; + args.provider_spiffe_workload_api_tcp_endpoint = + config.provider_spiffe_workload_api_tcp_endpoint; + args.provider_spiffe_allow_guest_tcp = config.provider_spiffe_allow_guest_tcp; + Ok(()) +} + async fn shutdown_signal() { let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) .expect("install SIGTERM handler"); @@ -784,11 +1003,120 @@ fn maybe_reexec_internal_vm_with_runtime_env() -> Result<()> { #[cfg(test)] mod tests { use super::{ - Args, ComputeDriverListenMode, PeerCredentials, authorize_peer_credentials, - compute_driver_listen_mode, parse_vm_mount_arg, + Args, ComputeDriverListenMode, PeerCredentials, StartupDocument, apply_startup_document, + authorize_peer_credentials, compute_driver_listen_mode, parse_args_from, + parse_vm_mount_arg, }; use clap::Parser; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; + + const VM_STARTUP_FIXTURE: &str = include_str!("../tests/fixtures/startup-vm.toml"); + + #[test] + fn startup_document_supplies_the_settings_the_gateway_used_to_pass_as_flags() { + let document = StartupDocument::parse(VM_STARTUP_FIXTURE).unwrap(); + let mut args = Args::parse_from(["openshell-driver-vm"]); + apply_startup_document(&mut args, &document).unwrap(); + + assert_eq!( + args.bind_socket.as_deref(), + Some(Path::new("/var/lib/openshell/vm/run/compute-driver.sock")) + ); + assert_eq!(args.expected_peer_pid, Some(4242)); + assert_eq!(args.log_level, "debug"); + assert_eq!(args.gateway_name.as_deref(), Some("gateway-a")); + assert_eq!( + args.grpc_endpoint.as_deref(), + Some("https://127.0.0.1:8080") + ); + assert_eq!( + args.guest_tls_ca.as_deref(), + Some(Path::new("/etc/openshell/tls/ca.pem")) + ); + assert!(args.admission_config_json.allow_driver_config); + assert_eq!( + args.otlp.endpoint.as_deref(), + Some("https://collector.example:4317") + ); + assert_eq!( + args.otlp.ocsf_protocol, + openshell_core::sandbox_env::OtlpProtocol::HttpProtobuf + ); + assert_eq!( + args.otlp.agent_endpoint.as_deref(), + Some("https://collector.example:4319") + ); + assert_eq!( + args.otlp.key_file.as_deref(), + Some(Path::new("/etc/openshell/otlp/key.pem")) + ); + assert_eq!( + args.upstream_proxy.as_deref(), + Some("http://proxy.example:3128") + ); + assert!(args.upstream_proxy_auth_allow_insecure); + assert!(args.upstream_proxy_connect_by_hostname); + assert_eq!( + args.upstream_proxy_ca_bundle.as_deref(), + Some(Path::new("/etc/openshell/proxy-ca.pem")) + ); + assert_eq!(args.additional_ca_certificate_count, Some(3)); + assert_eq!(args.state_dir, Path::new("/var/lib/openshell/vm")); + assert_eq!(args.vcpus, 4); + assert_eq!(args.mem_mib, 4096); + assert_eq!(args.overlay_disk_mib, 8192); + assert_eq!(args.sandbox_uid, Some(2000)); + assert_eq!(args.rootfs_tar_max_bytes, Some(1_073_741_824)); + assert!(args.enable_bind_mounts); + assert!(args.provider_spiffe_allow_guest_tcp); + } + + /// A flag renamed in `Args` must also be renamed in the list, or the + /// conflict check silently stops guarding it. + #[test] + fn every_flag_covered_by_config_is_a_real_argument() { + let command = ::command(); + for name in crate::FLAGS_COVERED_BY_CONFIG { + assert!( + command.get_arguments().any(|arg| arg.get_id() == *name), + "{name} is not an argument" + ); + } + } + + #[test] + fn config_cannot_be_combined_with_a_flag_it_covers() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("startup.toml"); + std::fs::write(&path, VM_STARTUP_FIXTURE).unwrap(); + let path = path.to_str().unwrap(); + + let error = parse_args_from(["openshell-driver-vm", "--config", path, "--vcpus", "8"]) + .unwrap_err() + .message(); + assert!( + error.contains("--vcpus") && error.contains("--config"), + "{error}" + ); + + let args = parse_args_from(["openshell-driver-vm", "--config", path]).unwrap(); + assert_eq!(args.vcpus, 4); + } + + #[test] + fn config_with_another_schema_version_is_refused_naming_both() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("startup.toml"); + std::fs::write( + &path, + VM_STARTUP_FIXTURE.replace("schema_version = 1", "schema_version = 9"), + ) + .unwrap(); + let error = parse_args_from(["openshell-driver-vm", "--config", path.to_str().unwrap()]) + .unwrap_err() + .message(); + assert!(error.contains('9') && error.contains('1'), "{error}"); + } #[test] fn corporate_proxy_flags_parse_into_driver_settings() { diff --git a/crates/openshell-driver-vm/src/startup_config.rs b/crates/openshell-driver-vm/src/startup_config.rs new file mode 100644 index 0000000000..065f694dd3 --- /dev/null +++ b/crates/openshell-driver-vm/src/startup_config.rs @@ -0,0 +1,370 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The VM driver's configuration and its view of the gateway startup document. +//! +//! The document's `[gateway]` table is defined by `openshell-driver-sdk`. Its +//! `[driver_config]` table is the operator's `[openshell.drivers.vm]` table, +//! passed through unchanged; [`VmComputeConfig`] is what the driver accepts in +//! it, and the driver validates it at startup. + +use std::path::PathBuf; + +use openshell_core::{Error, Result, UpstreamProxyConfig}; +use openshell_driver_sdk::StartupDocument; + +/// The VM driver's own configuration: the operator's `[openshell.drivers.vm]` +/// table, which the gateway passes through as the startup document's +/// `driver_config`. The driver validates it at startup. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct VmComputeConfig { + pub allow_driver_config: bool, + pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, + /// Working directory for VM driver sandbox state. + pub state_dir: PathBuf, + + /// Default sandbox image the driver should use when a request omits one. + pub default_image: String, + + /// Gateway gRPC endpoint the sandbox guest connects back to. + pub grpc_endpoint: String, + + /// Bootstrap image used to boot and prepare VM sandbox target images. + pub bootstrap_image: String, + + /// libkrun log level used by the VM driver helper. + pub krun_log_level: u32, + + /// Default vCPU count for VM sandboxes. + pub vcpus: u8, + + /// Default memory allocation for VM sandboxes, in MiB. + pub mem_mib: u32, + + /// Writable overlay disk size for each VM sandbox, in MiB. + pub overlay_disk_mib: u64, + + /// Optional UID override for the VM guest sandbox account. + pub sandbox_uid: Option, + + /// Optional GID override for the VM guest sandbox account. + pub sandbox_gid: Option, + + /// Directory shared with the gateway for request-scoped rootfs tar staging. + pub rootfs_tar_staging_dir: Option, + + /// Maximum accepted rootfs tar size, in bytes, before and after decompression. + pub rootfs_tar_max_bytes: Option, + + /// Corporate forward-proxy settings passed to the VM driver. Flattening + /// preserves the shared local-driver TOML field names. + #[serde(flatten)] + pub upstream_proxy: UpstreamProxyConfig, + + /// Path on the gateway host to a PEM CA bundle trusted for the corporate + /// proxy and for server certificates re-signed by a TLS-intercepting proxy. + pub proxy_ca_bundle: Option, + + /// Explicit guest-reachable SPIFFE Workload API TCP listener. VM guests + /// cannot receive a host UNIX socket, so this requires acknowledgement. + pub provider_spiffe_workload_api_tcp_endpoint: Option, + #[serde(default)] + pub provider_spiffe_allow_guest_tcp: bool, + + /// Allow bind-mounting host directories into VM sandboxes. + #[serde(default)] + pub enable_bind_mounts: bool, +} + +impl VmComputeConfig { + /// Default working directory for VM driver state. + #[must_use] + pub fn default_state_dir() -> PathBuf { + openshell_core::paths::openshell_state_dir().map_or_else( + |_| PathBuf::from("target/openshell-vm-driver"), + |dir| dir.join("vm-driver"), + ) + } + + /// Default libkrun log level. + #[must_use] + pub const fn default_krun_log_level() -> u32 { + 1 + } + + /// Default vCPU count. + #[must_use] + pub const fn default_vcpus() -> u8 { + 2 + } + + /// Default memory allocation, in MiB. + #[must_use] + pub const fn default_mem_mib() -> u32 { + 2048 + } + + /// Default writable overlay disk size, in MiB. + #[must_use] + pub const fn default_overlay_disk_mib() -> u64 { + 4096 + } + + /// Validate startup configuration without resolving binaries, creating + /// state directories, spawning a process, or connecting a socket. + pub fn validate_configuration(&self) -> Result<()> { + self.resource_admission.validate().map_err(Error::config)?; + if self.grpc_endpoint.trim().is_empty() { + return Err(Error::config( + "grpc_endpoint is required when using the vm compute driver", + )); + } + if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { + return Err(Error::config( + "bootstrap_image or default_image is required when using the vm compute driver; sandbox images cannot be used as VM bootstrap images", + )); + } + validate_vm_sandbox_identity(self)?; + if self + .rootfs_tar_staging_dir + .as_ref() + .is_some_and(|path| path.as_os_str().is_empty()) + { + return Err(Error::config( + "rootfs_tar_staging_dir must not be empty when set", + )); + } + if self.rootfs_tar_max_bytes == Some(0) { + return Err(Error::config( + "rootfs_tar_max_bytes must be greater than zero when set", + )); + } + self.validate_proxy_config()?; + if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { + openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( + endpoint, + self.provider_spiffe_allow_guest_tcp, + ) + .map_err(Error::config)?; + } else if self.provider_spiffe_allow_guest_tcp { + return Err(Error::config( + "provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured", + )); + } + Ok(()) + } + + fn validate_proxy_config(&self) -> Result<()> { + self.upstream_proxy.validate().map_err(Error::config)?; + if let Some(path) = self.proxy_ca_bundle.as_ref() { + if path.as_os_str().is_empty() { + return Err(Error::config("proxy_ca_bundle must not be empty when set")); + } + if self.upstream_proxy.https_proxy.is_none() { + return Err(Error::config( + "proxy_ca_bundle is set but no https_proxy is configured", + )); + } + } + Ok(()) + } +} + +impl Default for VmComputeConfig { + fn default() -> Self { + Self { + state_dir: Self::default_state_dir(), + allow_driver_config: false, + resource_admission: + openshell_core::resource_admission::ResourceAdmissionConfig::default(), + default_image: openshell_core::image::default_sandbox_image(), + grpc_endpoint: String::new(), + bootstrap_image: String::new(), + krun_log_level: Self::default_krun_log_level(), + vcpus: Self::default_vcpus(), + mem_mib: Self::default_mem_mib(), + overlay_disk_mib: Self::default_overlay_disk_mib(), + sandbox_uid: None, + sandbox_gid: None, + rootfs_tar_staging_dir: None, + rootfs_tar_max_bytes: None, + upstream_proxy: UpstreamProxyConfig::default(), + proxy_ca_bundle: None, + provider_spiffe_workload_api_tcp_endpoint: None, + provider_spiffe_allow_guest_tcp: false, + enable_bind_mounts: false, + } + } +} + +impl VmComputeConfig { + /// Decode the document's `driver_config` table. + /// + /// # Errors + /// + /// Returns a message naming the unknown or invalid key. + pub fn from_document(document: &StartupDocument) -> std::result::Result { + toml::Value::Table(document.driver_config.clone()) + .try_into() + .map_err(|error: toml::de::Error| { + format!("invalid [driver_config] in startup document: {error}") + }) + } +} + +pub fn validate_vm_sandbox_identity(config: &VmComputeConfig) -> Result<()> { + let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; + for (field, value) in [ + ("sandbox_uid", config.sandbox_uid), + ("sandbox_gid", config.sandbox_gid), + ] { + if let Some(value) = value + && !range.contains(&value) + { + return Err(Error::config(format!( + "{field} {value} is outside the allowed range [{}, {}]", + openshell_policy::MIN_SANDBOX_UID, + openshell_policy::MAX_SANDBOX_UID + ))); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const FIXTURE: &str = include_str!("../tests/fixtures/startup-vm.toml"); + + #[test] + fn the_fixture_driver_config_deserializes_and_validates() { + let document = StartupDocument::parse(FIXTURE).unwrap(); + let config = VmComputeConfig::from_document(&document).unwrap(); + config.validate_configuration().unwrap(); + assert_eq!(config.vcpus, 4); + assert!(config.allow_driver_config); + assert_eq!(config.grpc_endpoint, "https://127.0.0.1:8080"); + } + + #[test] + fn unknown_driver_config_keys_are_rejected() { + let mut document = StartupDocument::parse(FIXTURE).unwrap(); + document.driver_config = toml::from_str("surprise = 1").unwrap(); + let error = VmComputeConfig::from_document(&document).unwrap_err(); + assert!(error.contains("surprise"), "{error}"); + } + + #[test] + fn keys_the_gateway_owns_are_rejected_in_driver_config() { + for key in ["guest_tls_ca", "driver_dir"] { + let mut document = StartupDocument::parse(FIXTURE).unwrap(); + document.driver_config = toml::from_str(&format!("{key} = '/x'")).unwrap(); + assert!(VmComputeConfig::from_document(&document).is_err(), "{key}"); + } + } + + #[test] + fn vm_uses_nvidia_ubuntu_default_image() { + assert_eq!( + VmComputeConfig::default().default_image, + openshell_core::image::DEFAULT_SANDBOX_BASE_IMAGE + ); + } + + #[test] + fn vm_gateway_requires_a_trusted_bootstrap_image_source() { + let config = VmComputeConfig { + grpc_endpoint: "http://127.0.0.1:50051".to_string(), + default_image: String::new(), + bootstrap_image: String::new(), + ..Default::default() + }; + let error = config + .validate_configuration() + .expect_err("the gateway must reject an empty bootstrap configuration"); + assert!(error.to_string().contains("sandbox images cannot be used")); + + VmComputeConfig { + default_image: "openshell/sandbox:default".to_string(), + ..config.clone() + } + .validate_configuration() + .expect("the operator-controlled default image is a valid fallback"); + + VmComputeConfig { + bootstrap_image: "openshell/sandbox-bootstrap:latest".to_string(), + ..config + } + .validate_configuration() + .expect("an explicit bootstrap image is valid"); + } + + #[test] + fn invalid_corporate_proxy_config_is_rejected_before_the_driver_starts() { + let err = UpstreamProxyConfig { + https_proxy: Some("socks5://proxy.corp.com:1080".to_string()), + ..Default::default() + } + .validate() + .expect_err("only http:// and https:// proxies are supported"); + assert!(err.contains("https_proxy"), "{err}"); + + VmComputeConfig { + proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")), + ..Default::default() + } + .validate_proxy_config() + .expect_err("a CA bundle without a proxy URL must fail closed"); + + VmComputeConfig { + upstream_proxy: UpstreamProxyConfig { + https_proxy: Some("http://proxy.corp.com:8080".to_string()), + ..Default::default() + }, + ..Default::default() + } + .validate_proxy_config() + .expect("a lone proxy URL is a complete configuration"); + } + + #[test] + fn vm_gateway_toml_accepts_rootfs_tar_settings() { + let config: VmComputeConfig = toml::from_str( + r#" + grpc_endpoint = "http://127.0.0.1:50051" + rootfs_tar_staging_dir = "/var/lib/openshell/rootfs-tar-staging" + rootfs_tar_max_bytes = 1073741824 + "#, + ) + .expect("schema-v2 VM rootfs tar settings must deserialize"); + config + .validate_configuration() + .expect("rootfs tar settings must pass static validation"); + } + + #[test] + fn vm_gateway_rejects_zero_rootfs_tar_limit() { + let config = VmComputeConfig { + grpc_endpoint: "http://127.0.0.1:50051".to_string(), + rootfs_tar_max_bytes: Some(0), + ..Default::default() + }; + + let error = config + .validate_configuration() + .expect_err("a zero rootfs tar limit must fail before driver startup"); + assert!(error.to_string().contains("rootfs_tar_max_bytes")); + } + + #[test] + fn vm_gateway_config_rejects_root_identity() { + let config = VmComputeConfig { + sandbox_uid: Some(0), + ..Default::default() + }; + let error = validate_vm_sandbox_identity(&config).expect_err("root UID must fail"); + assert!(error.to_string().contains("sandbox_uid 0")); + } +} diff --git a/crates/openshell-driver-vm/tests/fixtures/startup-vm.toml b/crates/openshell-driver-vm/tests/fixtures/startup-vm.toml new file mode 100644 index 0000000000..8fc93832fc --- /dev/null +++ b/crates/openshell-driver-vm/tests/fixtures/startup-vm.toml @@ -0,0 +1,68 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Startup document the gateway writes for the VM driver, with every VM setting +# populated. The gateway's conversion test and the driver's overlay test both +# read this file, so a key one side stops writing or reading fails a test. + +schema_version = 1 + +[gateway] +bind_socket = "/var/lib/openshell/vm/run/compute-driver.sock" +expected_peer_pid = 4242 +log_level = "debug" +gateway_name = "gateway-a" +gateway_port = 8080 +tls_ca = "/etc/openshell/tls/ca.pem" + +[gateway.telemetry.traces] +endpoint = "https://collector.example:4317" +protocol = "grpc" + +[gateway.telemetry.ocsf] +endpoint = "https://collector.example:4318" +protocol = "http/protobuf" + +[gateway.telemetry.agent] +endpoint = "https://collector.example:4319" +protocol = "grpc" + +[gateway.telemetry.collector] +ca_file = "/etc/openshell/otlp/ca.pem" +cert_file = "/etc/openshell/otlp/cert.pem" +key_file = "/etc/openshell/otlp/key.pem" + +[gateway.network_trust] +path = "/var/lib/openshell/trust/bundle.pem" +digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" +certificate_count = 3 + +[driver_config] +allow_driver_config = true +grpc_endpoint = "https://127.0.0.1:8080" +https_proxy = "http://proxy.example:3128" +no_proxy = "localhost,127.0.0.1" +proxy_auth_file = "/etc/openshell/proxy-auth" +proxy_auth_allow_insecure = true +proxy_connect_by_hostname = true +proxy_ca_bundle = "/etc/openshell/proxy-ca.pem" +state_dir = "/var/lib/openshell/vm" +default_image = "openshell/sandbox:default" +bootstrap_image = "openshell/sandbox-bootstrap:latest" +krun_log_level = 2 +vcpus = 4 +mem_mib = 4096 +overlay_disk_mib = 8192 +sandbox_uid = 2000 +sandbox_gid = 3000 +rootfs_tar_staging_dir = "/var/lib/openshell/rootfs-staging" +rootfs_tar_max_bytes = 1073741824 +enable_bind_mounts = true +provider_spiffe_workload_api_tcp_endpoint = "tcp:10.0.0.5:8081" +provider_spiffe_allow_guest_tcp = true + +[driver_config.resource_admission] +enabled = true + +[driver_config.resource_admission.required_labels] +"openshell.ai/sandbox-attachable" = "true" diff --git a/crates/openshell-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml index 86249568ba..e0d1b38504 100644 --- a/crates/openshell-gateway/Cargo.toml +++ b/crates/openshell-gateway/Cargo.toml @@ -15,18 +15,20 @@ name = "openshell-gateway" path = "src/main.rs" [dependencies] +tempfile = "3" serde_json = { workspace = true } openshell-core = { path = "../openshell-core", default-features = false } +openshell-driver-sdk = { path = "../openshell-driver-sdk" } openshell-server = { path = "../openshell-server", default-features = false } openshell-otel = { path = "../openshell-otel", optional = true } async-trait = "0.1" miette = { workspace = true } tokio = { workspace = true } +toml = { workspace = true } [target.'cfg(not(target_os = "windows"))'.dependencies] openshell-driver-docker = { path = "../openshell-driver-docker", optional = true } openshell-driver-kubernetes = { path = "../openshell-driver-kubernetes", optional = true } -openshell-driver-podman = { path = "../openshell-driver-podman", optional = true } openshell-policy = { path = "../openshell-policy", optional = true } hyper-util = { workspace = true, optional = true } nix = { workspace = true, optional = true } @@ -51,7 +53,7 @@ in-tree-compute-drivers = [ compute-driver-mxc = ["dep:openshell-driver-mxc"] compute-driver-docker = ["dep:openshell-driver-docker", "dep:openshell-otel"] compute-driver-kubernetes = ["dep:openshell-driver-kubernetes", "dep:openshell-otel"] -compute-driver-podman = ["dep:openshell-driver-podman", "dep:openshell-otel"] +compute-driver-podman = ["dep:openshell-otel"] compute-driver-vm = [ "dep:openshell-policy", "dep:openshell-otel", @@ -81,5 +83,3 @@ workspace = true [dev-dependencies] openshell-crypto = { workspace = true, default-features = false, features = ["aws-lc"] } rcgen = { workspace = true } -tempfile = "3" -toml = { workspace = true } diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs new file mode 100644 index 0000000000..ff83945d4c --- /dev/null +++ b/crates/openshell-gateway/src/launcher.rs @@ -0,0 +1,1341 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Generic launcher for compute drivers that run as gateway-managed +//! subprocesses. +//! +//! The launcher resolves a driver binary, prepares a private run directory, +//! writes the driver's startup document there, starts the driver with +//! `--config `, waits for its Unix domain socket, and returns a gRPC +//! `Channel` plus a [`ManagedDriverProcess`] handle that reaps the subprocess +//! and cleans up the socket on drop. Each driver supplies its own name, binary, +//! and startup document; the driver owns and validates its configuration. + +#[cfg(unix)] +use hyper_util::rt::TokioIo; +#[cfg(unix)] +use openshell_core::proto::compute::v1::{ + GetCapabilitiesRequest, compute_driver_client::ComputeDriverClient, +}; +use openshell_core::{Error, Result}; +#[cfg(unix)] +use openshell_otel::TraceContextInterceptor; +use openshell_server::AcquiredRemoteDriverEndpoint; +use openshell_server::config_file::OtlpConfig; +#[cfg(unix)] +use openshell_server::{DriverProcessState, ManagedDriverProcess}; +#[cfg(unix)] +use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; +#[cfg(unix)] +use std::path::Path; +use std::path::PathBuf; +#[cfg(unix)] +use std::{io::ErrorKind, process::Stdio, sync::Arc, time::Duration}; +#[cfg(unix)] +use tokio::net::UnixStream; +#[cfg(unix)] +use tokio::process::Command; +use tonic::transport::Channel; +#[cfg(unix)] +use tonic::transport::Endpoint; +#[cfg(unix)] +use tower::service_fn; + +const COMPUTE_DRIVER_SOCKET_RUN_DIR: &str = "run"; +const COMPUTE_DRIVER_SOCKET_NAME: &str = "compute-driver.sock"; + +/// A driver binary the gateway launches and where it keeps its private run +/// directory. +#[derive(Debug, Clone, Copy)] +pub struct DriverProcess<'a> { + /// Short driver name used in messages and telemetry, such as `vm`. + pub name: &'a str, + /// File name of the driver binary, such as `openshell-driver-vm`. + pub binary_name: &'a str, + /// Operator-configured directory to search before the conventional ones. + pub driver_dir: Option<&'a Path>, + /// Config key that sets `driver_dir`, named in the not-found message. + pub driver_dir_key: Option<&'a str>, + /// Directory whose `run/` subdirectory holds the socket and startup + /// document. + pub state_dir: &'a Path, +} + +/// Resolve the driver binary path. +/// +/// Resolution order: +/// 1. `{driver_dir}/{binary_name}`, when the operator configures a `driver_dir`. +/// 2. Conventional install directories: +/// `~/.local/libexec/openshell`, `/usr/libexec/openshell`, +/// `/usr/local/libexec/openshell`, `/usr/local/libexec`. +/// 3. Sibling of the gateway's own executable (last-resort fallback so +/// local development builds still work out of the box). +pub fn resolve_driver_bin(driver: &DriverProcess<'_>) -> Result { + let mut searched: Vec = Vec::new(); + + // 1. Configured driver directory, or the conventional install locations + // when no explicit override is configured. + for dir in resolve_driver_search_dirs(driver.driver_dir) { + let candidate = dir.join(driver.binary_name); + if candidate.is_file() { + return Ok(candidate); + } + push_unique_path(&mut searched, candidate); + } + + // 2. Sibling-of-gateway fallback. + let current_exe = std::env::current_exe() + .map_err(|e| Error::config(format!("failed to resolve current executable: {e}")))?; + let Some(parent) = current_exe.parent() else { + return Err(Error::config(format!( + "current executable '{}' has no parent directory", + current_exe.display() + ))); + }; + let sibling = parent.join(driver.binary_name); + if sibling.is_file() { + return Ok(sibling); + } + push_unique_path(&mut searched, sibling); + + let searched_display = searched + .iter() + .map(|p| format!("'{}'", p.display())) + .collect::>() + .join(", "); + let name = driver.name; + let configured = driver + .driver_dir_key + .map_or_else(String::new, |key| format!("under {key}, ")); + Err(Error::config(format!( + "{name} compute driver binary not found (searched {searched_display}); install it {configured}in a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{{,/openshell}}, or place it next to the gateway binary" + ))) +} + +fn resolve_driver_search_dirs(driver_dir: Option<&Path>) -> Vec { + driver_dir.map(Path::to_path_buf).map_or_else( + || { + let mut dirs = Vec::new(); + if let Ok(current_exe) = std::env::current_exe() + && let Some(prefix) = current_exe.parent().and_then(Path::parent) + { + push_unique_path(&mut dirs, prefix.join("libexec")); + push_unique_path(&mut dirs, prefix.join("libexec").join("openshell")); + } + for dir in default_driver_search_dirs(std::env::var_os("HOME").map(PathBuf::from)) { + push_unique_path(&mut dirs, dir); + } + dirs + }, + |dir| vec![dir], + ) +} + +fn default_driver_search_dirs(home: Option) -> Vec { + let mut dirs = Vec::new(); + if let Some(home) = home { + dirs.push(home.join(".local").join("libexec").join("openshell")); + } + push_unique_path(&mut dirs, PathBuf::from("/usr/libexec/openshell")); + push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec/openshell")); + push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec")); + dirs +} + +fn push_unique_path(paths: &mut Vec, path: PathBuf) { + if !paths.iter().any(|existing| existing == &path) { + paths.push(path); + } +} + +/// Path of the Unix domain socket the driver will listen on. +pub fn socket_path(driver: &DriverProcess<'_>) -> PathBuf { + driver + .state_dir + .join(COMPUTE_DRIVER_SOCKET_RUN_DIR) + .join(COMPUTE_DRIVER_SOCKET_NAME) +} + +#[cfg(unix)] +fn prepare_socket_path(driver: &DriverProcess<'_>, socket_path: &Path) -> Result<()> { + let expected_uid = current_euid(); + prepare_state_dir(driver.state_dir, expected_uid)?; + let parent = socket_path.parent().ok_or_else(|| { + Error::execution(format!( + "compute driver socket path '{}' has no parent directory", + socket_path.display() + )) + })?; + prepare_private_socket_dir(parent, expected_uid)?; + remove_stale_socket(socket_path, expected_uid) +} + +#[cfg(unix)] +fn current_euid() -> u32 { + rustix::process::geteuid().as_raw() +} + +#[cfg(unix)] +fn prepare_state_dir(state_dir: &Path, expected_uid: u32) -> Result<()> { + std::fs::create_dir_all(state_dir).map_err(|err| { + Error::execution(format!( + "failed to create driver state dir '{}': {err}", + state_dir.display() + )) + })?; + let metadata = checked_directory_metadata(state_dir, expected_uid, "driver state dir")?; + let mode = metadata.permissions().mode() & 0o777; + if mode != 0o700 { + std::fs::set_permissions(state_dir, std::fs::Permissions::from_mode(0o700)).map_err( + |err| { + Error::execution(format!( + "failed to restrict driver state dir '{}': {err}", + state_dir.display() + )) + }, + )?; + } + Ok(()) +} + +#[cfg(unix)] +fn prepare_private_socket_dir(socket_dir: &Path, expected_uid: u32) -> Result<()> { + std::fs::create_dir_all(socket_dir).map_err(|err| { + Error::execution(format!( + "failed to create compute driver socket dir '{}': {err}", + socket_dir.display() + )) + })?; + let _ = checked_directory_metadata(socket_dir, expected_uid, "compute driver socket dir")?; + std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)).map_err(|err| { + Error::execution(format!( + "failed to restrict compute driver socket dir '{}': {err}", + socket_dir.display() + )) + }) +} + +#[cfg(unix)] +fn checked_directory_metadata( + path: &Path, + expected_uid: u32, + label: &str, +) -> Result { + let metadata = std::fs::symlink_metadata(path).map_err(|err| { + Error::execution(format!( + "failed to stat {label} '{}': {err}", + path.display() + )) + })?; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + return Err(Error::execution(format!( + "{label} '{}' is a symlink; refusing to use it", + path.display() + ))); + } + if !file_type.is_dir() { + return Err(Error::execution(format!( + "{label} '{}' is not a directory", + path.display() + ))); + } + if metadata.uid() != expected_uid { + return Err(Error::execution(format!( + "{label} '{}' is owned by uid {} but current euid is {}", + path.display(), + metadata.uid(), + expected_uid + ))); + } + Ok(metadata) +} + +#[cfg(unix)] +fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<()> { + let metadata = match std::fs::symlink_metadata(socket_path) { + Ok(metadata) => metadata, + Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()), + Err(err) => { + return Err(Error::execution(format!( + "failed to stat compute driver socket '{}': {err}", + socket_path.display() + ))); + } + }; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + return Err(Error::execution(format!( + "compute driver socket '{}' is a symlink; refusing to remove it", + socket_path.display() + ))); + } + if metadata.uid() != expected_uid { + return Err(Error::execution(format!( + "compute driver socket '{}' is owned by uid {} but current euid is {}", + socket_path.display(), + metadata.uid(), + expected_uid + ))); + } + if !file_type.is_socket() { + return Err(Error::execution(format!( + "compute driver socket path '{}' exists but is not a Unix socket", + socket_path.display() + ))); + } + std::fs::remove_file(socket_path).map_err(|err| { + Error::execution(format!( + "failed to remove stale compute driver socket '{}': {err}", + socket_path.display() + )) + }) +} + +/// Launch a compute-driver subprocess, wait for its UDS to come up, and +/// return a gRPC `Channel` connected to it plus a process handle that kills the +/// subprocess and removes the socket on drop. +/// +/// `build_document` receives the driver's socket path and returns the startup +/// document to write for it. +#[cfg(unix)] +pub async fn launch( + driver: &DriverProcess<'_>, + otlp_config: Option<&OtlpConfig>, + shutdown: tokio::sync::watch::Receiver, + build_document: impl FnOnce(&Path) -> Result, +) -> Result { + let name = driver.name; + let driver_bin = resolve_driver_bin(driver)?; + check_driver_binary_trust(&driver_bin, current_euid())?; + let socket_path = socket_path(driver); + prepare_socket_path(driver, &socket_path)?; + + let startup_path = startup_document_path(&socket_path); + let document = build_document(&socket_path)?; + write_startup_document(&startup_path, &document)?; + + let mut command = Command::new(&driver_bin); + command.kill_on_drop(true); + command.stdin(Stdio::null()); + command.stdout(Stdio::inherit()); + command.stderr(Stdio::inherit()); + command.arg("--config").arg(&startup_path); + apply_trace_headers_env(&mut command, otlp_config); + + let mut child = command.spawn().map_err(|e| { + remove_startup_document(&startup_path); + Error::execution(format!( + "failed to launch {name} compute driver '{}': {e}", + driver_bin.display() + )) + })?; + let ready = wait_for_compute_driver(name, &socket_path, &mut child).await; + // The driver reads the document before it binds its socket, so it is no + // longer needed once the driver is ready or has failed. + remove_startup_document(&startup_path); + let channel = ready?; + let process = Arc::new(ManagedDriverProcess::new(child, socket_path)); + watch_for_exit( + Arc::downgrade(&process), + name.to_string(), + EXIT_POLL_INTERVAL, + shutdown, + SHUTDOWN_GRACE, + |message| { + tracing::error!("{message}"); + std::process::exit(1); + }, + ); + Ok(AcquiredRemoteDriverEndpoint::managed( + name, channel, process, + )) +} + +/// How long auto-detection waits for a driver's `probe` before it counts the +/// driver as not available. +#[cfg(unix)] +pub const PROBE_TIMEOUT: Duration = Duration::from_secs(5); + +/// Run ` ` with no input and return its standard output. +/// +/// The command gets `timeout` to exit successfully and may print at most +/// `max_output` bytes. A command that fails, runs out of time, or prints more +/// than that returns an error message. +#[cfg(unix)] +fn run_bounded( + binary: &Path, + args: &[&std::ffi::OsStr], + timeout: Duration, + max_output: usize, +) -> std::result::Result, String> { + use std::io::Read as _; + + let mut child = std::process::Command::new(binary) + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|error| format!("failed to run '{}': {error}", binary.display()))?; + // Read while the process runs, so output beyond the pipe buffer cannot + // block it. Reading stops one byte past the limit, which closes the pipe. + let reader = child.stdout.take().map(|stdout| { + std::thread::spawn(move || { + let mut output = Vec::new(); + stdout + .take(max_output as u64 + 1) + .read_to_end(&mut output) + .map(|_| output) + }) + }); + let deadline = std::time::Instant::now() + timeout; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(10)); + } + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(format!("timed out after {}s", timeout.as_secs())); + } + Err(error) => return Err(format!("failed to wait for the process: {error}")), + } + }; + let output = match reader { + Some(reader) => reader + .join() + .map_err(|_| "output reader panicked".to_string())? + .map_err(|error| format!("failed to read output: {error}"))?, + None => Vec::new(), + }; + // Output past the limit closes the pipe on the process, which then ends + // with SIGPIPE. Hand it back so the caller reports the size, not the signal. + if output.len() > max_output { + return Ok(output); + } + if !status.success() { + return Err(format!("exited with {status}")); + } + Ok(output) +} + +/// Resolve the driver binary and check that the gateway can trust it. +#[cfg(unix)] +fn trusted_driver_bin(driver: &DriverProcess<'_>) -> Result { + let binary = resolve_driver_bin(driver)?; + check_driver_binary_trust(&binary, current_euid())?; + Ok(binary) +} + +/// Run ` probe` and report whether the driver is usable here. +/// +/// A missing or untrusted binary, a failed or timed-out probe, and oversized or +/// malformed output all count as not available, and the reason names the +/// driver, so detection never hangs on or trusts one broken driver. +#[cfg(unix)] +pub fn probe( + driver: &DriverProcess<'_>, + timeout: Duration, +) -> openshell_driver_sdk::probe::ProbeResult { + use openshell_driver_sdk::probe::{MAX_PROBE_OUTPUT_BYTES, ProbeResult}; + + let name = driver.name; + let unavailable = |reason: String| ProbeResult::unavailable(format!("{name} driver: {reason}")); + let binary = match trusted_driver_bin(driver) { + Ok(binary) => binary, + Err(error) => return unavailable(error.to_string()), + }; + let output = match run_bounded( + &binary, + &["probe".as_ref()], + timeout, + MAX_PROBE_OUTPUT_BYTES, + ) { + Ok(output) => output, + Err(error) => return unavailable(format!("probe {error}")), + }; + ProbeResult::parse(&output).unwrap_or_else(unavailable) +} + +/// How long `preflight` may take before the driver counts as failed. +#[cfg(unix)] +pub const PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(10); + +/// Have the driver validate the startup document it would receive, without +/// starting it. +/// +/// The document is the one [`launch`] would write, in a private temporary +/// directory that is removed afterwards, so no driver state is created. +/// +/// # Errors +/// +/// Returns an error naming the driver when it cannot be run, fails, times out, +/// prints unusable output, or rejects the configuration. +#[cfg(unix)] +pub fn preflight( + driver: &DriverProcess<'_>, + timeout: Duration, + build_document: impl FnOnce(&Path) -> Result, +) -> Result<()> { + use openshell_driver_sdk::preflight::{MAX_PREFLIGHT_OUTPUT_BYTES, PreflightResult}; + + let name = driver.name; + let binary = trusted_driver_bin(driver)?; + let directory = tempfile::Builder::new() + .prefix("openshell-preflight-") + .tempdir() + .map_err(|error| { + Error::execution(format!("failed to create preflight directory: {error}")) + })?; + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).map_err( + |error| Error::execution(format!("failed to restrict preflight directory: {error}")), + )?; + let document_path = directory.path().join(STARTUP_DOCUMENT_NAME); + let document = build_document(&directory.path().join(COMPUTE_DRIVER_SOCKET_NAME))?; + write_startup_document(&document_path, &document)?; + let output = run_bounded( + &binary, + &[ + "preflight".as_ref(), + "--config".as_ref(), + document_path.as_os_str(), + ], + timeout, + MAX_PREFLIGHT_OUTPUT_BYTES, + ) + .map_err(|error| Error::config(format!("{name} compute driver preflight {error}")))?; + let result = PreflightResult::parse(&output) + .map_err(|error| Error::config(format!("{name} compute driver: {error}")))?; + if result.ok { + Ok(()) + } else { + Err(Error::config(result.error.unwrap_or_else(|| { + format!("{name} compute driver rejected its configuration") + }))) + } +} + +#[cfg(unix)] +const EXIT_POLL_INTERVAL: Duration = Duration::from_millis(500); + +/// How long the watcher waits for the gateway's own shutdown to begin after a +/// driver exits. A stop signal reaches the driver and the gateway together, so +/// the driver can end a moment before the gateway notices it must shut down. +#[cfg(unix)] +const SHUTDOWN_GRACE: Duration = Duration::from_secs(2); + +/// Call `on_exit` with a message naming the driver if the process ends while +/// the gateway still holds it and is not shutting down. The gateway cannot +/// serve sandboxes without its driver, so the caller exits and leaves a +/// restart to the init system. +#[cfg(unix)] +fn watch_for_exit( + process: std::sync::Weak, + name: String, + interval: Duration, + mut shutdown: tokio::sync::watch::Receiver, + grace: Duration, + on_exit: impl FnOnce(String) + Send + 'static, +) { + tokio::spawn(async move { + loop { + tokio::time::sleep(interval).await; + if *shutdown.borrow() { + return; + } + let Some(process) = process.upgrade() else { + return; + }; + match process.poll_exit() { + DriverProcessState::Running => {} + DriverProcessState::Released => return, + DriverProcessState::Exited(status) => { + drop(process); + if tokio::time::timeout(grace, shutdown.wait_for(|stopping| *stopping)) + .await + .is_ok() + { + return; + } + on_exit(format!( + "{name} compute driver exited unexpectedly with status {status}" + )); + return; + } + } + } + }); +} + +/// Refuse a driver binary, or the directory that holds it, that another user +/// could replace: it must be owned by the gateway's effective user or root and +/// must not be group- or world-writable. +#[cfg(unix)] +fn check_driver_binary_trust(binary: &Path, expected_uid: u32) -> Result<()> { + let binary = binary.canonicalize().map_err(|error| { + Error::config(format!( + "failed to resolve compute driver binary '{}': {error}", + binary.display() + )) + })?; + let directory = binary.parent().ok_or_else(|| { + Error::config(format!( + "compute driver binary '{}' has no parent directory", + binary.display() + )) + })?; + for (label, path) in [("binary", binary.as_path()), ("directory", directory)] { + let metadata = std::fs::metadata(path).map_err(|error| { + Error::config(format!( + "failed to inspect compute driver {label} '{}': {error}", + path.display() + )) + })?; + if metadata.uid() != expected_uid && metadata.uid() != 0 { + return Err(Error::config(format!( + "compute driver {label} '{}' is owned by uid {}, not root or the gateway's uid {expected_uid}", + path.display(), + metadata.uid() + ))); + } + let mode = metadata.permissions().mode() & 0o777; + if mode & 0o022 != 0 { + return Err(Error::config(format!( + "compute driver {label} '{}' is group- or world-writable (mode {mode:o})", + path.display() + ))); + } + } + Ok(()) +} + +/// File name of the startup document, written beside the driver socket in its +/// private run directory. +#[cfg(unix)] +const STARTUP_DOCUMENT_NAME: &str = "startup.toml"; + +#[cfg(unix)] +fn startup_document_path(socket_path: &Path) -> PathBuf { + socket_path.with_file_name(STARTUP_DOCUMENT_NAME) +} + +/// Write the document with mode 0600. The run directory is private (0700), so +/// the file is not readable by other users. +#[cfg(unix)] +fn write_startup_document( + path: &Path, + document: &openshell_driver_sdk::StartupDocument, +) -> Result<()> { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + + let text = document + .to_toml() + .map_err(|error| Error::config(error.to_string()))?; + match std::fs::remove_file(path) { + Ok(()) => {} + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => { + return Err(Error::execution(format!( + "failed to remove stale startup document '{}': {error}", + path.display() + ))); + } + } + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .and_then(|mut file| file.write_all(text.as_bytes())) + .map_err(|error| { + let _ = std::fs::remove_file(path); + Error::execution(format!( + "failed to write startup document '{}': {error}", + path.display() + )) + }) +} + +#[cfg(unix)] +fn remove_startup_document(path: &Path) { + let _ = std::fs::remove_file(path); +} + +/// The driver's own trace exporter reads these headers like any OTLP SDK. +/// They stay in the environment so they never reach the startup document or +/// process listings. +#[cfg(unix)] +fn apply_trace_headers_env(command: &mut Command, otlp_config: Option<&OtlpConfig>) { + if let Some(headers) = openshell_server::gateway_trace_headers(otlp_config) { + command.env("OTEL_EXPORTER_OTLP_TRACES_HEADERS", headers.expose_secret()); + } +} + +#[cfg(not(unix))] +pub async fn launch( + _driver: &DriverProcess<'_>, + _otlp_config: Option<&OtlpConfig>, + _shutdown: tokio::sync::watch::Receiver, + _build_document: impl FnOnce(&Path) -> Result, +) -> Result { + Err(Error::config( + "launched compute drivers require unix domain socket support", + )) +} + +/// Readiness polls, 100 ms apart. The Podman driver retries its API ping for +/// about ten seconds before it binds its socket, so the wait is longer. +#[cfg(unix)] +const READY_POLLS: u32 = 300; + +#[cfg(unix)] +#[tracing::instrument( + name = "driver.wait_for_ready", + skip_all, + fields( + otel.name = "driver.wait_for_ready", + otel.status_code = tracing::field::Empty, + driver.name = %name, + ) +)] +async fn wait_for_compute_driver( + name: &str, + socket_path: &Path, + child: &mut tokio::process::Child, +) -> Result { + let mut last_error: Option = None; + for _ in 0..READY_POLLS { + let try_wait_result = child.try_wait().map_err(|e| { + Error::execution(format!("failed to poll {name} compute driver process: {e}")) + })?; + if let Some(status) = try_wait_result { + return Err(Error::execution(format!( + "{name} compute driver exited before becoming ready with status {status}" + ))); + } + + match connect_compute_driver(name, socket_path).await { + Ok(channel) => { + let mut client = + ComputeDriverClient::with_interceptor(channel.clone(), TraceContextInterceptor); + match client + .get_capabilities(tonic::Request::new(GetCapabilitiesRequest { + gateway: Some(openshell_core::extension_protocol::gateway_metadata( + openshell_core::extension_protocol::ExtensionFamily::Compute, + )), + })) + .await + { + Ok(_) => return Ok(channel), + Err(status) => last_error = Some(status.to_string()), + } + } + Err(err) => last_error = Some(err.to_string()), + } + + tokio::time::sleep(Duration::from_millis(100)).await; + } + + Err(Error::execution(format!( + "timed out waiting for {name} compute driver socket '{}': {}", + socket_path.display(), + last_error.unwrap_or_else(|| "unknown error".to_string()) + ))) +} + +#[cfg(unix)] +async fn connect_compute_driver(name: &str, socket_path: &Path) -> Result { + let socket_path = socket_path.to_path_buf(); + let display_path = socket_path.clone(); + Endpoint::from_static("http://[::]:50051") + .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { + let socket_path = socket_path.clone(); + async move { UnixStream::connect(socket_path).await.map(TokioIo::new) } + })) + .await + .map_err(|e| { + Error::execution(format!( + "failed to connect to {name} compute driver socket '{}': {e}", + display_path.display() + )) + }) +} + +#[cfg(all(test, unix))] +mod tests { + use super::{ + DriverProcess, apply_trace_headers_env, check_driver_binary_trust, current_euid, + prepare_socket_path, prepare_state_dir, resolve_driver_bin, resolve_driver_search_dirs, + socket_path, startup_document_path, watch_for_exit, write_startup_document, + }; + use openshell_server::ManagedDriverProcess; + use openshell_server::config_file::OtlpConfig; + use std::os::unix::fs::PermissionsExt; + use std::os::unix::net::UnixListener as StdUnixListener; + use std::path::{Path, PathBuf}; + use std::sync::Arc; + use std::time::Duration; + use tempfile::tempdir; + + /// Owned inputs for a [`DriverProcess`] in tests. + #[derive(Default)] + struct TestDriver { + driver_dir: Option, + state_dir: Option, + } + + impl TestDriver { + fn state_dir(&self) -> PathBuf { + self.state_dir.clone().unwrap_or_default() + } + + fn process(&self) -> DriverProcess<'_> { + DriverProcess { + name: "test", + binary_name: "openshell-driver-test", + driver_dir: self.driver_dir.as_deref(), + driver_dir_key: Some("[openshell.drivers.test].driver_dir"), + state_dir: self.state_dir.as_deref().unwrap_or_else(|| Path::new("")), + } + } + } + + #[test] + fn the_startup_document_is_private_and_replaced_when_stale() { + let dir = tempdir().unwrap(); + let socket = dir.path().join("compute-driver.sock"); + let path = startup_document_path(&socket); + assert_eq!(path, dir.path().join("startup.toml")); + + let document = openshell_driver_sdk::StartupDocument::parse(include_str!( + "../../openshell-driver-sdk/tests/fixtures/startup-v1.toml" + )) + .unwrap(); + write_startup_document(&path, &document).unwrap(); + // Rewriting replaces a stale file instead of failing on it. + write_startup_document(&path, &document).unwrap(); + + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + + /// The gateway passes the operator's table through unchanged, apart from + /// the launcher-owned `driver_dir`, and adds the gateway context the + /// driver's own tests read from the same fixture. + #[test] + fn vm_driver_receives_trace_headers_in_its_environment_only() { + crate::test_environment::Environment::new() + .remove("OTEL_EXPORTER_OTLP_HEADERS") + .remove("OTEL_EXPORTER_OTLP_TRACES_HEADERS") + .run(|| { + let otlp: OtlpConfig = toml::from_str( + "endpoint = 'http://collector.internal:4318'\n\ + headers = { authorization = 'Bearer secret-token' }\n", + ) + .unwrap(); + let mut command = tokio::process::Command::new("openshell-driver-vm"); + apply_trace_headers_env(&mut command, Some(&otlp)); + + let env = command + .as_std() + .get_envs() + .find(|(name, _)| *name == "OTEL_EXPORTER_OTLP_TRACES_HEADERS") + .and_then(|(_, value)| value) + .map(|value| value.to_string_lossy().into_owned()); + assert_eq!(env.as_deref(), Some("authorization=Bearer%20secret-token")); + assert!( + command + .as_std() + .get_args() + .all(|arg| !arg.to_string_lossy().contains("secret-token")) + ); + }); + } + + #[test] + fn resolve_driver_bin_uses_driver_dir_when_binary_present() { + let dir = tempdir().unwrap(); + let bin = dir.path().join("openshell-driver-test"); + std::fs::write(&bin, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let vm_config = TestDriver { + driver_dir: Some(dir.path().to_path_buf()), + ..Default::default() + }; + assert_eq!(resolve_driver_bin(&vm_config.process()).unwrap(), bin); + } + + #[test] + fn resolve_driver_bin_error_mentions_driver_dir_hint() { + let dir = tempdir().unwrap(); // empty — no driver binary present + + let vm_config = TestDriver { + driver_dir: Some(dir.path().to_path_buf()), + ..Default::default() + }; + let err = resolve_driver_bin(&vm_config.process()) + .unwrap_err() + .to_string(); + assert!(err.contains("[openshell.drivers.test].driver_dir")); + assert!(err.contains("openshell-driver-test")); + } + + #[test] + fn resolve_driver_search_dirs_include_libexec_fallbacks() { + let dirs = resolve_driver_search_dirs(None); + + assert!(dirs.contains(&PathBuf::from("/usr/libexec/openshell"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/libexec/openshell"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/libexec"))); + } + + #[test] + fn compute_driver_socket_path_uses_private_run_dir() { + let state_dir = PathBuf::from("/tmp/openshell-vm-state"); + let vm_config = TestDriver { + state_dir: Some(state_dir.clone()), + ..Default::default() + }; + + assert_eq!( + socket_path(&vm_config.process()), + state_dir.join("run").join("compute-driver.sock") + ); + } + + #[test] + fn prepare_compute_driver_socket_path_creates_private_run_dir() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let socket_path = socket_path(&vm_config.process()); + + prepare_socket_path(&vm_config.process(), &socket_path).unwrap(); + + let mode = std::fs::metadata(vm_config.state_dir().join("run")) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o700); + } + + #[test] + fn prepare_compute_driver_socket_path_restricts_existing_run_dir() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let run_dir = vm_config.state_dir().join("run"); + std::fs::create_dir_all(&run_dir).unwrap(); + std::fs::set_permissions(&run_dir, std::fs::Permissions::from_mode(0o777)).unwrap(); + let socket_path = socket_path(&vm_config.process()); + + prepare_socket_path(&vm_config.process(), &socket_path).unwrap(); + + let mode = std::fs::metadata(run_dir).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700); + } + + #[test] + fn prepare_compute_driver_socket_path_restricts_existing_state_dir() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + std::fs::create_dir_all(vm_config.state_dir()).unwrap(); + std::fs::set_permissions( + vm_config.state_dir(), + std::fs::Permissions::from_mode(0o777), + ) + .unwrap(); + let socket_path = socket_path(&vm_config.process()); + + prepare_socket_path(&vm_config.process(), &socket_path).unwrap(); + + let mode = std::fs::metadata(vm_config.state_dir()) + .unwrap() + .permissions() + .mode() + & 0o777; + assert_eq!(mode, 0o700); + } + + #[test] + fn prepare_compute_driver_socket_path_rejects_symlinked_state_dir() { + let dir = tempdir().unwrap(); + let target = dir.path().join("target"); + let state_link = dir.path().join("state-link"); + std::fs::create_dir_all(&target).unwrap(); + std::os::unix::fs::symlink(&target, &state_link).unwrap(); + let vm_config = TestDriver { + state_dir: Some(state_link), + ..Default::default() + }; + let socket_path = socket_path(&vm_config.process()); + + let err = prepare_socket_path(&vm_config.process(), &socket_path) + .expect_err("symlinked state dir should be rejected") + .to_string(); + assert!(err.contains("is a symlink")); + } + + #[test] + fn prepare_compute_driver_socket_path_rejects_symlinked_run_dir() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let target = dir.path().join("run-target"); + std::fs::create_dir_all(vm_config.state_dir()).unwrap(); + std::fs::create_dir_all(&target).unwrap(); + std::os::unix::fs::symlink(&target, vm_config.state_dir().join("run")).unwrap(); + let socket_path = socket_path(&vm_config.process()); + + let err = prepare_socket_path(&vm_config.process(), &socket_path) + .expect_err("symlinked run dir should be rejected") + .to_string(); + assert!(err.contains("is a symlink")); + } + + #[test] + fn prepare_vm_state_dir_rejects_wrong_owner() { + let dir = tempdir().unwrap(); + let state_dir = dir.path().join("state"); + std::fs::create_dir_all(&state_dir).unwrap(); + let wrong_uid = if current_euid() == u32::MAX { + u32::MAX - 1 + } else { + current_euid() + 1 + }; + + let err = prepare_state_dir(&state_dir, wrong_uid) + .expect_err("wrong owner should be rejected") + .to_string(); + assert!(err.contains("is owned by uid")); + } + + #[test] + fn prepare_compute_driver_socket_path_rejects_symlinked_socket() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let socket_path = socket_path(&vm_config.process()); + std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink("/tmp/not-a-socket", &socket_path).unwrap(); + + let err = prepare_socket_path(&vm_config.process(), &socket_path) + .expect_err("symlinked socket should be rejected") + .to_string(); + assert!(err.contains("is a symlink")); + } + + #[test] + fn prepare_compute_driver_socket_path_rejects_non_socket_stale_path() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let socket_path = socket_path(&vm_config.process()); + std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); + std::fs::write(&socket_path, "not a socket").unwrap(); + + let err = prepare_socket_path(&vm_config.process(), &socket_path) + .expect_err("regular file should be rejected") + .to_string(); + assert!(err.contains("is not a Unix socket")); + } + + #[test] + fn prepare_compute_driver_socket_path_removes_same_owner_stale_socket() { + let dir = tempdir().unwrap(); + let vm_config = TestDriver { + state_dir: Some(dir.path().join("state")), + ..Default::default() + }; + let socket_path = socket_path(&vm_config.process()); + std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); + let listener = StdUnixListener::bind(&socket_path).unwrap(); + + prepare_socket_path(&vm_config.process(), &socket_path).unwrap(); + + drop(listener); + assert!(!socket_path.exists()); + } + + fn driver_binary(dir: &Path, binary_mode: u32, dir_mode: u32) -> PathBuf { + let binary = dir.join("openshell-driver-test"); + std::fs::write(&binary, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(binary_mode)).unwrap(); + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(dir_mode)).unwrap(); + binary + } + + #[test] + fn a_driver_binary_owned_by_the_gateway_user_is_trusted() { + let dir = tempdir().unwrap(); + let binary = driver_binary(dir.path(), 0o755, 0o755); + check_driver_binary_trust(&binary, current_euid()).unwrap(); + } + + #[test] + fn a_writable_driver_binary_or_directory_is_refused() { + let dir = tempdir().unwrap(); + for (binary_mode, dir_mode, what) in [(0o775, 0o755, "binary"), (0o757, 0o755, "binary")] { + let binary = driver_binary(dir.path(), binary_mode, dir_mode); + let error = check_driver_binary_trust(&binary, current_euid()).unwrap_err(); + assert!(error.to_string().contains(what), "{error}"); + assert!(error.to_string().contains("writable"), "{error}"); + } + let binary = driver_binary(dir.path(), 0o755, 0o777); + let error = check_driver_binary_trust(&binary, current_euid()).unwrap_err(); + assert!(error.to_string().contains("directory"), "{error}"); + assert!(error.to_string().contains("writable"), "{error}"); + } + + #[test] + fn a_driver_binary_owned_by_another_user_is_refused() { + let dir = tempdir().unwrap(); + let binary = driver_binary(dir.path(), 0o755, 0o755); + // The binary is owned by the test user, so pretend the gateway runs as + // someone else. Root-owned files remain acceptable, so skip as root. + if current_euid() == 0 { + return; + } + let error = check_driver_binary_trust(&binary, current_euid() + 1).unwrap_err(); + assert!(error.to_string().contains("owned by uid"), "{error}"); + } + + fn spawn_sleeper(seconds: &str) -> tokio::process::Child { + tokio::process::Command::new("sleep") + .arg(seconds) + .kill_on_drop(true) + .spawn() + .unwrap() + } + + #[tokio::test] + async fn a_driver_that_exits_after_it_was_ready_is_reported_by_name() { + let dir = tempdir().unwrap(); + let child = tokio::process::Command::new("sh") + .args(["-c", "exit 3"]) + .spawn() + .unwrap(); + let process = Arc::new(ManagedDriverProcess::new(child, dir.path().join("d.sock"))); + let (sender, receiver) = tokio::sync::oneshot::channel(); + let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(false); + watch_for_exit( + Arc::downgrade(&process), + "vm".to_string(), + Duration::from_millis(10), + shutdown, + Duration::from_millis(50), + move |message| { + let _ = sender.send(message); + }, + ); + let message = tokio::time::timeout(Duration::from_secs(5), receiver) + .await + .unwrap() + .unwrap(); + assert!( + message.contains("vm compute driver exited unexpectedly"), + "{message}" + ); + assert!(message.contains("exit status: 3"), "{message}"); + } + + #[tokio::test] + async fn a_running_driver_is_not_reported() { + let dir = tempdir().unwrap(); + let process = Arc::new(ManagedDriverProcess::new( + spawn_sleeper("30"), + dir.path().join("d.sock"), + )); + let (sender, mut receiver) = tokio::sync::oneshot::channel::(); + let (_shutdown_tx, shutdown) = tokio::sync::watch::channel(false); + watch_for_exit( + Arc::downgrade(&process), + "vm".to_string(), + Duration::from_millis(10), + shutdown, + Duration::from_millis(50), + move |message| { + let _ = sender.send(message); + }, + ); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!(receiver.try_recv().is_err()); + drop(process); + } + + /// A stop signal reaches the driver and the gateway together. A driver that + /// ends while the gateway is shutting down is not a failure. + #[tokio::test] + async fn a_driver_that_exits_during_gateway_shutdown_is_not_reported() { + let dir = tempdir().unwrap(); + let child = tokio::process::Command::new("sh") + .args(["-c", "exit 0"]) + .spawn() + .unwrap(); + let process = Arc::new(ManagedDriverProcess::new(child, dir.path().join("d.sock"))); + let (sender, mut receiver) = tokio::sync::oneshot::channel::(); + let (shutdown_tx, shutdown) = tokio::sync::watch::channel(false); + watch_for_exit( + Arc::downgrade(&process), + "vm".to_string(), + Duration::from_millis(10), + shutdown, + Duration::from_secs(5), + move |message| { + let _ = sender.send(message); + }, + ); + // The driver has exited by the time the watcher notices. The gateway + // begins its own shutdown inside the grace period. + tokio::time::sleep(Duration::from_millis(100)).await; + shutdown_tx.send_replace(true); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(receiver.try_recv().is_err()); + } + + #[test] + fn output_beyond_the_limit_is_not_mistaken_for_a_timeout() { + let dir = tempdir().unwrap(); + let binary = probe_script(dir.path(), "head -c 300000 /dev/zero | tr '\\0' x"); + let output = super::run_bounded(&binary, &[], Duration::from_secs(5), 4096).unwrap(); + assert_eq!(output.len(), 4097); + } + + fn probe_script(dir: &Path, body: &str) -> PathBuf { + let binary = driver_binary(dir, 0o755, 0o755); + std::fs::write(&binary, format!("#!/bin/sh\n{body}\n")).unwrap(); + binary + } + + fn run_probe(body: &str, timeout: Duration) -> openshell_driver_sdk::probe::ProbeResult { + let dir = tempdir().unwrap(); + probe_script(dir.path(), body); + let state = dir.path().join("state"); + let driver = DriverProcess { + name: "test", + binary_name: "openshell-driver-test", + driver_dir: Some(dir.path()), + driver_dir_key: None, + state_dir: &state, + }; + super::probe(&driver, timeout) + } + + #[test] + fn a_probe_reports_availability() { + let result = run_probe("echo '{\"available\":true}'", Duration::from_secs(5)); + assert!(result.available, "{result:?}"); + let result = run_probe( + "echo '{\"available\":false,\"reason\":\"no socket\"}'", + Duration::from_secs(5), + ); + assert!(!result.available); + assert_eq!(result.reason.as_deref(), Some("no socket")); + } + + #[test] + fn a_broken_probe_counts_as_unavailable_and_names_the_driver() { + for body in [ + "exit 1", + "echo not-json", + "head -c 100000 /dev/zero | tr '\\0' ' '", + "sleep 30", + ] { + let result = run_probe(body, Duration::from_millis(300)); + assert!(!result.available, "{body}"); + assert!(result.reason.unwrap().starts_with("test driver:"), "{body}"); + } + } + + #[test] + fn a_missing_driver_is_unavailable() { + let dir = tempdir().unwrap(); + let state = dir.path().join("state"); + let driver = DriverProcess { + name: "test", + binary_name: "openshell-driver-absent", + driver_dir: Some(dir.path()), + driver_dir_key: None, + state_dir: &state, + }; + assert!(!super::probe(&driver, Duration::from_secs(1)).available); + } + + fn run_preflight(body: &str, timeout: Duration) -> openshell_core::Result<()> { + let dir = tempdir().unwrap(); + probe_script(dir.path(), body); + let state = dir.path().join("state"); + let driver = DriverProcess { + name: "test", + binary_name: "openshell-driver-test", + driver_dir: Some(dir.path()), + driver_dir_key: None, + state_dir: &state, + }; + let result = super::preflight(&driver, timeout, |socket| { + assert_eq!(socket.file_name().unwrap(), "compute-driver.sock"); + Ok(openshell_driver_sdk::StartupDocument::new( + openshell_driver_sdk::GatewayContext { + bind_socket: socket.to_path_buf(), + expected_peer_pid: 1, + log_level: "info".into(), + gateway_name: "g".into(), + gateway_port: 8080, + tls_ca: None, + telemetry: openshell_driver_sdk::Telemetry::default(), + network_trust: None, + }, + toml::Table::new(), + )) + }); + assert!(!state.exists(), "preflight must not create driver state"); + result + } + + #[test] + fn preflight_passes_the_document_and_reports_the_drivers_verdict() { + // The script checks it received `preflight --config ` + // whose mode is private. + let accepted = "test \"$1\" = preflight && test \"$2\" = --config && test -f \"$3\" && test \"$(ls -l \"$3\" | cut -c1-10)\" = -rw------- && echo '{\"ok\":true}'"; + run_preflight(accepted, Duration::from_secs(10)).unwrap(); + + let error = run_preflight( + "echo '{\"ok\":false,\"error\":\"vcpus must be positive\"}'", + Duration::from_secs(10), + ) + .unwrap_err(); + assert!( + error.to_string().contains("vcpus must be positive"), + "{error}" + ); + } + + #[test] + fn a_broken_preflight_fails_and_names_the_driver() { + for body in ["exit 1", "echo nope", "sleep 30"] { + let error = run_preflight(body, Duration::from_millis(500)) + .unwrap_err() + .to_string(); + assert!(error.contains("test compute driver"), "{body}: {error}"); + } + } +} diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 2e75ec61f6..d38f657d27 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -16,6 +16,17 @@ compile_error!( build a telemetry-free gateway with `--no-default-features --features defaults-without-telemetry`" ); +pub mod startup_document; + +#[cfg(all( + not(target_os = "windows"), + any(feature = "compute-driver-vm", feature = "compute-driver-podman") +))] +mod launcher; + +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] +mod podman; + #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] mod vm; @@ -194,17 +205,11 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { .with_in_process_tracing(openshell_driver_kubernetes::otel_tracing::TRACING) }), #[cfg(feature = "compute-driver-podman")] - ComputeDriverRegistration::new( - "podman", - 200, - Some(openshell_driver_podman::driver::is_available), - PodmanFactory, - ) - .map(|registration| { - registration - .with_telemetry_category(TelemetryComputeDriver::anonymous_category("podman")) - .with_in_process_tracing(openshell_driver_podman::otel_tracing::TRACING) - }), + ComputeDriverRegistration::new("podman", 200, Some(podman::is_available), PodmanFactory) + .map(|registration| { + registration + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("podman")) + }), #[cfg(feature = "compute-driver-docker")] ComputeDriverRegistration::new( "docker", @@ -479,60 +484,42 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory { true } + // The driver validates its own configuration through `preflight`. fn validate_config( &self, context: openshell_server::ComputeDriverConfigContext<'_>, ) -> openshell_core::Result<()> { - podman_config(context)? - .validate_configuration() - .map_err(|error| openshell_core::Error::config(error.to_string())) + podman::preflight( + context.gateway_log_level(), + context.gateway_name(), + context.gateway_port(), + context.driver_config()?, + ) } async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, ) -> openshell_core::Result { - let mut config = podman_config(context.config_context())?; - config.supervisor_otlp = context - .otlp_config() - .map(OtlpConfig::supervisor_otlp) - .unwrap_or_default(); - config.supervisor_gateway_name = Some(context.gateway_name().to_string()); + let driver_config: toml::Table = context.config_context().driver_config()?; require_guest_tls_for_local_driver(&context, "podman")?; - apply_guest_tls(&mut config.guest_tls_ca, context.guest_tls_ca()); - let driver = openshell_driver_podman::PodmanComputeDriver::new( - config, - context.network_trust_bundle().cloned(), - ) - .await - .map_err(|error| openshell_core::Error::execution(error.to_string()))?; - let driver = openshell_driver_podman::ComputeDriverService::new_in_process(driver); - Ok(openshell_server::ComputeDriverInstance::InProcess( - std::sync::Arc::new(driver), + let endpoint = podman::spawn(podman::PodmanLaunch { + gateway_log_level: context.gateway_log_level(), + gateway_name: context.gateway_name(), + gateway_port: context.gateway_port(), + tls_ca: context.guest_tls_ca(), + otlp_config: context.otlp_config(), + network_trust: context.network_trust_bundle(), + shutdown: context.shutdown_receiver(), + driver_config, + }) + .await?; + Ok(openshell_server::ComputeDriverInstance::ManagedRemote( + endpoint, )) } } -#[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] -fn podman_config( - context: openshell_server::ComputeDriverConfigContext<'_>, -) -> openshell_core::Result { - let mut config: openshell_driver_podman::PodmanComputeConfig = context.driver_config()?; - config.gateway_port = context.gateway_port(); - config.sandbox_runtime_image = prefer_environment( - config.sandbox_runtime_image, - std::env::var(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV).ok(), - ); - config.supervisor_image = prefer_environment( - config.supervisor_image, - std::env::var(openshell_core::config::SUPERVISOR_IMAGE_ENV).ok(), - ); - if let Ok(path) = std::env::var("OPENSHELL_PODMAN_SOCKET") { - config.socket_path = Some(path.into()); - } - Ok(config) -} - #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] #[derive(Clone, Copy)] struct VmFactory; @@ -544,6 +531,19 @@ impl openshell_server::ComputeDriverFactory for VmFactory { true } + // The driver validates its own configuration through `preflight`. + fn validate_config( + &self, + context: openshell_server::ComputeDriverConfigContext<'_>, + ) -> openshell_core::Result<()> { + vm::preflight( + context.gateway_log_level(), + context.gateway_name(), + context.gateway_port(), + vm_driver_table(context)?, + ) + } + async fn preflight_host_tools( &self, cancellation: tokio::sync::watch::Receiver, @@ -557,46 +557,24 @@ impl openshell_server::ComputeDriverFactory for VmFactory { true } - fn validate_config( - &self, - context: openshell_server::ComputeDriverConfigContext<'_>, - ) -> openshell_core::Result<()> { - let mut config = vm_config(context)?; - if config.grpc_endpoint.trim().is_empty() { - let scheme = if context.gateway_tls_enabled() { - "https" - } else { - "http" - }; - config.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", context.gateway_port()); - } - config.validate_configuration() - } - async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, ) -> openshell_core::Result { - let mut config = vm_config(context.config_context())?; + let driver_config = vm_driver_table(context.config_context())?; + let settings = vm::VmLaunchSettings::from_table(&driver_config)?; require_guest_tls_for_local_driver(&context, "vm")?; - if config.grpc_endpoint.trim().is_empty() - && (!context.gateway_tls_enabled() || context.guest_tls_ca().is_some()) - { - let scheme = if context.gateway_tls_enabled() { - "https" - } else { - "http" - }; - config.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", context.gateway_port()); - } - apply_guest_tls(&mut config.guest_tls_ca, context.guest_tls_ca()); - let endpoint = vm::spawn( - context.gateway_log_level(), - context.gateway_name(), - &config, - context.otlp_config(), - context.network_trust_bundle(), - ) + let endpoint = vm::spawn(vm::VmLaunch { + gateway_log_level: context.gateway_log_level(), + gateway_name: context.gateway_name(), + gateway_port: context.gateway_port(), + tls_ca: context.guest_tls_ca(), + otlp_config: context.otlp_config(), + network_trust: context.network_trust_bundle(), + shutdown: context.shutdown_receiver(), + settings: &settings, + driver_config, + }) .await?; Ok(openshell_server::ComputeDriverInstance::ManagedRemote( endpoint, @@ -605,14 +583,10 @@ impl openshell_server::ComputeDriverFactory for VmFactory { } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] -fn vm_config( +fn vm_driver_table( context: openshell_server::ComputeDriverConfigContext<'_>, -) -> openshell_core::Result { - let mut config: vm::VmComputeConfig = context.driver_config()?; - if config.state_dir.as_os_str().is_empty() { - config.state_dir = vm::VmComputeConfig::default_state_dir(); - } - Ok(config) +) -> openshell_core::Result { + context.driver_config() } #[cfg(all( diff --git a/crates/openshell-gateway/src/podman.rs b/crates/openshell-gateway/src/podman.rs new file mode 100644 index 0000000000..e4dc62149c --- /dev/null +++ b/crates/openshell-gateway/src/podman.rs @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launching the Podman compute driver through the generic launcher. +//! +//! The gateway passes the operator's `[openshell.drivers.podman]` table through +//! unchanged as the startup document's `driver_config`. The Podman driver +//! deserializes and validates it. + +use crate::launcher::{self, DriverProcess}; +use openshell_core::{NetworkSupervisorTrustBundle, Result}; +use openshell_server::AcquiredRemoteDriverEndpoint; +use openshell_server::config_file::OtlpConfig; +use std::path::{Path, PathBuf}; + +const DRIVER_BIN_NAME: &str = "openshell-driver-podman"; + +/// Everything the gateway supplies to launch the Podman driver. +pub struct PodmanLaunch<'a> { + pub gateway_log_level: &'a str, + pub gateway_name: &'a str, + pub gateway_port: u16, + /// The gateway's `guest_tls_ca`, when it serves TLS. + pub tls_ca: Option<&'a Path>, + pub otlp_config: Option<&'a OtlpConfig>, + pub network_trust: Option<&'a NetworkSupervisorTrustBundle>, + /// Becomes true when the gateway begins shutting down. + pub shutdown: tokio::sync::watch::Receiver, + /// The operator's `[openshell.drivers.podman]` table, passed through. + pub driver_config: toml::Table, +} + +/// Directory whose `run/` subdirectory holds the driver socket and startup +/// document. +#[must_use] +pub fn default_state_dir() -> PathBuf { + openshell_core::paths::openshell_state_dir().map_or_else( + |_| PathBuf::from("target/openshell-podman-driver"), + |dir| dir.join("podman-driver"), + ) +} + +/// Whether the Podman driver reports that Podman is usable on this host. +#[must_use] +pub fn is_available() -> bool { + let state_dir = default_state_dir(); + let process = DriverProcess { + name: "podman", + binary_name: DRIVER_BIN_NAME, + driver_dir: None, + driver_dir_key: None, + state_dir: &state_dir, + }; + let result = launcher::probe(&process, launcher::PROBE_TIMEOUT); + if !result.available { + tracing::debug!( + reason = result.reason.as_deref().unwrap_or("unknown"), + "podman compute driver not available" + ); + } + result.available +} + +/// Have the Podman driver validate the document the gateway would launch it +/// with. Values the gateway only knows once it serves, such as its TLS CA and +/// the staged network trust bundle, are left out. +pub fn preflight( + gateway_log_level: &str, + gateway_name: &str, + gateway_port: u16, + driver_config: toml::Table, +) -> Result<()> { + let state_dir = default_state_dir(); + let process = DriverProcess { + name: "podman", + binary_name: DRIVER_BIN_NAME, + driver_dir: None, + driver_dir_key: None, + state_dir: &state_dir, + }; + launcher::preflight(&process, launcher::PREFLIGHT_TIMEOUT, |socket_path| { + podman_startup_document( + PodmanLaunch { + gateway_log_level, + gateway_name, + gateway_port, + tls_ca: None, + otlp_config: None, + network_trust: None, + shutdown: tokio::sync::watch::channel(false).1, + driver_config, + }, + socket_path, + ) + }) +} + +/// Launch the Podman driver and return a managed endpoint for it. +pub async fn spawn(launch: PodmanLaunch<'_>) -> Result { + let state_dir = default_state_dir(); + let process = DriverProcess { + name: "podman", + binary_name: DRIVER_BIN_NAME, + driver_dir: None, + driver_dir_key: None, + state_dir: &state_dir, + }; + let otlp_config = launch.otlp_config; + let shutdown = launch.shutdown.clone(); + launcher::launch(&process, otlp_config, shutdown, |socket_path| { + podman_startup_document(launch, socket_path) + }) + .await +} + +fn podman_startup_document( + launch: PodmanLaunch<'_>, + socket_path: &Path, +) -> Result { + crate::startup_document::GatewayStartup { + bind_socket: socket_path, + log_level: launch.gateway_log_level, + gateway_name: launch.gateway_name, + gateway_port: launch.gateway_port, + tls_ca: launch.tls_ca, + otlp: launch.otlp_config, + network_trust: launch.network_trust, + } + .into_document(launch.driver_config) +} + +#[cfg(all(test, unix))] +mod tests { + use super::{PodmanLaunch, podman_startup_document}; + use openshell_core::NetworkSupervisorTrustBundle; + use openshell_core::sandbox_env::OtlpProtocol; + use openshell_server::config_file::{OtlpCollectorConfig, OtlpConfig, OtlpTracesConfig}; + use std::path::{Path, PathBuf}; + + const FIXTURE: &str = + include_str!("../../openshell-driver-podman/tests/fixtures/startup-podman.toml"); + + /// The gateway passes the operator's table through unchanged and adds the + /// gateway context the driver's own tests read from the same fixture. + #[test] + fn the_gateway_writes_the_documented_startup_document() { + let fixture = openshell_driver_sdk::StartupDocument::parse(FIXTURE).unwrap(); + let otlp = OtlpConfig { + metrics: None, + service_name: None, + traces: Some(OtlpTracesConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4317", + OtlpProtocol::Grpc, + ), + }), + ocsf: None, + agent: None, + }; + let trust = NetworkSupervisorTrustBundle::new( + b"pem".to_vec(), + 3, + "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), + ); + + let mut document = podman_startup_document( + PodmanLaunch { + gateway_log_level: "debug", + gateway_name: "gateway-a", + gateway_port: 8080, + tls_ca: None, + otlp_config: Some(&otlp), + network_trust: Some(&trust), + shutdown: tokio::sync::watch::channel(false).1, + driver_config: fixture.driver_config.clone(), + }, + Path::new("/var/lib/openshell/podman-driver/run/compute-driver.sock"), + ) + .unwrap(); + document.gateway.expected_peer_pid = 4242; + + assert_eq!(document, fixture); + } +} diff --git a/crates/openshell-gateway/src/startup_document.rs b/crates/openshell-gateway/src/startup_document.rs new file mode 100644 index 0000000000..da2b20e5f9 --- /dev/null +++ b/crates/openshell-gateway/src/startup_document.rs @@ -0,0 +1,229 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Builds the startup document the gateway passes to a launched driver. +//! +//! The document types live in `openshell-driver-sdk`, which shares none of the +//! gateway's configuration types. This module is the single place that +//! converts the gateway's resolved configuration into them. + +use std::path::Path; + +use openshell_core::{Error, NetworkSupervisorTrustBundle, Result}; +use openshell_driver_sdk as sdk; +use openshell_server::config_file::OtlpConfig; + +/// Resolved gateway values a launched driver needs. +pub struct GatewayStartup<'a> { + pub bind_socket: &'a Path, + pub log_level: &'a str, + pub gateway_name: &'a str, + pub gateway_port: u16, + /// The gateway's `guest_tls_ca`, when the driver should use it. + pub tls_ca: Option<&'a Path>, + pub otlp: Option<&'a OtlpConfig>, + pub network_trust: Option<&'a NetworkSupervisorTrustBundle>, +} + +impl GatewayStartup<'_> { + /// Combine the gateway context with the selected driver's `driver_config` + /// table, which the gateway passes through without interpreting. + /// + /// # Errors + /// + /// Returns an error when the trust bundle's certificate count does not fit + /// the document. + pub fn into_document(self, driver_config: toml::Table) -> Result { + let supervisor_otlp = self + .otlp + .map(OtlpConfig::supervisor_otlp) + .unwrap_or_default(); + let network_trust = self + .network_trust + .map(|bundle| { + Ok::<_, Error>(sdk::NetworkTrust { + path: bundle.artifact_path().to_path_buf(), + digest: bundle.digest().to_string(), + certificate_count: u32::try_from(bundle.certificate_count()).map_err(|_| { + Error::config("network trust bundle has too many certificates") + })?, + }) + }) + .transpose()?; + + let gateway = sdk::GatewayContext { + bind_socket: self.bind_socket.to_path_buf(), + expected_peer_pid: std::process::id(), + log_level: self.log_level.to_string(), + gateway_name: self.gateway_name.to_string(), + gateway_port: self.gateway_port, + tls_ca: self.tls_ca.map(Path::to_path_buf), + telemetry: sdk::Telemetry { + traces: supervisor_otlp.traces, + ocsf: supervisor_otlp.ocsf, + agent: supervisor_otlp.agent, + collector: self.otlp.and_then(collector_tls), + }, + network_trust, + }; + Ok(sdk::StartupDocument::new(gateway, driver_config)) + } +} + +/// TLS file paths for the trace collector, as the VM launch forwards them. The +/// other lanes use their own collectors and are not covered by these paths. +fn collector_tls(otlp: &OtlpConfig) -> Option { + let collector = &otlp.traces.as_ref()?.collector; + let tls = sdk::CollectorTls { + ca_file: collector.ca_file().map(Path::to_path_buf), + cert_file: collector.cert_file().map(Path::to_path_buf), + key_file: collector.key_file().map(Path::to_path_buf), + }; + (tls != sdk::CollectorTls::default()).then_some(tls) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::sandbox_env::OtlpProtocol; + use openshell_server::config_file::{ + AgentOtlpConfig, OcsfOtlpConfig, OtlpCollectorConfig, OtlpTracesConfig, + }; + use std::path::PathBuf; + + fn collector_with_tls(dir: &Path) -> OtlpCollectorConfig { + let certified = rcgen::generate_simple_self_signed(vec!["collector".into()]).unwrap(); + let [ca, cert, key] = ["ca.pem", "client.pem", "client-key.pem"].map(|name| { + let path = dir.join(name); + let pem = if name == "client-key.pem" { + certified.signing_key.serialize_pem() + } else { + certified.cert.pem() + }; + std::fs::write(&path, pem).unwrap(); + path + }); + OtlpCollectorConfig::new("https://collector.example:4317", OtlpProtocol::Grpc) + .with_tls_files(Some(ca), Some(cert), Some(key)) + .unwrap() + } + + /// Every field the gateway can resolve is set, so a field added to the + /// document and left out of the conversion shows up as a difference from + /// the fixture. + #[test] + fn a_fully_populated_gateway_converts_to_the_golden_fixture() { + let dir = tempfile::tempdir().unwrap(); + let otlp = OtlpConfig { + metrics: None, + service_name: None, + traces: Some(OtlpTracesConfig { + collector: collector_with_tls(dir.path()), + }), + ocsf: Some(OcsfOtlpConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4318", + OtlpProtocol::HttpProtobuf, + ), + schema_version: None, + }), + agent: Some(AgentOtlpConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4319", + OtlpProtocol::Grpc, + ), + }), + }; + let trust = NetworkSupervisorTrustBundle::new( + b"pem".to_vec(), + 3, + "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), + ); + let driver_config: toml::Table = toml::from_str( + "state_dir = \"/var/lib/openshell/vm\"\nvcpus = 2\n[nested]\nkey = \"value\"\n", + ) + .unwrap(); + + let mut document = GatewayStartup { + bind_socket: Path::new("/var/lib/openshell/run/compute-driver.sock"), + log_level: "info", + gateway_name: "gateway-a", + gateway_port: 8080, + tls_ca: Some(Path::new("/etc/openshell/tls/ca.pem")), + otlp: Some(&otlp), + network_trust: Some(&trust), + } + .into_document(driver_config) + .unwrap(); + + // The gateway's own pid and the temporary TLS file locations are the + // only values that differ from the committed fixture. + assert_eq!(document.gateway.expected_peer_pid, std::process::id()); + document.gateway.expected_peer_pid = 4242; + let tls = document.gateway.telemetry.collector.as_mut().unwrap(); + for (path, fixed) in [ + (&mut tls.ca_file, "/etc/openshell/otlp/ca.pem"), + (&mut tls.cert_file, "/etc/openshell/otlp/cert.pem"), + (&mut tls.key_file, "/etc/openshell/otlp/key.pem"), + ] { + assert!(path.as_deref().unwrap().starts_with(dir.path())); + *path = Some(fixed.into()); + } + + let fixture = sdk::StartupDocument::parse(include_str!( + "../../openshell-driver-sdk/tests/fixtures/startup-v1.toml" + )) + .unwrap(); + assert_eq!(document, fixture); + } + + #[test] + fn an_unconfigured_gateway_omits_optional_settings() { + let document = GatewayStartup { + bind_socket: Path::new("/run/driver.sock"), + log_level: "debug", + gateway_name: "gateway", + gateway_port: 8080, + tls_ca: None, + otlp: None, + network_trust: None, + } + .into_document(toml::Table::new()) + .unwrap(); + + let text = document.to_toml().unwrap(); + for absent in ["telemetry", "network_trust", "tls_ca"] { + assert!( + !text.contains(absent), + "{absent} should be omitted:\n{text}" + ); + } + assert!(document.driver_config.is_empty()); + } + + #[test] + fn the_document_carries_trust_artifact_metadata_not_certificate_bytes() { + let trust = NetworkSupervisorTrustBundle::new( + b"private-fixture-bytes".to_vec(), + 1, + "sha256:abc", + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), + ); + let text = GatewayStartup { + bind_socket: Path::new("/run/driver.sock"), + log_level: "info", + gateway_name: "gateway", + gateway_port: 8080, + tls_ca: None, + otlp: None, + network_trust: Some(&trust), + } + .into_document(toml::Table::new()) + .unwrap() + .to_toml() + .unwrap(); + assert!(!text.contains("private-fixture-bytes")); + assert!(text.contains("sha256:abc")); + } +} diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index 1f64a329a2..e97fb9fcb7 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -1,135 +1,34 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! VM compute driver plumbing. +//! Launching the VM compute driver through the generic launcher. //! -//! This module owns everything needed to hand the gateway a `Channel` speaking -//! the `openshell.compute.v1.ComputeDriver` RPC surface against an -//! `openshell-driver-vm` subprocess over a Unix domain socket: -//! -//! - [`VmComputeConfig`]: gateway-local configuration (state dir, driver binary, -//! VM shape, guest TLS material). -//! - [`spawn`]: spawn the driver subprocess, wait for its UDS to be ready, -//! and return a live gRPC channel plus a [`ManagedDriverProcess`] handle -//! that will reap the subprocess and clean up the socket on drop. -//! - Helpers to resolve the driver binary, compute the socket path, and -//! validate guest TLS material when the gateway runs an `https://` control -//! plane. -//! -//! The VM-driver fields deliberately live here rather than in -//! [`openshell_core::Config`] so the shared core stays free of driver-specific -//! plumbing. -//! -//! Process launch remains deliberately VM-specific at this binary composition -//! boundary: it translates gateway configuration into the standalone driver's -//! argv and then connects through the same public compute-driver RPC interface -//! used by operator-managed external drivers. +//! The gateway reads only the launcher's own keys (`driver_dir`, `state_dir`) +//! from the operator's `[openshell.drivers.vm]` table. The VM driver owns and +//! validates the rest of the table, which the gateway passes through as the +//! startup document's `driver_config`. -#[cfg(unix)] -use hyper_util::rt::TokioIo; -#[cfg(unix)] -use openshell_core::proto::compute::v1::{ - GetCapabilitiesRequest, compute_driver_client::ComputeDriverClient, -}; -use openshell_core::sandbox_env::{self, OtlpExport, OtlpProtocol}; -use openshell_core::{Error, NetworkSupervisorTrustBundle, Result, UpstreamProxyConfig}; -#[cfg(unix)] -use openshell_otel::TraceContextInterceptor; +use crate::launcher::{self, DriverProcess}; +use openshell_core::{Error, NetworkSupervisorTrustBundle, Result}; use openshell_server::AcquiredRemoteDriverEndpoint; -#[cfg(unix)] -use openshell_server::ManagedDriverProcess; use openshell_server::config_file::OtlpConfig; -#[cfg(unix)] -use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; -#[cfg(unix)] -use std::path::Path; -use std::path::PathBuf; -#[cfg(unix)] -use std::{io::ErrorKind, process::Stdio, sync::Arc, time::Duration}; -#[cfg(unix)] -use tokio::net::UnixStream; -#[cfg(unix)] -use tokio::process::Command; -use tonic::transport::Channel; -#[cfg(unix)] -use tonic::transport::Endpoint; -#[cfg(unix)] -use tower::service_fn; +use std::path::{Path, PathBuf}; const DRIVER_BIN_NAME: &str = "openshell-driver-vm"; -const COMPUTE_DRIVER_SOCKET_RUN_DIR: &str = "run"; -const COMPUTE_DRIVER_SOCKET_NAME: &str = "compute-driver.sock"; - -/// Configuration for launching and talking to the VM compute driver. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct VmComputeConfig { - pub allow_driver_config: bool, - pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - /// Working directory for VM driver sandbox state. - pub state_dir: PathBuf, +const DRIVER_DIR_KEY: &str = "[openshell.drivers.vm].driver_dir"; +/// The launcher's view of `[openshell.drivers.vm]`. +#[derive(Debug, Clone, Default, serde::Deserialize)] +pub struct VmLaunchSettings { /// Directory to search for compute-driver binaries before the gateway /// falls back to its conventional install paths and sibling binary. pub driver_dir: Option, - - /// Default sandbox image the driver should use when a request omits one. - pub default_image: String, - - /// Gateway gRPC endpoint the sandbox guest connects back to. - pub grpc_endpoint: String, - - /// Bootstrap image used to boot and prepare VM sandbox target images. - pub bootstrap_image: String, - - /// libkrun log level used by the VM driver helper. - pub krun_log_level: u32, - - /// Default vCPU count for VM sandboxes. - pub vcpus: u8, - - /// Default memory allocation for VM sandboxes, in MiB. - pub mem_mib: u32, - - /// Writable overlay disk size for each VM sandbox, in MiB. - pub overlay_disk_mib: u64, - - /// Optional UID override for the VM guest sandbox account. - pub sandbox_uid: Option, - - /// Optional GID override for the VM guest sandbox account. - pub sandbox_gid: Option, - - /// Directory shared with the gateway for request-scoped rootfs tar staging. - pub rootfs_tar_staging_dir: Option, - - /// Maximum accepted rootfs tar size, in bytes, before and after decompression. - pub rootfs_tar_max_bytes: Option, - - /// Host-side CA certificate used to authenticate the gateway. - pub guest_tls_ca: Option, - - /// Corporate forward-proxy settings passed to the VM driver. Flattening - /// preserves the shared local-driver TOML field names. - #[serde(flatten)] - pub upstream_proxy: UpstreamProxyConfig, - - /// Path on the gateway host to a PEM CA bundle trusted for the corporate - /// proxy and for server certificates re-signed by a TLS-intercepting proxy. - pub proxy_ca_bundle: Option, - - /// Explicit guest-reachable SPIFFE Workload API TCP listener. VM guests - /// cannot receive a host UNIX socket, so this requires acknowledgement. - pub provider_spiffe_workload_api_tcp_endpoint: Option, - #[serde(default)] - pub provider_spiffe_allow_guest_tcp: bool, - - /// Allow bind-mounting host directories into VM sandboxes. - #[serde(default)] - pub enable_bind_mounts: bool, + /// Working directory for VM driver state, which holds the private run + /// directory with the driver socket and startup document. + pub state_dir: Option, } -impl VmComputeConfig { +impl VmLaunchSettings { /// Default working directory for VM driver state. #[must_use] pub fn default_state_dir() -> PathBuf { @@ -139,792 +38,154 @@ impl VmComputeConfig { ) } - /// Default libkrun log level. - #[must_use] - pub const fn default_krun_log_level() -> u32 { - 1 - } - - /// Default vCPU count. - #[must_use] - pub const fn default_vcpus() -> u8 { - 2 - } - - /// Default memory allocation, in MiB. - #[must_use] - pub const fn default_mem_mib() -> u32 { - 2048 - } - - /// Default writable overlay disk size, in MiB. - #[must_use] - pub const fn default_overlay_disk_mib() -> u64 { - 4096 - } - - /// Validate startup configuration without resolving binaries, creating - /// state directories, spawning a process, or connecting a socket. - pub fn validate_configuration(&self) -> Result<()> { - self.resource_admission.validate().map_err(Error::config)?; - if self.grpc_endpoint.trim().is_empty() { - return Err(Error::config( - "grpc_endpoint is required when using the vm compute driver", - )); - } - if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { - return Err(Error::config( - "bootstrap_image or default_image is required when using the vm compute driver; sandbox images cannot be used as VM bootstrap images", - )); - } - validate_vm_sandbox_identity(self)?; - if self - .rootfs_tar_staging_dir + /// Read the launcher's keys from the operator's driver table. + /// + /// # Errors + /// + /// Returns an error when `driver_dir` or `state_dir` has the wrong type. + pub fn from_table(table: &toml::Table) -> Result { + let mut settings: Self = + toml::Value::Table(table.clone()) + .try_into() + .map_err(|error: toml::de::Error| { + Error::config(format!("invalid [openshell.drivers.vm] table: {error}")) + })?; + if settings + .state_dir .as_ref() - .is_some_and(|path| path.as_os_str().is_empty()) + .is_none_or(|dir| dir.as_os_str().is_empty()) { - return Err(Error::config( - "rootfs_tar_staging_dir must not be empty when set", - )); - } - if self.rootfs_tar_max_bytes == Some(0) { - return Err(Error::config( - "rootfs_tar_max_bytes must be greater than zero when set", - )); - } - self.validate_proxy_config()?; - if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { - openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( - endpoint, - self.provider_spiffe_allow_guest_tcp, - ) - .map_err(Error::config)?; - } else if self.provider_spiffe_allow_guest_tcp { - return Err(Error::config( - "provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured", - )); - } - Ok(()) - } - - fn validate_proxy_config(&self) -> Result<()> { - self.upstream_proxy.validate().map_err(Error::config)?; - if let Some(path) = self.proxy_ca_bundle.as_ref() { - if path.as_os_str().is_empty() { - return Err(Error::config("proxy_ca_bundle must not be empty when set")); - } - if self.upstream_proxy.https_proxy.is_none() { - return Err(Error::config( - "proxy_ca_bundle is set but no https_proxy is configured", - )); - } + settings.state_dir = Some(Self::default_state_dir()); } - Ok(()) + Ok(settings) } - #[must_use] - fn default_driver_search_dirs(home: Option) -> Vec { - let mut dirs = Vec::new(); - if let Some(home) = home { - dirs.push(home.join(".local").join("libexec").join("openshell")); - } - push_unique_path(&mut dirs, PathBuf::from("/usr/libexec/openshell")); - push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec/openshell")); - push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec")); - dirs + fn state_dir(&self) -> PathBuf { + self.state_dir + .clone() + .unwrap_or_else(Self::default_state_dir) } } -impl Default for VmComputeConfig { - fn default() -> Self { - Self { - state_dir: Self::default_state_dir(), - allow_driver_config: false, - resource_admission: - openshell_core::resource_admission::ResourceAdmissionConfig::default(), - driver_dir: None, - default_image: openshell_core::image::default_sandbox_image(), - grpc_endpoint: String::new(), - bootstrap_image: String::new(), - krun_log_level: Self::default_krun_log_level(), - vcpus: Self::default_vcpus(), - mem_mib: Self::default_mem_mib(), - overlay_disk_mib: Self::default_overlay_disk_mib(), - sandbox_uid: None, - sandbox_gid: None, - rootfs_tar_staging_dir: None, - rootfs_tar_max_bytes: None, - guest_tls_ca: None, - upstream_proxy: UpstreamProxyConfig::default(), - proxy_ca_bundle: None, - provider_spiffe_workload_api_tcp_endpoint: None, - provider_spiffe_allow_guest_tcp: false, - enable_bind_mounts: false, - } - } +/// Everything the gateway supplies to launch the VM driver. +pub struct VmLaunch<'a> { + pub gateway_log_level: &'a str, + pub gateway_name: &'a str, + pub gateway_port: u16, + /// The gateway's `guest_tls_ca`, when it serves TLS. + pub tls_ca: Option<&'a Path>, + pub otlp_config: Option<&'a OtlpConfig>, + pub network_trust: Option<&'a NetworkSupervisorTrustBundle>, + /// Becomes true when the gateway begins shutting down. + pub shutdown: tokio::sync::watch::Receiver, + pub settings: &'a VmLaunchSettings, + /// The operator's `[openshell.drivers.vm]` table, passed through. + pub driver_config: toml::Table, } -#[cfg(unix)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct VmGuestTlsPaths { - pub ca: PathBuf, -} - -/// Resolve the `openshell-driver-vm` binary path. -/// -/// Resolution order: -/// 1. `{driver_dir}/openshell-driver-vm`, where `driver_dir` comes from -/// `[openshell.drivers.vm].driver_dir`. -/// 2. Conventional install directories: -/// `~/.local/libexec/openshell`, `/usr/libexec/openshell`, -/// `/usr/local/libexec/openshell`, `/usr/local/libexec`. -/// 3. Sibling of the gateway's own executable (last-resort fallback so -/// local development builds still work out of the box). -pub fn resolve_compute_driver_bin(vm_config: &VmComputeConfig) -> Result { - let mut searched: Vec = Vec::new(); - - // 1. Configured driver directory, or the conventional install locations - // when no explicit override is configured. - for dir in resolve_driver_search_dirs(vm_config) { - let candidate = dir.join(DRIVER_BIN_NAME); - if candidate.is_file() { - return Ok(candidate); - } - push_unique_path(&mut searched, candidate); - } - - // 2. Sibling-of-gateway fallback. - let current_exe = std::env::current_exe() - .map_err(|e| Error::config(format!("failed to resolve current executable: {e}")))?; - let Some(parent) = current_exe.parent() else { - return Err(Error::config(format!( - "current executable '{}' has no parent directory", - current_exe.display() - ))); - }; - let sibling = parent.join(DRIVER_BIN_NAME); - if sibling.is_file() { - return Ok(sibling); - } - push_unique_path(&mut searched, sibling); - - let searched_display = searched - .iter() - .map(|p| format!("'{}'", p.display())) - .collect::>() - .join(", "); - Err(Error::config(format!( - "vm compute driver binary not found (searched {searched_display}); install it under [openshell.drivers.vm].driver_dir, a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{{,/openshell}}, or place it next to the gateway binary" - ))) -} - -fn resolve_driver_search_dirs(vm_config: &VmComputeConfig) -> Vec { - vm_config.driver_dir.clone().map_or_else( - || { - let mut dirs = Vec::new(); - if let Ok(current_exe) = std::env::current_exe() - && let Some(prefix) = current_exe.parent().and_then(Path::parent) - { - push_unique_path(&mut dirs, prefix.join("libexec")); - push_unique_path(&mut dirs, prefix.join("libexec").join("openshell")); - } - for dir in VmComputeConfig::default_driver_search_dirs( - std::env::var_os("HOME").map(PathBuf::from), - ) { - push_unique_path(&mut dirs, dir); - } - dirs - }, - |dir| vec![dir], - ) -} - -fn push_unique_path(paths: &mut Vec, path: PathBuf) { - if !paths.iter().any(|existing| existing == &path) { - paths.push(path); - } -} - -/// Path of the Unix domain socket the driver will listen on. -pub fn compute_driver_socket_path(vm_config: &VmComputeConfig) -> PathBuf { - vm_config - .state_dir - .join(COMPUTE_DRIVER_SOCKET_RUN_DIR) - .join(COMPUTE_DRIVER_SOCKET_NAME) -} - -#[cfg(unix)] -fn prepare_compute_driver_socket_path( - vm_config: &VmComputeConfig, - socket_path: &Path, -) -> Result<()> { - let expected_uid = current_euid(); - prepare_vm_state_dir(&vm_config.state_dir, expected_uid)?; - let parent = socket_path.parent().ok_or_else(|| { - Error::execution(format!( - "vm compute driver socket path '{}' has no parent directory", - socket_path.display() - )) - })?; - prepare_private_socket_dir(parent, expected_uid)?; - remove_stale_socket(socket_path, expected_uid) -} - -#[cfg(unix)] -fn current_euid() -> u32 { - rustix::process::geteuid().as_raw() -} - -#[cfg(unix)] -fn prepare_vm_state_dir(state_dir: &Path, expected_uid: u32) -> Result<()> { - std::fs::create_dir_all(state_dir).map_err(|err| { - Error::execution(format!( - "failed to create vm driver state dir '{}': {err}", - state_dir.display() - )) - })?; - let metadata = checked_directory_metadata(state_dir, expected_uid, "vm driver state dir")?; - let mode = metadata.permissions().mode() & 0o777; - if mode != 0o700 { - std::fs::set_permissions(state_dir, std::fs::Permissions::from_mode(0o700)).map_err( - |err| { - Error::execution(format!( - "failed to restrict vm driver state dir '{}': {err}", - state_dir.display() - )) - }, - )?; - } - Ok(()) -} - -#[cfg(unix)] -fn prepare_private_socket_dir(socket_dir: &Path, expected_uid: u32) -> Result<()> { - std::fs::create_dir_all(socket_dir).map_err(|err| { - Error::execution(format!( - "failed to create vm compute driver socket dir '{}': {err}", - socket_dir.display() - )) - })?; - let _ = checked_directory_metadata(socket_dir, expected_uid, "vm compute driver socket dir")?; - std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)).map_err(|err| { - Error::execution(format!( - "failed to restrict vm compute driver socket dir '{}': {err}", - socket_dir.display() - )) - }) -} - -#[cfg(unix)] -fn checked_directory_metadata( - path: &Path, - expected_uid: u32, - label: &str, -) -> Result { - let metadata = std::fs::symlink_metadata(path).map_err(|err| { - Error::execution(format!( - "failed to stat {label} '{}': {err}", - path.display() - )) - })?; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(Error::execution(format!( - "{label} '{}' is a symlink; refusing to use it", - path.display() - ))); - } - if !file_type.is_dir() { - return Err(Error::execution(format!( - "{label} '{}' is not a directory", - path.display() - ))); - } - if metadata.uid() != expected_uid { - return Err(Error::execution(format!( - "{label} '{}' is owned by uid {} but current euid is {}", - path.display(), - metadata.uid(), - expected_uid - ))); - } - Ok(metadata) -} - -#[cfg(unix)] -fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<()> { - let metadata = match std::fs::symlink_metadata(socket_path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()), - Err(err) => { - return Err(Error::execution(format!( - "failed to stat vm compute driver socket '{}': {err}", - socket_path.display() - ))); - } +/// Launch the VM driver and return a managed endpoint for it. +pub async fn spawn(launch: VmLaunch<'_>) -> Result { + let settings = launch.settings; + let state_dir = settings.state_dir(); + let process = DriverProcess { + name: "vm", + binary_name: DRIVER_BIN_NAME, + driver_dir: settings.driver_dir.as_deref(), + driver_dir_key: Some(DRIVER_DIR_KEY), + state_dir: &state_dir, }; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(Error::execution(format!( - "vm compute driver socket '{}' is a symlink; refusing to remove it", - socket_path.display() - ))); - } - if metadata.uid() != expected_uid { - return Err(Error::execution(format!( - "vm compute driver socket '{}' is owned by uid {} but current euid is {}", - socket_path.display(), - metadata.uid(), - expected_uid - ))); - } - if !file_type.is_socket() { - return Err(Error::execution(format!( - "vm compute driver socket path '{}' exists but is not a Unix socket", - socket_path.display() - ))); - } - std::fs::remove_file(socket_path).map_err(|err| { - Error::execution(format!( - "failed to remove stale vm compute driver socket '{}': {err}", - socket_path.display() - )) + let otlp_config = launch.otlp_config; + let shutdown = launch.shutdown.clone(); + launcher::launch(&process, otlp_config, shutdown, |socket_path| { + vm_startup_document(launch, socket_path) }) + .await } -#[cfg(unix)] -pub fn compute_driver_guest_tls_paths( - vm_config: &VmComputeConfig, -) -> Result> { - if !vm_config.grpc_endpoint.starts_with("https://") { - return Ok(None); - } - - if vm_config.guest_tls_ca.is_none() { - return Err(Error::config( - "vm compute driver requires guest_tls_ca when grpc_endpoint uses https://", - )); - } - - let Some(ca) = vm_config.guest_tls_ca.clone() else { - return Err(Error::config( - "guest_tls_ca is required when VM guest TLS materials are configured", - )); - }; - for path in [&ca] { - if !path.is_file() { - return Err(Error::config(format!( - "vm guest TLS material '{}' does not exist or is not a file", - path.display() - ))); - } - } - - Ok(Some(VmGuestTlsPaths { ca })) -} - -/// Launch the VM compute-driver subprocess, wait for its UDS to come up, -/// and return a gRPC `Channel` connected to it plus a process handle that -/// kills the subprocess and removes the socket on drop. -#[cfg(unix)] -pub async fn spawn( +/// Have the VM driver validate the document the gateway would launch it with. +/// Values the gateway only knows once it serves, such as its TLS CA and the +/// staged network trust bundle, are left out. +pub fn preflight( gateway_log_level: &str, gateway_name: &str, - vm_config: &VmComputeConfig, - otlp_config: Option<&OtlpConfig>, - additional_ca_bundle: Option<&NetworkSupervisorTrustBundle>, -) -> Result { - vm_config.validate_configuration()?; - let driver_bin = resolve_compute_driver_bin(vm_config)?; - let socket_path = compute_driver_socket_path(vm_config); - let guest_tls_paths = compute_driver_guest_tls_paths(vm_config)?; - prepare_compute_driver_socket_path(vm_config, &socket_path)?; - - let mut command = Command::new(&driver_bin); - command.kill_on_drop(true); - command.stdin(Stdio::null()); - command.stdout(Stdio::inherit()); - command.stderr(Stdio::inherit()); - command.arg("--bind-socket").arg(&socket_path); - command.arg("--admission-config-json").arg( - serde_json::to_string(&openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: vm_config.allow_driver_config, - resource_admission: vm_config.resource_admission.clone(), - }) - .map_err(|error| Error::config(error.to_string()))?, - ); - command - .arg("--expected-peer-pid") - .arg(std::process::id().to_string()); - command.arg("--log-level").arg(gateway_log_level); - append_otlp_args(&mut command, otlp_config, gateway_name); - command.arg("--grpc-endpoint").arg(&vm_config.grpc_endpoint); - command.arg("--state-dir").arg(&vm_config.state_dir); - if !vm_config.default_image.trim().is_empty() { - command.arg("--default-image").arg(&vm_config.default_image); - } - if !vm_config.bootstrap_image.trim().is_empty() { - command - .arg("--bootstrap-image") - .arg(&vm_config.bootstrap_image); - } - command - .arg("--krun-log-level") - .arg(vm_config.krun_log_level.to_string()); - command.arg("--vcpus").arg(vm_config.vcpus.to_string()); - command.arg("--mem-mib").arg(vm_config.mem_mib.to_string()); - command - .arg("--overlay-disk-mib") - .arg(vm_config.overlay_disk_mib.to_string()); - append_vm_identity_args(&mut command, vm_config); - append_vm_rootfs_tar_args(&mut command, vm_config); - if let Some(tls) = guest_tls_paths { - command.arg("--guest-tls-ca").arg(tls.ca); - } - append_vm_proxy_and_spiffe_args(&mut command, vm_config); - append_vm_network_trust_args(&mut command, additional_ca_bundle); - if vm_config.enable_bind_mounts { - command.arg("--enable-bind-mounts"); - } - - let mut child = command.spawn().map_err(|e| { - Error::execution(format!( - "failed to launch vm compute driver '{}': {e}", - driver_bin.display() - )) - })?; - let channel = wait_for_compute_driver(&socket_path, &mut child).await?; - let process = Arc::new(ManagedDriverProcess::new(child, socket_path)); - Ok(AcquiredRemoteDriverEndpoint::managed( - "vm", channel, process, - )) -} - -fn validate_vm_sandbox_identity(config: &VmComputeConfig) -> Result<()> { - let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; - for (field, value) in [ - ("sandbox_uid", config.sandbox_uid), - ("sandbox_gid", config.sandbox_gid), - ] { - if let Some(value) = value - && !range.contains(&value) - { - return Err(Error::config(format!( - "{field} {value} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID - ))); - } - } - Ok(()) -} - -#[cfg(unix)] -fn append_vm_identity_args(command: &mut Command, config: &VmComputeConfig) { - if let Some(uid) = config.sandbox_uid { - command.arg("--sandbox-uid").arg(uid.to_string()); - } - if let Some(gid) = config.sandbox_gid { - command.arg("--sandbox-gid").arg(gid.to_string()); - } -} - -#[cfg(unix)] -fn append_vm_rootfs_tar_args(command: &mut Command, config: &VmComputeConfig) { - if let Some(path) = config.rootfs_tar_staging_dir.as_ref() { - command.arg("--rootfs-tar-staging-dir").arg(path); - } - if let Some(max_bytes) = config.rootfs_tar_max_bytes { - command - .arg("--rootfs-tar-max-bytes") - .arg(max_bytes.to_string()); - } -} - -#[cfg(unix)] -fn append_vm_network_trust_args( - command: &mut Command, - bundle: Option<&NetworkSupervisorTrustBundle>, -) { - if let Some(bundle) = bundle { - // Only stable, non-secret artifact metadata crosses the process - // boundary. The child reads and verifies the bounded artifact once, - // then retains its own immutable snapshot for sandbox launches. - command - .arg("--additional-ca-bundle") - .arg(bundle.artifact_path()); - command.arg("--additional-ca-digest").arg(bundle.digest()); - command - .arg("--additional-ca-certificate-count") - .arg(bundle.certificate_count().to_string()); - } -} - -#[cfg(unix)] -fn append_vm_proxy_and_spiffe_args(command: &mut Command, config: &VmComputeConfig) { - let proxy = &config.upstream_proxy; - if let Some(url) = proxy.https_proxy.as_ref() { - command.arg("--upstream-proxy").arg(url); - } - if let Some(no_proxy) = proxy.no_proxy.as_ref() { - command.arg("--upstream-no-proxy").arg(no_proxy); - } - if let Some(auth_file) = proxy.proxy_auth_file.as_ref() { - command.arg("--upstream-proxy-auth-file").arg(auth_file); - } - if proxy.proxy_auth_allow_insecure == Some(true) { - command.arg("--upstream-proxy-auth-allow-insecure"); - } - if proxy.proxy_connect_by_hostname == Some(true) { - command.arg("--upstream-proxy-connect-by-hostname"); - } - if let Some(path) = config.proxy_ca_bundle.as_ref() { - command.arg("--upstream-proxy-ca-bundle").arg(path); - } - if let Some(endpoint) = config.provider_spiffe_workload_api_tcp_endpoint.as_ref() { - command - .arg("--provider-spiffe-workload-api-tcp-endpoint") - .arg(endpoint); - command.arg("--provider-spiffe-allow-guest-tcp"); - } -} - -fn append_otlp_export_args( - command: &mut Command, - export: Option<&OtlpExport>, - endpoint_flag: &str, - protocol_flag: &str, -) { - if let Some(export) = export { - command - .arg(format!("--{endpoint_flag}")) - .arg(&export.endpoint); - if export.protocol != OtlpProtocol::Grpc { - command - .arg(format!("--{protocol_flag}")) - .arg(export.protocol.as_str()); - } - } -} - -fn append_otlp_args(command: &mut Command, otlp_config: Option<&OtlpConfig>, gateway_name: &str) { - let otlp = otlp_config - .map(OtlpConfig::supervisor_otlp) - .unwrap_or_default(); - append_otlp_export_args( - command, - otlp.traces.as_ref(), - sandbox_env::OTLP_ENDPOINT_FLAG, - sandbox_env::OTLP_PROTOCOL_FLAG, - ); - append_otlp_export_args( - command, - otlp.ocsf.as_ref(), - sandbox_env::OTLP_OCSF_ENDPOINT_FLAG, - sandbox_env::OTLP_OCSF_PROTOCOL_FLAG, - ); - append_otlp_export_args( - command, - otlp.agent.as_ref(), - sandbox_env::OTLP_AGENT_ENDPOINT_FLAG, - sandbox_env::OTLP_AGENT_PROTOCOL_FLAG, - ); - if let Some(traces) = otlp_config.and_then(|otlp| otlp.traces.as_ref()) { - let collector = &traces.collector; - for (flag, path) in [ - (sandbox_env::OTLP_CA_FILE_FLAG, collector.ca_file()), - (sandbox_env::OTLP_CERT_FILE_FLAG, collector.cert_file()), - (sandbox_env::OTLP_KEY_FILE_FLAG, collector.key_file()), - ] { - if let Some(path) = path { - command.arg(format!("--{flag}")).arg(path); - } - } - } - // The driver's own trace exporter reads this like any OTLP SDK; keeping - // it out of the arguments keeps the headers out of process listings. - if let Some(headers) = openshell_server::gateway_trace_headers(otlp_config) { - command.env("OTEL_EXPORTER_OTLP_TRACES_HEADERS", headers.expose_secret()); - } - // The driver names its own spans with the gateway name, and supervisors - // name their spans, OCSF records, and relayed traces with it. - if !otlp.is_empty() { - command.arg("--gateway-name").arg(gateway_name); - } + gateway_port: u16, + driver_config: toml::Table, +) -> Result<()> { + let settings = VmLaunchSettings::from_table(&driver_config)?; + let state_dir = settings.state_dir(); + let process = DriverProcess { + name: "vm", + binary_name: DRIVER_BIN_NAME, + driver_dir: settings.driver_dir.as_deref(), + driver_dir_key: Some(DRIVER_DIR_KEY), + state_dir: &state_dir, + }; + launcher::preflight(&process, launcher::PREFLIGHT_TIMEOUT, |socket_path| { + vm_startup_document( + VmLaunch { + gateway_log_level, + gateway_name, + gateway_port, + tls_ca: None, + otlp_config: None, + network_trust: None, + shutdown: tokio::sync::watch::channel(false).1, + settings: &settings, + driver_config, + }, + socket_path, + ) + }) } -#[cfg(not(unix))] -pub async fn spawn( - _gateway_log_level: &str, - _gateway_name: &str, - _vm_config: &VmComputeConfig, - _otlp_config: Option<&OtlpConfig>, - _additional_ca_bundle: Option<&NetworkSupervisorTrustBundle>, -) -> Result { - Err(Error::config( - "the vm compute driver requires unix domain socket support", - )) +/// The VM driver's `[driver_config]`: the operator's table, passed through, +/// without the launcher-owned `driver_dir`. +fn vm_driver_config_table(mut table: toml::Table) -> toml::Table { + table.remove("driver_dir"); + table } -#[cfg(unix)] -#[tracing::instrument( - name = "driver.wait_for_ready", - skip_all, - fields( - otel.name = "driver.wait_for_ready", - otel.status_code = tracing::field::Empty, - driver.name = "vm", - ) -)] -async fn wait_for_compute_driver( +fn vm_startup_document( + launch: VmLaunch<'_>, socket_path: &Path, - child: &mut tokio::process::Child, -) -> Result { - let mut last_error: Option = None; - for _ in 0..100 { - let try_wait_result = child.try_wait().map_err(|e| { - Error::execution(format!("failed to poll vm compute driver process: {e}")) - })?; - if let Some(status) = try_wait_result { - return Err(Error::execution(format!( - "vm compute driver exited before becoming ready with status {status}" - ))); - } - - match connect_compute_driver(socket_path).await { - Ok(channel) => { - let mut client = - ComputeDriverClient::with_interceptor(channel.clone(), TraceContextInterceptor); - match client - .get_capabilities(tonic::Request::new(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - { - Ok(_) => return Ok(channel), - Err(status) => last_error = Some(status.to_string()), - } - } - Err(err) => last_error = Some(err.to_string()), - } - - tokio::time::sleep(Duration::from_millis(100)).await; - } - - Err(Error::execution(format!( - "timed out waiting for vm compute driver socket '{}': {}", - socket_path.display(), - last_error.unwrap_or_else(|| "unknown error".to_string()) - ))) -} - -#[cfg(unix)] -async fn connect_compute_driver(socket_path: &Path) -> Result { - let socket_path = socket_path.to_path_buf(); - let display_path = socket_path.clone(); - Endpoint::from_static("http://[::]:50051") - .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { - let socket_path = socket_path.clone(); - async move { UnixStream::connect(socket_path).await.map(TokioIo::new) } - })) - .await - .map_err(|e| { - Error::execution(format!( - "failed to connect to vm compute driver socket '{}': {e}", - display_path.display() - )) - }) +) -> Result { + crate::startup_document::GatewayStartup { + bind_socket: socket_path, + log_level: launch.gateway_log_level, + gateway_name: launch.gateway_name, + gateway_port: launch.gateway_port, + tls_ca: launch.tls_ca, + otlp: launch.otlp_config, + network_trust: launch.network_trust, + } + .into_document(vm_driver_config_table(launch.driver_config)) } #[cfg(all(test, unix))] mod tests { - use super::{ - VmComputeConfig, append_otlp_args, append_vm_identity_args, append_vm_network_trust_args, - append_vm_proxy_and_spiffe_args, append_vm_rootfs_tar_args, compute_driver_guest_tls_paths, - compute_driver_socket_path, current_euid, prepare_compute_driver_socket_path, - prepare_vm_state_dir, resolve_compute_driver_bin, resolve_driver_search_dirs, - validate_vm_sandbox_identity, - }; + use super::{VmLaunch, VmLaunchSettings, vm_driver_config_table, vm_startup_document}; + use openshell_core::NetworkSupervisorTrustBundle; use openshell_core::sandbox_env::OtlpProtocol; - use openshell_core::{NetworkSupervisorTrustBundle, UpstreamProxyConfig}; use openshell_server::config_file::{ AgentOtlpConfig, OcsfOtlpConfig, OtlpCollectorConfig, OtlpConfig, OtlpTracesConfig, }; - use std::os::unix::fs::PermissionsExt; - use std::os::unix::net::UnixListener as StdUnixListener; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; use tempfile::tempdir; - #[test] - fn vm_uses_nvidia_ubuntu_default_image() { - assert_eq!( - VmComputeConfig::default().default_image, - openshell_core::image::DEFAULT_SANDBOX_BASE_IMAGE - ); - } + const VM_STARTUP_FIXTURE: &str = + include_str!("../../openshell-driver-vm/tests/fixtures/startup-vm.toml"); - #[test] - fn vm_gateway_requires_a_trusted_bootstrap_image_source() { - let config = VmComputeConfig { - grpc_endpoint: "http://127.0.0.1:50051".to_string(), - default_image: String::new(), - bootstrap_image: String::new(), - ..Default::default() - }; - let error = config - .validate_configuration() - .expect_err("the gateway must reject an empty bootstrap configuration"); - assert!(error.to_string().contains("sandbox images cannot be used")); - - VmComputeConfig { - default_image: "openshell/sandbox:default".to_string(), - ..config.clone() - } - .validate_configuration() - .expect("the operator-controlled default image is a valid fallback"); - - VmComputeConfig { - bootstrap_image: "openshell/sandbox-bootstrap:latest".to_string(), - ..config - } - .validate_configuration() - .expect("an explicit bootstrap image is valid"); - } - - #[test] - fn vm_driver_receives_trace_headers_in_its_environment_only() { - crate::test_environment::Environment::new() - .remove("OTEL_EXPORTER_OTLP_HEADERS") - .remove("OTEL_EXPORTER_OTLP_TRACES_HEADERS") - .run(|| { - let otlp: OtlpConfig = toml::from_str( - "endpoint = 'http://collector.internal:4318'\n\ - headers = { authorization = 'Bearer secret-token' }\n", - ) - .unwrap(); - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args(&mut command, Some(&otlp), "production-us-west"); - - let env = command - .as_std() - .get_envs() - .find(|(name, _)| *name == "OTEL_EXPORTER_OTLP_TRACES_HEADERS") - .and_then(|(_, value)| value) - .map(|value| value.to_string_lossy().into_owned()); - assert_eq!(env.as_deref(), Some("authorization=Bearer%20secret-token")); - assert!( - command - .as_std() - .get_args() - .all(|arg| !arg.to_string_lossy().contains("secret-token")) - ); - }); + fn fixture_driver_config() -> toml::Table { + openshell_driver_sdk::StartupDocument::parse(VM_STARTUP_FIXTURE) + .unwrap() + .driver_config } + /// The gateway passes the operator's table through unchanged, apart from + /// the launcher-owned `driver_dir`, and adds the gateway context the + /// driver's own tests read from the same fixture. #[test] - fn vm_driver_receives_the_trace_collectors_tls_file_paths() { + fn the_gateway_writes_the_documented_startup_document() { let dir = tempdir().unwrap(); let certified = rcgen::generate_simple_self_signed(vec!["collector".into()]).unwrap(); let [ca, cert, key] = ["ca.pem", "client.pem", "client-key.pem"].map(|name| { @@ -937,667 +198,89 @@ mod tests { std::fs::write(&path, pem).unwrap(); path }); - let collector = OtlpCollectorConfig::new("https://collector:4317", OtlpProtocol::Grpc) - .with_tls_files(Some(ca.clone()), Some(cert.clone()), Some(key.clone())) - .unwrap(); - assert!(collector.tls().client_identity().is_some()); let otlp = OtlpConfig { metrics: None, service_name: None, - traces: Some(OtlpTracesConfig { collector }), - ocsf: None, - agent: None, - }; - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args(&mut command, Some(&otlp), "production-us-west"); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - for (flag, path) in [ - ("--otlp-ca-file", ca), - ("--otlp-cert-file", cert), - ("--otlp-key-file", key), - ] { - let pair = [flag.to_string(), path.display().to_string()]; - assert!( - args.windows(2).any(|window| window == pair), - "{pair:?} in {args:?}" - ); - } - } - - #[test] - fn vm_driver_command_includes_gateway_otlp_configuration() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: Some("custom-gateway".to_string()), - traces: Some(OtlpTracesConfig { - collector: OtlpCollectorConfig::new( - "http://collector.internal:4317", - OtlpProtocol::Grpc, - ), - }), - ocsf: None, - agent: None, - }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-endpoint", - "http://collector.internal:4317", - "--gateway-name", - "production-us-west" - ] - ); - - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: Some(OtlpTracesConfig { - collector: OtlpCollectorConfig::new( - "http://collector.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - }), - ocsf: None, - agent: None, + traces: Some(OtlpTracesConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4317", + OtlpProtocol::Grpc, + ) + .with_tls_files(Some(ca), Some(cert), Some(key)) + .unwrap(), }), - "production-us-west", - ); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args[..4], - [ - "--otlp-endpoint", - "http://collector.internal:4318", - "--otlp-protocol", - "http/protobuf", - ] - ); - } - - #[test] - fn vm_driver_command_includes_gateway_ocsf_export() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: None, - ocsf: Some(OcsfOtlpConfig { - collector: OtlpCollectorConfig::new( - "http://siem.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - schema_version: Some("2.0".into()), - }), - agent: None, + ocsf: Some(OcsfOtlpConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4318", + OtlpProtocol::HttpProtobuf, + ), + schema_version: None, }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-ocsf-endpoint", - "http://siem.internal:4318", - "--otlp-ocsf-protocol", - "http/protobuf", - "--gateway-name", - "production-us-west" - ] - ); - } - - #[test] - fn vm_driver_command_includes_the_agent_trace_relay() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: None, - ocsf: None, - agent: Some(AgentOtlpConfig { - collector: OtlpCollectorConfig::new( - "http://agents.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - }), + agent: Some(AgentOtlpConfig { + collector: OtlpCollectorConfig::new( + "https://collector.example:4319", + OtlpProtocol::Grpc, + ), }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-agent-endpoint", - "http://agents.internal:4318", - "--otlp-agent-protocol", - "http/protobuf", - "--gateway-name", - "production-us-west" - ] - ); - } - - #[test] - fn vm_driver_command_forwards_corporate_proxy_settings() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args( - &mut command, - &VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - no_proxy: Some("10.0.0.0/8".to_string()), - proxy_auth_file: Some(PathBuf::from("/etc/openshell/secrets/proxy-auth")), - proxy_auth_allow_insecure: Some(true), - proxy_connect_by_hostname: Some(true), - }, - proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")), - provider_spiffe_workload_api_tcp_endpoint: Some("tcp:192.0.2.10:8081".to_string()), - provider_spiffe_allow_guest_tcp: true, - ..VmComputeConfig::default() - }, - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--upstream-proxy", - "http://proxy.corp.com:8080", - "--upstream-no-proxy", - "10.0.0.0/8", - "--upstream-proxy-auth-file", - "/etc/openshell/secrets/proxy-auth", - "--upstream-proxy-auth-allow-insecure", - "--upstream-proxy-connect-by-hostname", - "--upstream-proxy-ca-bundle", - "/etc/openshell/tls/proxy-ca.pem", - "--provider-spiffe-workload-api-tcp-endpoint", - "tcp:192.0.2.10:8081", - "--provider-spiffe-allow-guest-tcp", - ] - ); - } - - #[test] - fn vm_driver_command_omits_unset_corporate_proxy_settings() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args(&mut command, &VmComputeConfig::default()); - assert_eq!(command.as_std().get_args().count(), 0); - } - - #[test] - fn vm_driver_command_forwards_only_network_trust_artifact_metadata() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - let pem = - b"-----BEGIN CERTIFICATE-----\nprivate-fixture-bytes\n-----END CERTIFICATE-----\n"; - let bundle = NetworkSupervisorTrustBundle::new( - pem.to_vec(), - 2, + }; + let trust = NetworkSupervisorTrustBundle::new( + b"pem".to_vec(), + 3, "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - PathBuf::from("/var/lib/openshell/network/additional-ca.crt"), - ); - append_vm_network_trust_args(&mut command, Some(&bundle)); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--additional-ca-bundle", - "/var/lib/openshell/network/additional-ca.crt", - "--additional-ca-digest", - "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - "--additional-ca-certificate-count", - "2", - ] + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), ); - assert!(!args.iter().any(|arg| arg == "OPENSHELL_TLS_CA")); - assert!( - !args.iter().any(|arg| arg.contains("private-fixture-bytes")), - "CA material must not cross the process boundary in argv: {args:?}" - ); - - let mut unset = tokio::process::Command::new("openshell-driver-vm"); - append_vm_network_trust_args(&mut unset, None); - assert_eq!(unset.as_std().get_args().count(), 0); - } - - #[test] - fn invalid_corporate_proxy_config_is_rejected_before_the_driver_starts() { - let err = UpstreamProxyConfig { - https_proxy: Some("socks5://proxy.corp.com:1080".to_string()), - ..Default::default() - } - .validate() - .expect_err("only http:// and https:// proxies are supported"); - assert!(err.contains("https_proxy"), "{err}"); - - VmComputeConfig { - proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")), - ..Default::default() - } - .validate_proxy_config() - .expect_err("a CA bundle without a proxy URL must fail closed"); - - VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - ..Default::default() + let mut operator_table = fixture_driver_config(); + operator_table.insert("driver_dir".into(), "/usr/libexec/openshell".into()); + let settings = VmLaunchSettings::from_table(&operator_table).unwrap(); + + let mut document = vm_startup_document( + VmLaunch { + gateway_log_level: "debug", + gateway_name: "gateway-a", + gateway_port: 8080, + tls_ca: Some(Path::new("/etc/openshell/tls/ca.pem")), + otlp_config: Some(&otlp), + network_trust: Some(&trust), + shutdown: tokio::sync::watch::channel(false).1, + settings: &settings, + driver_config: operator_table, }, - ..Default::default() - } - .validate_proxy_config() - .expect("a lone proxy URL is a complete configuration"); - } - - #[test] - fn vm_driver_command_includes_configured_sandbox_identity() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - let config = VmComputeConfig { - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }; - - validate_vm_sandbox_identity(&config).expect("valid identity"); - append_vm_identity_args(&mut command, &config); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!(args, ["--sandbox-uid", "2000", "--sandbox-gid", "3000"]); - } - - #[test] - fn vm_gateway_toml_forwards_rootfs_tar_settings() { - let config: VmComputeConfig = toml::from_str( - r#" - grpc_endpoint = "http://127.0.0.1:50051" - rootfs_tar_staging_dir = "/var/lib/openshell/rootfs-tar-staging" - rootfs_tar_max_bytes = 1073741824 - "#, + Path::new("/var/lib/openshell/vm/run/compute-driver.sock"), ) - .expect("schema-v2 VM rootfs tar settings must deserialize"); - config - .validate_configuration() - .expect("rootfs tar settings must pass static validation"); - - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_rootfs_tar_args(&mut command, &config); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - - assert_eq!( - args, - [ - "--rootfs-tar-staging-dir", - "/var/lib/openshell/rootfs-tar-staging", - "--rootfs-tar-max-bytes", - "1073741824", - ] - ); - } + .unwrap(); - #[test] - fn vm_gateway_rejects_zero_rootfs_tar_limit() { - let config = VmComputeConfig { - grpc_endpoint: "http://127.0.0.1:50051".to_string(), - rootfs_tar_max_bytes: Some(0), - ..Default::default() - }; + document.gateway.expected_peer_pid = 4242; + let tls = document.gateway.telemetry.collector.as_mut().unwrap(); + tls.ca_file = Some("/etc/openshell/otlp/ca.pem".into()); + tls.cert_file = Some("/etc/openshell/otlp/cert.pem".into()); + tls.key_file = Some("/etc/openshell/otlp/key.pem".into()); - let error = config - .validate_configuration() - .expect_err("a zero rootfs tar limit must fail before driver startup"); - assert!(error.to_string().contains("rootfs_tar_max_bytes")); + let fixture = openshell_driver_sdk::StartupDocument::parse(VM_STARTUP_FIXTURE).unwrap(); + assert_eq!(document, fixture); } #[test] - fn vm_driver_command_forwards_proxy_and_spiffe_configuration_without_credentials() { - let config = VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("https://proxy.internal:8443".to_string()), - no_proxy: Some("localhost,.svc".to_string()), - proxy_auth_file: Some(PathBuf::from("/gateway/secrets/proxy-auth")), - proxy_auth_allow_insecure: Some(true), - proxy_connect_by_hostname: Some(true), - }, - provider_spiffe_workload_api_tcp_endpoint: Some("tcp:192.0.2.10:8081".to_string()), - provider_spiffe_allow_guest_tcp: true, - ..Default::default() - }; - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args(&mut command, &config); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--upstream-proxy", - "https://proxy.internal:8443", - "--upstream-no-proxy", - "localhost,.svc", - "--upstream-proxy-auth-file", - "/gateway/secrets/proxy-auth", - "--upstream-proxy-auth-allow-insecure", - "--upstream-proxy-connect-by-hostname", - "--provider-spiffe-workload-api-tcp-endpoint", - "tcp:192.0.2.10:8081", - "--provider-spiffe-allow-guest-tcp", - ] - ); - assert!(!args.iter().any(|arg| arg.contains("user:password"))); + fn only_the_launcher_owned_key_is_removed_from_the_operator_table() { + let mut table = fixture_driver_config(); + let before = table.clone(); + table.insert("driver_dir".into(), "/opt/drivers".into()); + assert_eq!(vm_driver_config_table(table), before); } #[test] - fn vm_gateway_config_rejects_root_identity() { - let config = VmComputeConfig { - sandbox_uid: Some(0), - ..Default::default() - }; - let error = validate_vm_sandbox_identity(&config).expect_err("root UID must fail"); - assert!(error.to_string().contains("sandbox_uid 0")); - } - - #[test] - fn resolve_driver_bin_uses_driver_dir_when_binary_present() { - let dir = tempdir().unwrap(); - let bin = dir.path().join("openshell-driver-vm"); - std::fs::write(&bin, "#!/bin/sh\n").unwrap(); - std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); - - let vm_config = VmComputeConfig { - driver_dir: Some(dir.path().to_path_buf()), - ..Default::default() - }; - assert_eq!(resolve_compute_driver_bin(&vm_config).unwrap(), bin); - } - - #[test] - fn resolve_driver_bin_error_mentions_driver_dir_hint() { - let dir = tempdir().unwrap(); // empty — no driver binary present - - let vm_config = VmComputeConfig { - driver_dir: Some(dir.path().to_path_buf()), - ..Default::default() - }; - let err = resolve_compute_driver_bin(&vm_config) - .unwrap_err() - .to_string(); - assert!(err.contains("[openshell.drivers.vm].driver_dir")); - assert!(err.contains("openshell-driver-vm")); - } - - #[test] - fn resolve_driver_search_dirs_include_libexec_fallbacks() { - let dirs = resolve_driver_search_dirs(&VmComputeConfig { - driver_dir: None, - ..Default::default() - }); - - assert!(dirs.contains(&PathBuf::from("/usr/libexec/openshell"))); - assert!(dirs.contains(&PathBuf::from("/usr/local/libexec/openshell"))); - assert!(dirs.contains(&PathBuf::from("/usr/local/libexec"))); - } - - #[test] - fn vm_compute_driver_tls_requires_explicit_guest_bundle() { - let vm_config = VmComputeConfig { - grpc_endpoint: "https://gateway.internal:8443".to_string(), - ..Default::default() - }; - - let err = compute_driver_guest_tls_paths(&vm_config) - .expect_err("https vm endpoints should require an explicit gateway CA"); - assert!(err.to_string().contains("guest_tls_ca")); - } - - #[test] - fn vm_compute_driver_tls_uses_only_gateway_ca() { - let dir = tempdir().unwrap(); - let guest_ca = dir.path().join("guest-ca.crt"); - std::fs::write(&guest_ca, guest_ca.display().to_string()).unwrap(); - - let vm_config = VmComputeConfig { - grpc_endpoint: "https://gateway.internal:8443".to_string(), - guest_tls_ca: Some(guest_ca.clone()), - ..Default::default() - }; - - let guest_paths = compute_driver_guest_tls_paths(&vm_config) - .unwrap() - .expect("https vm endpoints should pass an explicit gateway CA"); - assert_eq!(guest_paths.ca, guest_ca); - } - - #[test] - fn compute_driver_socket_path_uses_private_run_dir() { - let state_dir = PathBuf::from("/tmp/openshell-vm-state"); - let vm_config = VmComputeConfig { - state_dir: state_dir.clone(), - ..Default::default() - }; + fn launch_settings_default_the_state_dir_and_read_the_driver_dir() { + let settings = VmLaunchSettings::from_table(&toml::Table::new()).unwrap(); + assert_eq!(settings.state_dir(), VmLaunchSettings::default_state_dir()); + assert!(settings.driver_dir.is_none()); + let table: toml::Table = + toml::from_str("driver_dir = '/opt/drivers'\nstate_dir = '/var/lib/vm'\nvcpus = 4\n") + .unwrap(); + let settings = VmLaunchSettings::from_table(&table).unwrap(); assert_eq!( - compute_driver_socket_path(&vm_config), - state_dir.join("run").join("compute-driver.sock") + settings.driver_dir.as_deref(), + Some(Path::new("/opt/drivers")) ); - } - - #[test] - fn prepare_compute_driver_socket_path_creates_private_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(vm_config.state_dir.join("run")) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_restricts_existing_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let run_dir = vm_config.state_dir.join("run"); - std::fs::create_dir_all(&run_dir).unwrap(); - std::fs::set_permissions(&run_dir, std::fs::Permissions::from_mode(0o777)).unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(run_dir).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_restricts_existing_state_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - std::fs::create_dir_all(&vm_config.state_dir).unwrap(); - std::fs::set_permissions(&vm_config.state_dir, std::fs::Permissions::from_mode(0o777)) - .unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(vm_config.state_dir) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_state_dir() { - let dir = tempdir().unwrap(); - let target = dir.path().join("target"); - let state_link = dir.path().join("state-link"); - std::fs::create_dir_all(&target).unwrap(); - std::os::unix::fs::symlink(&target, &state_link).unwrap(); - let vm_config = VmComputeConfig { - state_dir: state_link, - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked state dir should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let target = dir.path().join("run-target"); - std::fs::create_dir_all(&vm_config.state_dir).unwrap(); - std::fs::create_dir_all(&target).unwrap(); - std::os::unix::fs::symlink(&target, vm_config.state_dir.join("run")).unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked run dir should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_vm_state_dir_rejects_wrong_owner() { - let dir = tempdir().unwrap(); - let state_dir = dir.path().join("state"); - std::fs::create_dir_all(&state_dir).unwrap(); - let wrong_uid = if current_euid() == u32::MAX { - u32::MAX - 1 - } else { - current_euid() + 1 - }; - - let err = prepare_vm_state_dir(&state_dir, wrong_uid) - .expect_err("wrong owner should be rejected") - .to_string(); - assert!(err.contains("is owned by uid")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_socket() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink("/tmp/not-a-socket", &socket_path).unwrap(); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked socket should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_non_socket_stale_path() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - std::fs::write(&socket_path, "not a socket").unwrap(); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("regular file should be rejected") - .to_string(); - assert!(err.contains("is not a Unix socket")); - } - - #[test] - fn prepare_compute_driver_socket_path_removes_same_owner_stale_socket() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - let listener = StdUnixListener::bind(&socket_path).unwrap(); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - drop(listener); - assert!(!socket_path.exists()); + assert_eq!(settings.state_dir(), PathBuf::from("/var/lib/vm")); } } diff --git a/crates/openshell-gateway/tests/config_preflight.rs b/crates/openshell-gateway/tests/config_preflight.rs index 9b14a584bb..81f8e79fdc 100644 --- a/crates/openshell-gateway/tests/config_preflight.rs +++ b/crates/openshell-gateway/tests/config_preflight.rs @@ -21,6 +21,14 @@ impl Fixture { let tools = root.path().join("tools"); fs::create_dir(&tools).expect("tools directory"); let config = root.path().join("gateway.toml"); + // The driver validates its own configuration. These tests are about + // the host tools, so a stand-in driver accepts any document. + let drivers = root.path().join("drivers"); + fs::create_dir(&drivers).expect("drivers directory"); + let driver = drivers.join("openshell-driver-vm"); + fs::write(&driver, "#!/bin/sh\necho '{\"ok\":true}'\n").expect("driver fixture"); + fs::set_permissions(&driver, fs::Permissions::from_mode(0o755)).expect("driver mode"); + fs::set_permissions(&drivers, fs::Permissions::from_mode(0o755)).expect("drivers mode"); let fixture = Self { root, tools, @@ -41,8 +49,10 @@ impl Fixture { // TOML serialization preserves quotes and escapes in the fixture path. let state_dir = toml::Value::try_from(self.root.path().join("vm-state")) .expect("serialize VM state directory"); + let driver_dir = toml::Value::try_from(self.root.path().join("drivers")) + .expect("serialize driver directory"); fs::write(&self.config, format!( - "[openshell]\nversion = 2\n[openshell.gateway]\ndisable_tls = true\n{selector}[openshell.drivers.vm]\nbootstrap_image = 'unreachable.invalid/vm:must-not-pull'\nstate_dir = {state_dir}\n" + "[openshell]\nversion = 2\n[openshell.gateway]\ndisable_tls = true\n{selector}[openshell.drivers.vm]\nbootstrap_image = 'unreachable.invalid/vm:must-not-pull'\nstate_dir = {state_dir}\ndriver_dir = {driver_dir}\n" )).expect("gateway configuration"); } @@ -217,7 +227,9 @@ async fn signals_stop_probe_wrapper_and_descendants_before_cli_exit() { .expect("preflight process"); let pid = Pid::from_raw(i32::try_from(child.id().expect("gateway PID")).expect("valid PID")); - tokio::time::timeout(Duration::from_secs(5), async { + // Startup of a debug gateway under parallel tests is slow; only the + // cleanup after the signal is time-sensitive. + tokio::time::timeout(Duration::from_secs(30), async { while !ready.exists() { tokio::time::sleep(Duration::from_millis(10)).await; } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 32641d0937..61e6612273 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -560,6 +560,17 @@ const ORPHAN_GRACE_PERIOD: Duration = Duration::from_mins(5); // Re-export the shared error type under the name used by this module. pub use openshell_core::ComputeDriverError as ComputeError; +/// State of a gateway-managed driver process. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DriverProcessState { + Running, + /// The process ended without the gateway asking it to. Carries the exit + /// status. + Exited(String), + /// The gateway took the process to shut it down. + Released, +} + #[derive(Debug)] pub struct ManagedDriverProcess { child: std::sync::Mutex>, @@ -575,6 +586,22 @@ impl ManagedDriverProcess { } } + /// Report whether the driver process is still running, without waiting. + #[cfg(unix)] + pub fn poll_exit(&self) -> DriverProcessState { + let Ok(mut guard) = self.child.lock() else { + return DriverProcessState::Released; + }; + let Some(child) = guard.as_mut() else { + return DriverProcessState::Released; + }; + match child.try_wait() { + Ok(None) => DriverProcessState::Running, + Ok(Some(status)) => DriverProcessState::Exited(status.to_string()), + Err(error) => DriverProcessState::Exited(format!("status unavailable: {error}")), + } + } + #[cfg(unix)] async fn shutdown(&self) -> Result<(), String> { use nix::errno::Errno; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 799c46e397..7d854f11cf 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -1800,8 +1800,8 @@ async fn terminate_signal() { } pub use compute::{ - AcquiredRemoteDriverEndpoint, DriverWatchStream, ManagedDriverProcess, SharedComputeDriver, - SharedComputeDriverAppEndpoints, SharedComputeDriverConfigurationUpdates, + AcquiredRemoteDriverEndpoint, DriverProcessState, DriverWatchStream, ManagedDriverProcess, + SharedComputeDriver, SharedComputeDriverAppEndpoints, SharedComputeDriverConfigurationUpdates, }; /// Driver instance returned by a compiled compute-driver factory. diff --git a/docs/extensibility/drivers.mdx b/docs/extensibility/drivers.mdx index 366be0af30..7dcde8bb59 100644 --- a/docs/extensibility/drivers.mdx +++ b/docs/extensibility/drivers.mdx @@ -19,6 +19,10 @@ external compute driver communicates with the gateway over a Unix domain socket and negotiates its protocol version and capabilities before serving requests. +The gateway launches the VM and Podman drivers as separate processes. Refer to +[Launched Compute Drivers](/how-it-works/gateways/configuration#launched-compute-drivers) +for how it finds, starts, and validates them. + For built-in driver configuration and behavior, refer to [Runtimes](/how-it-works/sandboxes/runtimes). For implementation details, refer to each driver crate: diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 57c4da5c0b..e7ba6c71ab 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -961,7 +961,7 @@ Each enabled signal needs an endpoint, either in its own table or from `endpoint `protocol` selects the transport to a collector: `grpc`, the default, or `http/protobuf`. With `http/protobuf`, the endpoint is a base URL and each signal is posted to its path under it, `/v1/traces`, `/v1/logs`, or `/v1/metrics`, as with `OTEL_EXPORTER_OTLP_ENDPOINT`. HTTP/JSON is not supported. Point a `grpc` endpoint at a collector's gRPC receiver, conventionally port `4317`, and an `http/protobuf` endpoint at its HTTP receiver, conventionally port `4318`. A URI alone cannot distinguish the two, so a mismatched endpoint is accepted at startup and then fails on export. Sandbox supervisors and standalone compute drivers must come from the same release as the gateway to use `http/protobuf`: an older supervisor exports over gRPC, and an older driver rejects the protocol setting. -`headers` sets request headers sent with every export to a collector, as gRPC metadata or HTTP headers, such as an authorization token or a backend's routing header. Each name must be a valid HTTP header name set once, ignoring case; names the exporters set themselves, such as `content-type`, `host`, and `grpc-*`, and binary gRPC names ending in `-bin` are rejected. Each value must be non-empty printable ASCII; spaces are allowed. The gateway's exporters also read their signal's `OTEL_EXPORTER_OTLP_TRACES_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS`, or `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, or else `OTEL_EXPORTER_OTLP_HEADERS`, and a header set there replaces a configured header of the same name. In-process compute drivers and the VM driver send the gateway's trace headers, including those from the environment, with their own spans. A standalone compute driver sends only the headers in its own `OTEL_EXPORTER_OTLP_*HEADERS` variables. Supervisors send their trace collector's `headers` with their own spans, and the gateway's OCSF headers, including those from the environment, with their OCSF records. Trace headers from the gateway's environment do not reach supervisors, so set `headers` or `headers_file` on the trace collector when supervisor spans need them. The agent trace relay sends only its collector's `headers`, never ones from the environment, so its credentials can only be set with `headers` or `headers_file`. A changed header takes effect when the gateway restarts, and reaches a running sandbox only after that sandbox restarts. +`headers` sets request headers sent with every export to a collector, as gRPC metadata or HTTP headers, such as an authorization token or a backend's routing header. Each name must be a valid HTTP header name set once, ignoring case; names the exporters set themselves, such as `content-type`, `host`, and `grpc-*`, and binary gRPC names ending in `-bin` are rejected. Each value must be non-empty printable ASCII; spaces are allowed. The gateway's exporters also read their signal's `OTEL_EXPORTER_OTLP_TRACES_HEADERS`, `OTEL_EXPORTER_OTLP_LOGS_HEADERS`, or `OTEL_EXPORTER_OTLP_METRICS_HEADERS`, or else `OTEL_EXPORTER_OTLP_HEADERS`, and a header set there replaces a configured header of the same name. In-process compute drivers and launched compute drivers (VM and Podman) send the gateway's trace headers, including those from the environment, with their own spans. A standalone compute driver sends only the headers in its own `OTEL_EXPORTER_OTLP_*HEADERS` variables. Supervisors send their trace collector's `headers` with their own spans, and the gateway's OCSF headers, including those from the environment, with their OCSF records. Trace headers from the gateway's environment do not reach supervisors, so set `headers` or `headers_file` on the trace collector when supervisor spans need them. The agent trace relay sends only its collector's `headers`, never ones from the environment, so its credentials can only be set with `headers` or `headers_file`. A changed header takes effect when the gateway restarts, and reaches a running sandbox only after that sandbox restarts. Put credentials in `headers_file` rather than `headers`. It reads a collector's headers from a file instead, such as a mounted Kubernetes Secret, so credentials stay out of the configuration file. The file holds one `name=value` header per line. Blank lines are skipped, and whitespace around each name and value is trimmed. The headers are validated like `headers`, the file must be UTF-8 and at most 64 KiB, and setting both `headers` and `headers_file` in one table is a configuration error. A relative path uses the gateway's working directory. The gateway reads the file at startup and fails to start if it is missing or invalid, so a changed file takes effect as a changed header does. @@ -1066,7 +1066,7 @@ gateway under the worktree-specific k3d cluster name; select it with tasks export spans and OCSF log records to the forwarded receiver automatically. -In-process compute drivers read their backend-specific settings from `[openshell.drivers.]`. An external driver's gateway table supplies only its `socket_path`; configure the external driver process itself through that binary's flags or environment variables. A driver that advertises `supports_sandbox_authentication` may authenticate an opaque bootstrap credential through the compute-driver protocol. It must return the same non-empty runtime identity from sandbox creation and credential authentication. Start requests include the previously recorded opaque identity so the driver can preserve the stable resource while rotating generation-specific compute. For `IssueSandboxToken`, the gateway verifies the sandbox exists and the driver/runtime identity matches the durable provisioning record before returning a generation-bound session JWT. The in-process Kubernetes driver reads `service_account_name`, `workspace_mode`, and namespace discovery from `[openshell.drivers.kubernetes]`; an external Kubernetes driver receives the equivalent values through its own CLI or environment contract. +Built-in compute drivers read their backend-specific settings from `[openshell.drivers.]`. The gateway passes the table of a launched driver (VM or Podman) through unchanged, and the driver validates it. An external driver's gateway table supplies only its `socket_path`; configure the external driver process itself through that binary's flags or environment variables. A driver that advertises `supports_sandbox_authentication` may authenticate an opaque bootstrap credential through the compute-driver protocol. It must return the same non-empty runtime identity from sandbox creation and credential authentication. Start requests include the previously recorded opaque identity so the driver can preserve the stable resource while rotating generation-specific compute. For `IssueSandboxToken`, the gateway verifies the sandbox exists and the driver/runtime identity matches the durable provisioning record before returning a generation-bound session JWT. The in-process Kubernetes driver reads `service_account_name`, `workspace_mode`, and namespace discovery from `[openshell.drivers.kubernetes]`; an external Kubernetes driver receives the equivalent values through its own CLI or environment contract. ### OTLP Metrics @@ -1405,6 +1405,26 @@ The gateway refuses to start when a peer endpoint is configured on a multi-repli ## Driver References +### Launched Compute Drivers + +The VM and Podman drivers run as separate binaries that the gateway launches: `openshell-driver-vm` and `openshell-driver-podman`. Docker and Kubernetes still run inside the gateway process. + +When `driver_dir` is set in `[openshell.drivers.vm]`, the gateway searches only that directory for the VM driver, then the directory that holds the gateway binary. Otherwise it searches these locations in order: + +1. `libexec` and `libexec/openshell` under the gateway's install prefix. +2. `~/.local/libexec/openshell`, `/usr/libexec/openshell`, `/usr/local/libexec/openshell`, and `/usr/local/libexec`. +3. The directory that holds the gateway binary. + +The Podman driver has no `driver_dir` setting. + +The gateway refuses a driver binary, or the directory that holds it, that is not owned by the gateway's user or root, or that is writable by its group or by other users. It fails with an error naming the driver when no binary is found. + +The gateway writes a startup document to a private `run/` directory under the driver's state directory and starts the driver with `--config `. The document holds the gateway's resolved values, such as its name, port, TLS CA, telemetry settings, and the staged network trust artifact. It also holds the driver's `[openshell.drivers.]` table, which the gateway does not interpret. The gateway removes the file once the driver is ready or has failed. OTLP headers stay in the driver's environment and never enter the document. + +The driver validates its own table at startup and exits when it is invalid. The gateway then reports that the driver exited before it was ready. If a driver exits after it was ready, the gateway logs an error naming the driver and exits with a nonzero status so a service manager can restart it. A driver that ends during a gateway shutdown is not reported. + +Podman auto-detection runs `openshell-driver-podman probe` with a five-second limit. A missing, untrusted, failing, slow, or malformed probe counts as Podman not being available. `openshell-gateway config preflight` runs the driver's `preflight` command for the selected driver, and for each auto-detectable driver that has a table in the configuration, so the binary must be installed on the host where you run it. Each driver gets ten seconds. Preflight does not see the gateway's TLS CA or the network trust bundle, because the gateway has not created them yet. + ### External Resource Admission Every compute driver disables caller-supplied `template.driver_config` by @@ -2112,7 +2132,7 @@ gateway_id = "openshell" [openshell.drivers.vm] state_dir = "/var/lib/openshell/vm" -# Where the gateway looks for the openshell-driver-vm subprocess binary. +# Where the gateway looks for the openshell-driver-vm binary it launches. driver_dir = "/usr/local/libexec/openshell" default_image = "nvcr.io/nvidia/base/ubuntu:24.04" # Optional override. When omitted, the gateway derives @@ -2191,6 +2211,8 @@ openshell-gateway generate-certs --output-dir "$OPENSHELL_LOCAL_TLS_DIR" The command also installs local CLI mTLS credentials. For explicit signing configuration, set the example's signing paths to `jwt/signing.pem`, `jwt/public.pem`, and `jwt/kid` under that directory. The gateway loads those paths in preference to local discovery. +Configure the guest TLS CA only under `[openshell.gateway]`. The VM driver rejects a `guest_tls_ca` key in `[openshell.drivers.vm]`. + Rootfs tar staging requires the gateway and the VM driver to share a filesystem and run as the same user. That holds for the managed VM driver, which the gateway starts as a subprocess. If you point `compute_driver_endpoints` at an diff --git a/install.sh b/install.sh index abbb624698..d013d3a334 100755 --- a/install.sh +++ b/install.sh @@ -22,6 +22,7 @@ HOMEBREW_FORMULA_NAME="openshell" HOMEBREW_CLI_ASSET="openshell-aarch64-apple-darwin.tar.gz" HOMEBREW_GATEWAY_ASSET="openshell-gateway-aarch64-apple-darwin.tar.gz" HOMEBREW_DRIVER_VM_ASSET="openshell-driver-vm-aarch64-apple-darwin.tar.gz" +HOMEBREW_DRIVER_PODMAN_ASSET="openshell-driver-podman-aarch64-apple-darwin.tar.gz" HOMEBREW_PROVER_ASSET="openshell-prover-aarch64-apple-darwin.tar.gz" BREAKING_RELEASE_VERSION="0.0.37" LINUX_PACKAGE_GLIBC_MIN_VERSION="2.28" @@ -912,7 +913,7 @@ patch_prerelease_homebrew_formula_urls() { _formula_file="$1" [ -n "$RELEASE_ASSET_DIR" ] || return 0 - for _asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do + for _asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_PROVER_ASSET"; do if [ ! -f "${RELEASE_ASSET_DIR}/${_asset}" ]; then error "prerelease artifact is missing the required macOS asset: ${_asset}" fi @@ -925,6 +926,7 @@ patch_prerelease_homebrew_formula_urls() { -e "s#${_release_asset_url}/${HOMEBREW_CLI_ASSET}#${_local_asset_url}/${HOMEBREW_CLI_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_GATEWAY_ASSET}#${_local_asset_url}/${HOMEBREW_GATEWAY_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_DRIVER_VM_ASSET}#${_local_asset_url}/${HOMEBREW_DRIVER_VM_ASSET}#g" \ + -e "s#${_release_asset_url}/${HOMEBREW_DRIVER_PODMAN_ASSET}#${_local_asset_url}/${HOMEBREW_DRIVER_PODMAN_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_PROVER_ASSET}#${_local_asset_url}/${HOMEBREW_PROVER_ASSET}#g" \ "$_formula_file" >"$_patched_file" mv "$_patched_file" "$_formula_file" diff --git a/nix/test-guest/README.md b/nix/test-guest/README.md index 982a882e39..cb551f340d 100644 --- a/nix/test-guest/README.md +++ b/nix/test-guest/README.md @@ -263,6 +263,7 @@ Package existing ARM64 Linux binaries with the repository's `package:deb:arm64` OPENSHELL_CLI_BINARY="$PWD/target/aarch64-unknown-linux-musl/release/openshell" \ OPENSHELL_GATEWAY_BINARY="$PWD/target/aarch64-unknown-linux-gnu/release/openshell-gateway" \ OPENSHELL_DRIVER_VM_BINARY="$PWD/target/aarch64-unknown-linux-gnu/release/openshell-driver-vm" \ +OPENSHELL_DRIVER_PODMAN_BINARY="$PWD/target/aarch64-unknown-linux-gnu/release/openshell-driver-podman" \ OPENSHELL_DEB_VERSION=0.0.0-local \ OPENSHELL_OUTPUT_DIR="$PWD/artifacts" \ nix develop --command mise run package:deb:arm64 diff --git a/openshell.spec b/openshell.spec index eaa60d96ee..35805de6ae 100644 --- a/openshell.spec +++ b/openshell.spec @@ -107,6 +107,7 @@ grep -q 'version = "%{openshell_cargo_version}"' Cargo.toml || (echo "ERROR: Car test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell" test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-gateway" test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-prover" +test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-driver-podman" # Generate vendored crate manifest and license metadata. # cargo-vendor.txt is consumed by an RPM generator (from cargo-rpm-macros) @@ -129,6 +130,11 @@ install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-prover" %{buildroo # --- Gateway binary --- install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-gateway" %{buildroot}%{_bindir}/%{name}-gateway +# --- Podman compute driver --- +# The gateway launches this binary from %{_libexecdir}/%{name} to run Podman +# sandboxes and to detect whether Podman is available. +install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-driver-podman" %{buildroot}%{_libexecdir}/%{name}/%{name}-driver-podman + # --- Default gateway TOML config template --- # Shipped as a read-only reference in %{_datadir}. The systemd unit seeds a # user-level copy at ~/.config/openshell/gateway.toml on first start. @@ -244,6 +250,9 @@ touch %{buildroot}%{python3_sitelib}/%{name}-%{openshell_python_version}.dist-in # Smoke-test the gateway binary %{buildroot}%{_bindir}/%{name}-gateway --version +# The Podman driver must run and report availability as JSON. +%{buildroot}%{_libexecdir}/%{name}/%{name}-driver-podman probe | grep -q '"available"' + # Smoke-test the Python SDK version metadata via importlib.metadata. # We query the dist-info directly rather than importing the package because # the full import pulls in grpcio and other runtime deps not present in the @@ -308,6 +317,7 @@ grep -q 'gateway.toml.default.v1' %{buildroot}%{_userunitdir}/%{name}-gateway.se %doc %{_docdir}/%{name}-gateway/CONFIGURATION.md %doc %{_docdir}/%{name}-gateway/TROUBLESHOOTING.md %{_bindir}/%{name}-gateway +%{_libexecdir}/%{name}/%{name}-driver-podman %{_userunitdir}/%{name}-gateway.service %{_libexecdir}/%{name}-gateway-migrate-config %{_datadir}/%{name}-gateway/gateway.toml.default diff --git a/tasks/scripts/gateway-podman.sh b/tasks/scripts/gateway-podman.sh index bb837e464a..fe481b6fab 100644 --- a/tasks/scripts/gateway-podman.sh +++ b/tasks/scripts/gateway-podman.sh @@ -161,9 +161,11 @@ ensure_podman_runtime_image \ "sandbox runtime" export OPENSHELL_SUPERVISOR_IMAGE="${SUPERVISOR_IMAGE}" -echo "Building openshell-gateway..." +echo "Building openshell-gateway and the Podman compute driver..." require_mise mise run build:gateway +# The gateway launches the driver binary found beside it. +cargo build -p openshell-driver-podman if [[ ! -x "${GATEWAY_BIN}" ]]; then echo "ERROR: expected gateway binary at ${GATEWAY_BIN}" >&2 diff --git a/tasks/scripts/package-deb-install.sh b/tasks/scripts/package-deb-install.sh index bd95a13e49..b5afbc4e40 100755 --- a/tasks/scripts/package-deb-install.sh +++ b/tasks/scripts/package-deb-install.sh @@ -7,7 +7,7 @@ # or on the gateway-as-a-service flow. # # Steps: -# 1. cargo build --release the four binaries that go into the deb. +# 1. cargo build --release the five binaries that go into the deb. # 2. Run tasks/scripts/package-deb.sh against those binaries. # 3. sudo dpkg -i the resulting artifact. # 4. Start the packaged user gateway service and register it locally. @@ -58,13 +58,15 @@ cargo build --release \ -p openshell-cli \ -p openshell-gateway \ -p openshell-prover-cli \ - -p openshell-driver-vm + -p openshell-driver-vm \ + -p openshell-driver-podman echo "==> Building Debian package" OPENSHELL_CLI_BINARY="${repo_root}/target/release/openshell" \ OPENSHELL_GATEWAY_BINARY="${repo_root}/target/release/openshell-gateway" \ OPENSHELL_PROVER_BINARY="${repo_root}/target/release/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${repo_root}/target/release/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="${repo_root}/target/release/openshell-driver-podman" \ OPENSHELL_DEB_VERSION="$VERSION" \ OPENSHELL_DEB_ARCH="$ARCH" \ OPENSHELL_OUTPUT_DIR="$OUTPUT_DIR" \ diff --git a/tasks/scripts/package-deb.sh b/tasks/scripts/package-deb.sh index c2492dd242..0f894915c6 100755 --- a/tasks/scripts/package-deb.sh +++ b/tasks/scripts/package-deb.sh @@ -23,6 +23,7 @@ Required environment: OPENSHELL_GATEWAY_BINARY Path to openshell-gateway OPENSHELL_PROVER_BINARY Path to openshell-prover OPENSHELL_DRIVER_VM_BINARY Path to openshell-driver-vm + OPENSHELL_DRIVER_PODMAN_BINARY Path to openshell-driver-podman OPENSHELL_DEB_VERSION Debian package version Optional environment: @@ -72,6 +73,7 @@ require_env OPENSHELL_CLI_BINARY require_env OPENSHELL_GATEWAY_BINARY require_env OPENSHELL_PROVER_BINARY require_env OPENSHELL_DRIVER_VM_BINARY +require_env OPENSHELL_DRIVER_PODMAN_BINARY require_env OPENSHELL_DEB_VERSION OPENSHELL_DEB_ARCH="${OPENSHELL_DEB_ARCH:-$(infer_deb_arch)}" @@ -114,6 +116,7 @@ stage_binary "$OPENSHELL_CLI_BINARY" "$pkgroot/usr/bin/openshell" stage_binary "$OPENSHELL_GATEWAY_BINARY" "$pkgroot/usr/bin/openshell-gateway" stage_binary "$OPENSHELL_PROVER_BINARY" "$pkgroot/usr/bin/openshell-prover" stage_binary "$OPENSHELL_DRIVER_VM_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-vm" +stage_binary "$OPENSHELL_DRIVER_PODMAN_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-podman" # Per-user systemd unit. Each user enables it via `systemctl --user`. install -D -m 0644 "$src_dir/openshell-gateway.service" \ diff --git a/tasks/scripts/release.py b/tasks/scripts/release.py index c62ec0b67a..6d6e50b59c 100644 --- a/tasks/scripts/release.py +++ b/tasks/scripts/release.py @@ -37,6 +37,7 @@ class Versions: HOMEBREW_CLI_ASSET = f"openshell-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_GATEWAY_ASSET = f"openshell-gateway-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_DRIVER_VM_ASSET = f"openshell-driver-vm-{HOMEBREW_TARGET}.tar.gz" +HOMEBREW_DRIVER_PODMAN_ASSET = f"openshell-driver-podman-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_PROVER_ASSET = f"openshell-prover-{HOMEBREW_TARGET}.tar.gz" GITHUB_RELEASE_DOWNLOADS = "https://github.com/ai-openshell/openshell/releases/download" LOCAL_GATEWAY_PORT = 17670 @@ -311,6 +312,7 @@ def render_homebrew_formula( cli_sha256: str, gateway_sha256: str, driver_vm_sha256: str, + driver_podman_sha256: str, prover_sha256: str, ) -> str: if not _RELEASE_TAG_RE.fullmatch(release_tag): @@ -343,6 +345,11 @@ class Openshell < Formula sha256 "{driver_vm_sha256}" end + resource "openshell-driver-podman" do + url "{_asset_url(release_tag, HOMEBREW_DRIVER_PODMAN_ASSET)}" + sha256 "{driver_podman_sha256}" + end + resource "openshell-prover" do url "{_asset_url(release_tag, HOMEBREW_PROVER_ASSET)}" sha256 "{prover_sha256}" @@ -361,6 +368,10 @@ def install libexec.install "openshell-driver-vm" end + resource("openshell-driver-podman").stage do + libexec.install "openshell-driver-podman" + end + resource("openshell-prover").stage do bin.install "openshell-prover" end @@ -518,6 +529,11 @@ def generate_homebrew_formula( HOMEBREW_DRIVER_VM_ASSET, checksums_path, ), + driver_podman_sha256=_required_checksum( + checksums, + HOMEBREW_DRIVER_PODMAN_ASSET, + checksums_path, + ), prover_sha256=_required_checksum( prover_checksums, HOMEBREW_PROVER_ASSET, diff --git a/tasks/scripts/release_formula_test.py b/tasks/scripts/release_formula_test.py index 789c59b727..12ae7b472f 100644 --- a/tasks/scripts/release_formula_test.py +++ b/tasks/scripts/release_formula_test.py @@ -19,6 +19,7 @@ def test_generate_homebrew_formula_uses_channel_urls_and_exact_version( [ "a" * 64 + " openshell-aarch64-apple-darwin.tar.gz", "b" * 64 + " openshell-driver-vm-aarch64-apple-darwin.tar.gz", + "c" * 64 + " openshell-driver-podman-aarch64-apple-darwin.tar.gz", ] ) + "\n", @@ -55,6 +56,13 @@ def test_generate_homebrew_formula_uses_channel_urls_and_exact_version( "https://github.com/ai-openshell/openshell/releases/download/" "v0.1.0-pre.3/openshell-driver-vm-aarch64-apple-darwin.tar.gz" ) in formula + assert ( + "https://github.com/NVIDIA/OpenShell/releases/download/" + "v0.1.0-pre.3/openshell-driver-podman-aarch64-apple-darwin.tar.gz" + ) in formula + assert 'sha256 "' + "c" * 64 + '"' in formula + assert 'resource("openshell-driver-podman").stage' in formula + assert 'libexec.install "openshell-driver-podman"' in formula assert 'version "0.1.0-pre.3"' in formula assert 'sha256 "' + "b" * 64 + '"' in formula assert ( diff --git a/tasks/scripts/test-install-sh.sh b/tasks/scripts/test-install-sh.sh index fe40564525..94c2c057a8 100755 --- a/tasks/scripts/test-install-sh.sh +++ b/tasks/scripts/test-install-sh.sh @@ -1040,7 +1040,7 @@ if [ "$(cat "$downloaded_checksum")" != "checksums" ]; then exit 1 fi -for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do +for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_PROVER_ASSET"; do : >"${RELEASE_ASSET_DIR}/${asset}" done prerelease_formula="${tmpdir}/openshell.rb" @@ -1048,10 +1048,11 @@ printf '%s\n' \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_CLI_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_GATEWAY_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_DRIVER_VM_ASSET}\"" \ + " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_DRIVER_PODMAN_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_PROVER_ASSET}\"" \ >"$prerelease_formula" patch_prerelease_homebrew_formula_urls "$prerelease_formula" -for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do +for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_PROVER_ASSET"; do if ! grep -Fq "file://${RELEASE_ASSET_DIR}/${asset}" "$prerelease_formula"; then echo "FAIL: prerelease formula did not use local asset ${asset}" >&2 exit 1 diff --git a/tasks/scripts/test-packaging-assets.sh b/tasks/scripts/test-packaging-assets.sh index 6ae81fe64b..4c224048ca 100755 --- a/tasks/scripts/test-packaging-assets.sh +++ b/tasks/scripts/test-packaging-assets.sh @@ -298,7 +298,7 @@ if command -v dpkg-deb >/dev/null 2>&1; then package_work=$(mktemp -d "${TMPDIR:-/tmp}/openshell-package-assets.XXXXXX") trap 'rm -rf "$package_work"' EXIT mkdir -p "$package_work/bin" "$package_work/output" - for binary in openshell openshell-gateway openshell-prover openshell-driver-vm; do + for binary in openshell openshell-gateway openshell-prover openshell-driver-vm openshell-driver-podman; do printf '#!/bin/sh\nexit 0\n' >"$package_work/bin/$binary" chmod +x "$package_work/bin/$binary" done @@ -306,6 +306,7 @@ if command -v dpkg-deb >/dev/null 2>&1; then OPENSHELL_GATEWAY_BINARY="$package_work/bin/openshell-gateway" \ OPENSHELL_PROVER_BINARY="$package_work/bin/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="$package_work/bin/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="$package_work/bin/openshell-driver-podman" \ OPENSHELL_DEB_VERSION=0.0.0 \ OPENSHELL_DEB_ARCH=amd64 \ OPENSHELL_OUTPUT_DIR="$package_work/output" \ @@ -322,6 +323,14 @@ if command -v dpkg-deb >/dev/null 2>&1; then echo "FAIL: package-deb did not stage openshell-prover" >&2 exit 1 fi + # The gateway launches the VM and Podman drivers from this directory. + for driver in openshell-driver-vm openshell-driver-podman; do + if ! dpkg-deb --fsys-tarfile "$package_work/output/openshell_0.0.0_amd64.deb" \ + | tar -tf - | grep -x "./usr/libexec/openshell/$driver" >/dev/null; then + echo "FAIL: package-deb did not stage $driver" >&2 + exit 1 + fi + done else echo "SKIP: dpkg-deb unavailable; Debian artifact staging requires its assigned lane" fi diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index 764889a1ee..52a7cfe43d 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -205,6 +205,7 @@ rec { cargo build --target ${gnuToolchain.target} \ -p openshell-gateway \ + -p openshell-driver-podman \ -p openshell-supervisor install -D -m 0755 \ @@ -219,6 +220,10 @@ rec { target/${gnuToolchain.target}/debug/openshell-gateway \ artifacts/binaries/${gnuToolchain.target}/openshell-gateway + install -D -m 0755 \ + target/${gnuToolchain.target}/debug/openshell-driver-podman \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman + install -D -m 0755 \ target/${gnuToolchain.target}/debug/openshell-supervisor \ artifacts/binaries/${gnuToolchain.target}/openshell-supervisor @@ -389,6 +394,7 @@ rec { OPENSHELL_GATEWAY_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-gateway" \ OPENSHELL_PROVER_BINARY="$root/artifacts/binaries/${muslToolchain.target}/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman" \ OPENSHELL_DEB_VERSION="$package_version" \ OPENSHELL_DEB_ARCH=${dockerArch} \ OPENSHELL_OUTPUT_DIR="$root/artifacts/packages" \ @@ -424,6 +430,7 @@ rec { for binary in \ artifacts/binaries/${muslToolchain.target}/openshell \ artifacts/binaries/${gnuToolchain.target}/openshell-gateway \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman \ artifacts/binaries/${muslToolchain.target}/openshell-prover; do if [[ ! -x "$binary" ]]; then echo "missing $binary; run build-artifacts-binaries first" >&2 @@ -442,6 +449,7 @@ rec { --volume "$root:/repo:ro" \ --volume "$root/artifacts/binaries/${muslToolchain.target}/openshell:/binaries/openshell:ro" \ --volume "$root/artifacts/binaries/${gnuToolchain.target}/openshell-gateway:/binaries/openshell-gateway:ro" \ + --volume "$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman:/binaries/openshell-driver-podman:ro" \ --volume "$root/artifacts/binaries/${muslToolchain.target}/openshell-prover:/binaries/openshell-prover:ro" \ --volume "$output_dir:/out" \ --volume openshell-rpm-cargo:/root/.cargo/registry \