From 6d6b84ef05a97ab2499d0d4e9a2cedcc9665643d Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:16:47 +0000 Subject: [PATCH 1/9] feat(otel): enable driver trace export after tracing is installed A launched driver logs before the gateway has sent its telemetry settings. install_deferred_driver_tracing installs console logging at start with an empty export slot, and DeferredDriverTracing::enable_export fills it once. The span filter stays outside the slot because a per-layer filter added by a reload is never registered with the subscriber. Signed-off-by: Evan Lezar --- crates/openshell-otel/src/driver.rs | 103 ++++++++++++++++++ crates/openshell-otel/src/lib.rs | 5 +- .../tests/deferred_driver_tracing.rs | 43 ++++++++ 3 files changed, 149 insertions(+), 2 deletions(-) create mode 100644 crates/openshell-otel/tests/deferred_driver_tracing.rs diff --git a/crates/openshell-otel/src/driver.rs b/crates/openshell-otel/src/driver.rs index 68be206834..501f88376d 100644 --- a/crates/openshell-otel/src/driver.rs +++ b/crates/openshell-otel/src/driver.rs @@ -267,6 +267,109 @@ pub fn install_driver_tracing( DriverTracingHandle { provider } } +type ExportLayer = + Box + Send + Sync + 'static>; + +/// Driver logging installed at process start, with OTLP export added once a +/// launching gateway sends its telemetry settings. +pub struct DeferredDriverTracing { + descriptor: ComputeDriverTracing, + export: tracing_subscriber::reload::Handle, tracing_subscriber::Registry>, + provider: std::sync::Mutex>, +} + +/// Install console logging now and leave OTLP export to +/// [`DeferredDriverTracing::enable_export`]. +#[must_use] +pub fn install_deferred_driver_tracing( + descriptor: ComputeDriverTracing, + log_level: &str, + ansi: bool, +) -> DeferredDriverTracing { + // The span filter sits outside the reloadable slot: a per-layer filter + // added by a reload would never be registered with the subscriber. + let (export, handle) = tracing_subscriber::reload::Layer::new(None::); + tracing_subscriber::registry() + .with( + export.with_filter(tracing_subscriber::filter::filter_fn(|metadata| { + metadata.is_span() && !metadata.target().starts_with("opentelemetry") + })), + ) + .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(log_level))) + .with(tracing_subscriber::fmt::layer().with_ansi(ansi)) + .init(); + DeferredDriverTracing { + descriptor, + export: handle, + provider: std::sync::Mutex::new(None), + } +} + +impl DeferredDriverTracing { + /// Start exporting to the collector in `config`, sending `headers`. Does + /// nothing without an endpoint or once export is running. Setup failures + /// are logged, as at standalone startup. + pub fn enable_export(&self, config: DriverTracingConfig<'_>, headers: http::HeaderMap) { + let mut running = self + .provider + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(endpoint) = config.endpoint else { + return; + }; + if running.is_some() { + return; + } + let (provider, error) = match config.transport() { + Ok(mut transport) => { + transport.headers = headers; + self.descriptor.provider_for( + Some(endpoint), + &transport, + config.service_version, + config.gateway_name, + Some(self.descriptor.compute_driver()), + ) + } + Err(error) => (None, Some(error.into())), + }; + if let Some(error) = error { + tracing::error!(%error, "OTLP exporting could not be started"); + return; + } + let Some(provider) = provider else { + return; + }; + let layer: ExportLayer = { + use opentelemetry::trace::TracerProvider as _; + Box::new( + tracing_opentelemetry::layer() + .with_tracer(provider.tracer(self.descriptor.service_name())), + ) + }; + if let Err(error) = self.export.reload(Some(layer)) { + tracing::error!(%error, "OTLP exporting could not be started"); + return; + } + tracing::info!(endpoint, "OTLP exporting enabled"); + *running = Some(provider); + } +} + +impl Drop for DeferredDriverTracing { + fn drop(&mut self) { + let provider = self + .provider + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(provider) = provider + && let Err(error) = provider.shutdown() + { + tracing::warn!(%error, "OTLP tracer provider shutdown failed"); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/openshell-otel/src/lib.rs b/crates/openshell-otel/src/lib.rs index b8c2f4d79b..c34f1637c4 100644 --- a/crates/openshell-otel/src/lib.rs +++ b/crates/openshell-otel/src/lib.rs @@ -54,8 +54,9 @@ pub use correlation::current_ocsf_trace_correlation; #[cfg(feature = "export")] pub use driver::{ - BoxGrpcStream, ComputeDriverTracing, DriverTracingConfig, DriverTracingHandle, - IN_PROCESS_COMPUTE_DRIVER_TARGET, InProcessRpcTracer, install_driver_tracing, + BoxGrpcStream, ComputeDriverTracing, DeferredDriverTracing, DriverTracingConfig, + DriverTracingHandle, IN_PROCESS_COMPUTE_DRIVER_TARGET, InProcessRpcTracer, + install_deferred_driver_tracing, install_driver_tracing, }; #[cfg(feature = "export")] pub use grpc::{ diff --git a/crates/openshell-otel/tests/deferred_driver_tracing.rs b/crates/openshell-otel/tests/deferred_driver_tracing.rs new file mode 100644 index 0000000000..b7878204f1 --- /dev/null +++ b/crates/openshell-otel/tests/deferred_driver_tracing.rs @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Installs process-wide tracing, so it runs in its own test binary. + +use openshell_otel::{DriverTracingConfig, Protocol}; +use openshell_otel_test_support::OtlpTestServer; + +#[tokio::test(flavor = "multi_thread")] +async fn export_enabled_after_install_reaches_the_collector_once() { + let tracing = openshell_otel::install_deferred_driver_tracing( + openshell_otel::compute_driver_tracing!(), + "info", + false, + ); + tracing::info_span!("driver.before_export").in_scope(|| {}); + + let collector = OtlpTestServer::start().await; + let config = DriverTracingConfig { + endpoint: Some(collector.endpoint()), + protocol: Protocol::Grpc, + ca_file: None, + cert_file: None, + key_file: None, + gateway_name: Some("test-gateway"), + service_version: "test", + log_level: "info", + ansi: false, + }; + tracing.enable_export(config, http::HeaderMap::new()); + tracing.enable_export(config, http::HeaderMap::new()); + tracing::info_span!("driver.after_export").in_scope(|| {}); + drop(tracing); + let received = collector.shutdown().await; + + let names: Vec<_> = received + .spans + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(names, ["driver.after_export"]); + assert_eq!(received.gateway_names, ["test-gateway"]); +} From f9a9758f9059f620f4918cf1fe90333c375be24e Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:17:54 +0000 Subject: [PATCH 2/9] feat(drivers): add the driver launch protocol A gateway-launched driver starts with only its socket, the gateway's PID and the log level, and serves the DriverLaunch service from proto/driver_launch.proto at once. GetLaunchInfo reports the driver's name, version and protocol version; Configure carries the gateway context, the staged network trust artifact, typed image overrides, telemetry and the operator's driver table as opaque TOML. openshell-driver-launch provides the generated types, a Configure service that applies the request at most once and allows a retry after a failure, and a ComputeDriver wrapper that returns UNAVAILABLE until then. Signed-off-by: Evan Lezar --- Cargo.lock | 14 + crates/openshell-driver-launch/Cargo.toml | 30 ++ crates/openshell-driver-launch/build.rs | 18 + crates/openshell-driver-launch/src/lib.rs | 334 +++++++++++++++++++ crates/openshell-server/src/storage_proto.rs | 18 +- proto/driver_launch.proto | 91 +++++ 6 files changed, 504 insertions(+), 1 deletion(-) create mode 100644 crates/openshell-driver-launch/Cargo.toml create mode 100644 crates/openshell-driver-launch/build.rs create mode 100644 crates/openshell-driver-launch/src/lib.rs create mode 100644 proto/driver_launch.proto diff --git a/Cargo.lock b/Cargo.lock index 9260c5bc89..67026195ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4718,6 +4718,20 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "openshell-driver-launch" +version = "0.0.0" +dependencies = [ + "http 1.4.0", + "prost", + "protoc-bin-vendored", + "tokio", + "tonic", + "tonic-prost", + "tonic-prost-build", + "tower", +] + [[package]] name = "openshell-driver-mxc" version = "0.0.0" diff --git a/crates/openshell-driver-launch/Cargo.toml b/crates/openshell-driver-launch/Cargo.toml new file mode 100644 index 0000000000..afdc8177ce --- /dev/null +++ b/crates/openshell-driver-launch/Cargo.toml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-launch" +description = "Launch protocol between the OpenShell gateway and gateway-launched compute drivers" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +http = { workspace = true } +prost = { workspace = true } +tokio = { workspace = true, features = ["sync"] } +tonic = { workspace = true } +tonic-prost = { workspace = true } +tower = { workspace = true } + +[build-dependencies] +protoc-bin-vendored = { workspace = true } +tonic-prost-build = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true, features = ["macros", "rt"] } +tower = { workspace = true, features = ["util"] } + +[lints] +workspace = true diff --git a/crates/openshell-driver-launch/build.rs b/crates/openshell-driver-launch/build.rs new file mode 100644 index 0000000000..ee021e5c4f --- /dev/null +++ b/crates/openshell-driver-launch/build.rs @@ -0,0 +1,18 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +fn main() -> Result<(), Box> { + const PROTO: &str = "../../proto/driver_launch.proto"; + println!("cargo:rerun-if-changed={PROTO}"); + let mut config = tonic_prost_build::Config::new(); + config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); + let includes = [ + std::path::PathBuf::from("../../proto"), + protoc_bin_vendored::include_path()?, + ]; + tonic_prost_build::configure() + .build_server(true) + .build_client(true) + .compile_with_config(config, &[std::path::PathBuf::from(PROTO)], &includes)?; + Ok(()) +} diff --git a/crates/openshell-driver-launch/src/lib.rs b/crates/openshell-driver-launch/src/lib.rs new file mode 100644 index 0000000000..adfe7ea613 --- /dev/null +++ b/crates/openshell-driver-launch/src/lib.rs @@ -0,0 +1,334 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launch protocol between the gateway and the compute drivers it launches. +//! +//! The gateway starts a driver with a short bootstrap command line (socket, +//! peer PID, log level, OTLP). The driver serves [`proto::driver_launch_server::DriverLaunch`] +//! and its `ComputeDriver` service on that socket at once. `ComputeDriver` +//! RPCs return `UNAVAILABLE` until the gateway calls `Configure`, which builds +//! the driver. + +use std::convert::Infallible; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; + +use tonic::{Request, Response, Status}; + +#[allow( + clippy::all, + clippy::pedantic, + clippy::nursery, + unused_qualifications, + rust_2018_idioms +)] +pub mod proto { + tonic::include_proto!("openshell.driver.launch.v1"); +} + +use proto::driver_launch_server::{DriverLaunch, DriverLaunchServer}; +use proto::{ConfigureRequest, ConfigureResponse, GetLaunchInfoRequest, GetLaunchInfoResponse}; + +/// The launch protocol version this crate implements. +pub const PROTOCOL_VERSION: u32 = 1; + +/// Largest encoded `ConfigureRequest` a driver accepts on `preflight` stdin. +pub const MAX_CONFIGURE_REQUEST_BYTES: usize = 1024 * 1024; + +/// Encode a request for `preflight`, which reads it from stdin. +#[must_use] +pub fn encode_configure_request(request: &ConfigureRequest) -> Vec { + prost::Message::encode_to_vec(request) +} + +/// Decode the request `preflight` reads from stdin. +/// +/// # Errors +/// +/// Returns a message when the input is too large or not a `ConfigureRequest`. +pub fn decode_configure_request(bytes: &[u8]) -> Result { + if bytes.len() > MAX_CONFIGURE_REQUEST_BYTES { + return Err(format!( + "configure request exceeds {MAX_CONFIGURE_REQUEST_BYTES} bytes" + )); + } + ::decode(bytes) + .map_err(|error| format!("invalid configure request: {error}")) +} + +type BoxFuture = Pin + Send + 'static>>; +type ConfigureFn = Arc BoxFuture> + Send + Sync>; + +/// A gRPC service that answers `UNAVAILABLE` until `Configure` fills it. +pub struct Deferred { + slot: Arc>, +} + +impl Clone for Deferred { + fn clone(&self) -> Self { + Self { + slot: self.slot.clone(), + } + } +} + +impl tower::Service> for Deferred +where + S: tower::Service< + http::Request, + Response = http::Response, + Error = Infallible, + > + Clone + + Send + + Sync + + 'static, + S::Future: Send + 'static, +{ + type Response = http::Response; + type Error = Infallible; + type Future = BoxFuture>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, request: http::Request) -> Self::Future { + let Some(inner) = self.slot.get() else { + return Box::pin(async { + Ok( + Status::unavailable("compute driver is not configured; call Configure first") + .into_http(), + ) + }); + }; + let mut inner = inner.clone(); + Box::pin(async move { + std::future::poll_fn(|cx| inner.poll_ready(cx)).await?; + inner.call(request).await + }) + } +} + +impl tonic::server::NamedService for Deferred { + const NAME: &'static str = S::NAME; +} + +/// The driver side of `DriverLaunch`. +pub struct Launch { + slot: Arc>, + configuring: tokio::sync::Mutex<()>, + configure: ConfigureFn, + info: GetLaunchInfoResponse, +} + +#[tonic::async_trait] +impl DriverLaunch for Launch { + async fn get_launch_info( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(self.info.clone())) + } + + async fn configure( + &self, + request: Request, + ) -> Result, Status> { + let _configuring = self.configuring.lock().await; + if self.slot.get().is_some() { + return Err(Status::failed_precondition( + "compute driver is already configured", + )); + } + let request = request.into_inner(); + if !self + .info + .protocol_versions + .contains(&request.protocol_version) + { + return Err(Status::invalid_argument(format!( + "unsupported launch protocol version {}; this driver supports {:?}", + request.protocol_version, self.info.protocol_versions + ))); + } + if let Some(feature) = request + .required_features + .iter() + .find(|feature| !self.info.features.contains(feature)) + { + return Err(Status::failed_precondition(format!( + "compute driver does not support required feature '{feature}'" + ))); + } + let service = (self.configure)(request).await?; + let _ = self.slot.set(service); + Ok(Response::new(ConfigureResponse {})) + } +} + +/// Build the `DriverLaunch` service and the deferred driver service it fills. +/// +/// `configure` runs on each `Configure` call until one succeeds. A failed call +/// leaves the driver unconfigured so the gateway can retry. +pub fn services( + driver_name: &str, + driver_version: &str, + configure: F, +) -> (DriverLaunchServer>, Deferred) +where + S: Send + Sync + 'static, + F: Fn(ConfigureRequest) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let (launch, deferred) = parts(driver_name, driver_version, configure); + (DriverLaunchServer::new(launch), deferred) +} + +fn parts( + driver_name: &str, + driver_version: &str, + configure: F, +) -> (Launch, Deferred) +where + S: Send + Sync + 'static, + F: Fn(ConfigureRequest) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, +{ + let slot = Arc::new(OnceLock::new()); + let launch = Launch { + slot: slot.clone(), + configuring: tokio::sync::Mutex::new(()), + configure: Arc::new(move |request| Box::pin(configure(request))), + info: GetLaunchInfoResponse { + protocol_versions: vec![PROTOCOL_VERSION], + features: Vec::new(), + driver_name: driver_name.to_string(), + driver_version: driver_version.to_string(), + }, + }; + (launch, Deferred { slot }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + + fn request(version: u32, features: &[&str]) -> Request { + Request::new(ConfigureRequest { + protocol_version: version, + required_features: features.iter().map(ToString::to_string).collect(), + ..ConfigureRequest::default() + }) + } + + fn launch(fail_first: bool) -> (Launch, Arc) { + let calls = Arc::new(AtomicU32::new(0)); + let counter = calls.clone(); + let (launch, _deferred) = parts("test", "0", move |_request| { + let call = counter.fetch_add(1, Ordering::SeqCst); + async move { + if fail_first && call == 0 { + Err(Status::unavailable("backend down")) + } else { + Ok(7_u32) + } + } + }); + (launch, calls) + } + + #[tokio::test] + async fn configure_succeeds_once() { + let (launch, _) = launch(false); + launch + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap(); + let error = launch + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert_eq!(launch.slot.get(), Some(&7)); + } + + #[tokio::test] + async fn a_failed_configure_can_be_retried() { + let (launch, calls) = launch(true); + let error = launch + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::Unavailable); + assert!(launch.slot.get().is_none()); + launch + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn unknown_versions_and_features_are_refused_before_building() { + let (launch, calls) = launch(false); + let error = launch.configure(request(99, &[])).await.unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + let error = launch + .configure(request(PROTOCOL_VERSION, &["network_trust.v2"])) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + assert_eq!(calls.load(Ordering::SeqCst), 0); + } + + #[test] + fn configure_requests_round_trip_and_oversized_input_is_refused() { + let request = ConfigureRequest { + protocol_version: PROTOCOL_VERSION, + driver_config_toml: "network_name = \"n\"".to_string(), + ..ConfigureRequest::default() + }; + let decoded = decode_configure_request(&encode_configure_request(&request)).unwrap(); + assert_eq!(decoded, request); + let error = + decode_configure_request(&vec![0; MAX_CONFIGURE_REQUEST_BYTES + 1]).unwrap_err(); + assert!(error.contains("exceeds"), "{error}"); + } + + fn grpc_status(response: &http::Response) -> Option<&str> { + response + .headers() + .get("grpc-status") + .and_then(|value| value.to_str().ok()) + } + + #[tokio::test] + async fn the_deferred_service_is_unavailable_until_filled() { + use tower::ServiceExt as _; + + let mut deferred = Deferred { + slot: Arc::new(OnceLock::new()), + }; + let response = deferred + .clone() + .oneshot(http::Request::new(tonic::body::Body::empty())) + .await + .unwrap(); + assert_eq!(grpc_status(&response), Some("14")); + + let inner = tower::service_fn(|_request: http::Request| async { + Ok::<_, Infallible>(Status::not_found("from inner").into_http()) + }); + assert!(deferred.slot.set(inner).is_ok()); + let response = tower::Service::call( + &mut deferred, + http::Request::new(tonic::body::Body::empty()), + ) + .await + .unwrap(); + assert_eq!(grpc_status(&response), Some("5")); + } +} diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 74e6f3acc4..77fe56e461 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -630,6 +630,7 @@ mod tests { let mut isolation_methods = BTreeSet::new(); let mut sandbox_protocol_methods = BTreeSet::new(); let mut supervisor_host_methods = BTreeSet::new(); + let mut driver_launch_methods = BTreeSet::new(); for file in &public.file { let package = file.package.as_deref().unwrap_or_default(); for service in &file.service { @@ -661,6 +662,16 @@ mod tests { method.name.as_deref().expect("supervisor host method name") })); } + // Private gateway-to-launched-driver protocol: served by the + // driver, never by the gateway. + if package == "openshell.driver.launch.v1" { + assert_eq!(service_name, "DriverLaunch"); + driver_launch_methods.extend( + service.method.iter().map(|method| { + method.name.as_deref().expect("driver launch method name") + }), + ); + } if !matches!( (package, service_name), ( @@ -701,6 +712,10 @@ mod tests { BTreeSet::from(["Exchange", "Mediate"]) ); assert_eq!(supervisor_host_methods, BTreeSet::from(["Attach"])); + assert_eq!( + driver_launch_methods, + BTreeSet::from(["Configure", "GetLaunchInfo"]) + ); for signature in PROVIDER_READINESS_RPC_SIGNATURES { assert!( methods.iter().any(|method| method == signature), @@ -726,7 +741,8 @@ mod tests { + PEER_CONFIG_RPC_SIGNATURES.len() + isolation_methods.len() + sandbox_protocol_methods.len() - + supervisor_host_methods.len(), + + supervisor_host_methods.len() + + driver_launch_methods.len(), "classify every compiled RPC" ); assert_eq!( diff --git a/proto/driver_launch.proto b/proto/driver_launch.proto new file mode 100644 index 0000000000..b4262124d5 --- /dev/null +++ b/proto/driver_launch.proto @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package openshell.driver.launch.v1; + +// Served by a gateway-launched compute driver on its bootstrap socket, next to +// ComputeDriver. ComputeDriver RPCs return UNAVAILABLE until Configure +// succeeds. +service DriverLaunch { + // Protocol versions and features the driver supports. Callable at any time. + rpc GetLaunchInfo(GetLaunchInfoRequest) returns (GetLaunchInfoResponse); + // Build the driver. Succeeds at most once per process; a failed call can be + // retried. + rpc Configure(ConfigureRequest) returns (ConfigureResponse); +} + +message GetLaunchInfoRequest {} + +message GetLaunchInfoResponse { + repeated uint32 protocol_versions = 1; + repeated string features = 2; + string driver_name = 3; + string driver_version = 4; +} + +message ConfigureRequest { + // One of GetLaunchInfoResponse.protocol_versions. + uint32 protocol_version = 1; + // Features the driver must honour. A driver rejects any it does not know. + repeated string required_features = 2; + GatewayContext gateway = 3; + // Absent when the gateway has no network trust bundle. + NetworkTrust network_trust = 4; + // The operator's driver table, TOML-encoded. Opaque to the gateway. + string driver_config_toml = 5; + // Gateway-resolved overrides the driver applies over driver_config. + ImageOverrides image_overrides = 6; + // Absent when the gateway exports no telemetry. + Telemetry telemetry = 7; +} + +message GatewayContext { + uint32 gateway_port = 1; + // Path of the gateway's guest TLS CA, empty when the gateway does not serve TLS. + string tls_ca_path = 2; + string gateway_name = 3; +} + +// OTLP settings for the driver's own trace export and for the supervisors it +// starts. The driver logs to stderr from process start and begins exporting +// when Configure arrives. +message Telemetry { + OtlpExport traces = 1; + OtlpExport ocsf = 2; + OtlpExport agent = 3; + // TLS files for the driver's trace collector. + CollectorTls collector = 4; + // Secret. Headers for the driver's trace export, as comma-separated + // name=value pairs. + string trace_headers = 5; +} + +message OtlpExport { + string endpoint = 1; + // "grpc" (default when empty) or "http/protobuf". + string protocol = 2; +} + +message CollectorTls { + string ca_file = 1; + string cert_file = 2; + string key_file = 3; +} + +// The gateway's staged bundle file. Drivers load it once, check it against the +// digest and count, and bind-mount it into sandboxes, re-verifying it first. +message NetworkTrust { + string artifact_path = 1; + // "sha256:" of the normalized PEM. + string digest = 2; + uint32 certificate_count = 3; +} + +message ImageOverrides { + optional string sandbox_runtime_image = 1; + optional string supervisor_image = 2; +} + +message ConfigureResponse {} From bac7c5807bfded1b0245dd39430fca382d7ec3da Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:19:06 +0000 Subject: [PATCH 3/9] feat(drivers): add a shared SDK for launched compute drivers openshell-driver-sdk holds what launched drivers share on top of the launch protocol: applying Configure telemetry to supervisor OTLP settings and the driver's own export, loading and re-verifying the gateway's staged network trust artifact, stopping with the gateway, and the bounded JSON results of the probe and preflight subcommands. The VM driver's network trust loader moves here unchanged. Signed-off-by: Evan Lezar --- AGENTS.md | 2 + Cargo.lock | 18 ++ crates/openshell-driver-sdk/Cargo.toml | 33 +++ crates/openshell-driver-sdk/README.md | 25 ++ crates/openshell-driver-sdk/src/launch.rs | 166 ++++++++++++ crates/openshell-driver-sdk/src/lib.rs | 15 ++ .../openshell-driver-sdk/src/network_trust.rs | 239 ++++++++++++++++++ crates/openshell-driver-sdk/src/parent.rs | 65 +++++ crates/openshell-driver-sdk/src/preflight.rs | 97 +++++++ crates/openshell-driver-sdk/src/probe.rs | 93 +++++++ crates/openshell-driver-vm/Cargo.toml | 1 + crates/openshell-driver-vm/src/driver.rs | 212 +--------------- 12 files changed, 764 insertions(+), 202 deletions(-) create mode 100644 crates/openshell-driver-sdk/Cargo.toml create mode 100644 crates/openshell-driver-sdk/README.md create mode 100644 crates/openshell-driver-sdk/src/launch.rs create mode 100644 crates/openshell-driver-sdk/src/lib.rs create mode 100644 crates/openshell-driver-sdk/src/network_trust.rs create mode 100644 crates/openshell-driver-sdk/src/parent.rs create mode 100644 crates/openshell-driver-sdk/src/preflight.rs create mode 100644 crates/openshell-driver-sdk/src/probe.rs diff --git a/AGENTS.md b/AGENTS.md index 20c8d5ac0a..c35d2b28bb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,8 @@ 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-launch/` | Driver launch protocol | `GetLaunchInfo` and `Configure` services the gateway uses to configure the compute drivers it launches | +| `crates/openshell-driver-sdk/` | Driver SDK | Helpers shared by launched compute drivers: `Configure` telemetry, network trust artifact loading, parent-death handling, and `probe` and `preflight` results | | `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 67026195ba..9659cc90b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4797,6 +4797,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "openshell-driver-sdk" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "libc", + "openshell-core", + "openshell-crypto", + "openshell-driver-launch", + "openshell-otel", + "serde", + "serde_json", + "thiserror 2.0.20", + "toml", + "tracing", +] + [[package]] name = "openshell-driver-vault" version = "0.0.0" @@ -4841,6 +4858,7 @@ dependencies = [ "openshell-core", "openshell-crypto", "openshell-driver-podman", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", diff --git a/crates/openshell-driver-sdk/Cargo.toml b/crates/openshell-driver-sdk/Cargo.toml new file mode 100644 index 0000000000..5828266092 --- /dev/null +++ b/crates/openshell-driver-sdk/Cargo.toml @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-sdk" +description = "Shared helpers for compute drivers launched by the OpenShell gateway" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +base64 = { workspace = true } +openshell-crypto = { workspace = true } +openshell-driver-launch = { path = "../openshell-driver-launch" } +openshell-otel = { path = "../openshell-otel" } +tracing = { 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 take `SupervisorOtlpArgs` on their command line. +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..65c30df86e --- /dev/null +++ b/crates/openshell-driver-sdk/README.md @@ -0,0 +1,25 @@ +# openshell-driver-sdk + +Shared helpers for the compute drivers the gateway launches. + +The gateway starts a driver as `openshell-driver- serve` with only its +socket path, the gateway's process ID, and the log level, then configures it +with the `Configure` RPC from `openshell-driver-launch`. This crate holds what +drivers share on top of that protocol: + +- `launch`: applies `Configure` telemetry to the driver's supervisor OTLP + settings and enables the driver's own trace export. +- `network_trust`: loads and re-verifies the gateway's staged network trust + artifact from its path, digest, and certificate count. +- `parent`: stops the driver when the gateway exits. +- `probe` and `preflight`: the JSON results of those subcommands. + +## 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 configuration, and the gateway gives it five +seconds and 4 KiB. `preflight` reads a protobuf-encoded `ConfigureRequest` from stdin and +validates it 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/launch.rs b/crates/openshell-driver-sdk/src/launch.rs new file mode 100644 index 0000000000..c6aa061e4c --- /dev/null +++ b/crates/openshell-driver-sdk/src/launch.rs @@ -0,0 +1,166 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Reading the gateway's telemetry from a `Configure` request, for drivers the +//! gateway launches in `serve` mode. + +use openshell_core::sandbox_env::{OtlpExport, OtlpProtocol, SupervisorOtlp}; +use openshell_driver_launch::proto::{ConfigureRequest, Telemetry}; + +fn export( + export: Option<&openshell_driver_launch::proto::OtlpExport>, +) -> Result, String> { + export + .map(|export| { + let protocol = if export.protocol.is_empty() { + OtlpProtocol::default() + } else { + export.protocol.parse()? + }; + Ok(OtlpExport { + endpoint: export.endpoint.clone(), + protocol, + }) + }) + .transpose() +} + +/// The exports a driver passes to the supervisors it starts. +/// +/// # Errors +/// +/// Returns a message when an export names an unknown protocol. +pub fn supervisor_otlp(telemetry: Option<&Telemetry>) -> Result { + let Some(telemetry) = telemetry else { + return Ok(SupervisorOtlp::default()); + }; + Ok(SupervisorOtlp { + traces: export(telemetry.traces.as_ref())?, + ocsf: export(telemetry.ocsf.as_ref())?, + agent: export(telemetry.agent.as_ref())?, + }) +} + +/// Set a driver's OTLP command-line settings from the request's telemetry. +/// Settings the request leaves out keep their current values. +/// +/// # Errors +/// +/// Returns a message when an export names an unknown protocol. +#[cfg(feature = "clap")] +pub fn apply_telemetry( + telemetry: Option<&Telemetry>, + args: &mut openshell_core::sandbox_env::SupervisorOtlpArgs, +) -> Result<(), String> { + let Some(telemetry) = telemetry else { + return Ok(()); + }; + let otlp = supervisor_otlp(Some(telemetry))?; + if let Some(export) = otlp.traces { + args.endpoint = Some(export.endpoint); + args.protocol = export.protocol; + } + if let Some(export) = otlp.ocsf { + args.ocsf_endpoint = Some(export.endpoint); + args.ocsf_protocol = export.protocol; + } + if let Some(export) = otlp.agent { + args.agent_endpoint = Some(export.endpoint); + args.agent_protocol = export.protocol; + } + if let Some(collector) = &telemetry.collector { + let path = |path: &str| (!path.is_empty()).then(|| path.into()); + args.ca_file = path(&collector.ca_file); + args.cert_file = path(&collector.cert_file); + args.key_file = path(&collector.key_file); + } + Ok(()) +} + +/// Start the driver's own trace export from the request's telemetry. Setup +/// failures are logged, as at standalone startup. +pub fn enable_export( + tracing: &openshell_otel::DeferredDriverTracing, + request: &ConfigureRequest, + log_level: &str, + ansi: bool, + service_version: &'static str, +) { + let Some(telemetry) = request.telemetry.as_ref() else { + return; + }; + let Some(traces) = telemetry.traces.as_ref() else { + return; + }; + let protocol = match export(Some(traces)) { + Ok(export) => export.map(|export| export.protocol).unwrap_or_default(), + Err(error) => { + tracing::error!(%error, "OTLP exporting could not be started"); + return; + } + }; + let collector = telemetry.collector.clone().unwrap_or_default(); + let path = |path: &str| (!path.is_empty()).then(|| std::path::PathBuf::from(path)); + let (ca_file, cert_file, key_file) = ( + path(&collector.ca_file), + path(&collector.cert_file), + path(&collector.key_file), + ); + let gateway_name = request + .gateway + .as_ref() + .map(|gateway| gateway.gateway_name.as_str()) + .filter(|name| !name.is_empty()); + tracing.enable_export( + openshell_otel::DriverTracingConfig { + endpoint: Some(&traces.endpoint), + protocol: protocol.into(), + ca_file: ca_file.as_deref(), + cert_file: cert_file.as_deref(), + key_file: key_file.as_deref(), + gateway_name, + service_version, + log_level, + ansi, + }, + openshell_otel::parse_otlp_headers(&telemetry.trace_headers), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_driver_launch::proto::{CollectorTls, OtlpExport as WireExport}; + + fn telemetry() -> Telemetry { + Telemetry { + traces: Some(WireExport { + endpoint: "https://collector:4317".into(), + protocol: String::new(), + }), + ocsf: Some(WireExport { + endpoint: "https://collector:4318".into(), + protocol: "http/protobuf".into(), + }), + agent: None, + collector: Some(CollectorTls { + ca_file: "/ca.pem".into(), + ..CollectorTls::default() + }), + trace_headers: String::new(), + } + } + + #[test] + fn supervisor_exports_default_to_grpc_and_reject_unknown_protocols() { + let otlp = supervisor_otlp(Some(&telemetry())).unwrap(); + assert_eq!(otlp.traces.unwrap().protocol, OtlpProtocol::Grpc); + assert_eq!(otlp.ocsf.unwrap().protocol, OtlpProtocol::HttpProtobuf); + assert!(otlp.agent.is_none()); + + let mut unknown = telemetry(); + unknown.traces.as_mut().unwrap().protocol = "carrier-pigeon".into(); + assert!(supervisor_otlp(Some(&unknown)).is_err()); + assert_eq!(supervisor_otlp(None).unwrap(), SupervisorOtlp::default()); + } +} diff --git a/crates/openshell-driver-sdk/src/lib.rs b/crates/openshell-driver-sdk/src/lib.rs new file mode 100644 index 0000000000..ffffd84cfb --- /dev/null +++ b/crates/openshell-driver-sdk/src/lib.rs @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Shared helpers for the compute drivers the `OpenShell` gateway launches. +//! +//! The launch protocol itself (`GetLaunchInfo` and `Configure`) is in +//! `openshell-driver-launch`. This crate holds what drivers share on top of +//! it: applying `Configure` telemetry, loading the staged network trust +//! artifact, parent-death handling, and the `probe` and `preflight` results. + +pub mod launch; +pub mod network_trust; +pub mod parent; +pub mod preflight; +pub mod probe; 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..630b9c3dec --- /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. +//! +//! `Configure` 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..f551585201 --- /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` reads a protobuf-encoded +//! `ConfigureRequest` from stdin and validates it 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 `Configure` request. +#[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-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index 57921d4b9a..a4ef8142d7 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -54,6 +54,7 @@ openshell-crypto = { workspace = true, optional = true } url = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } +openshell-driver-sdk = { path = "../openshell-driver-sdk" } oci-client = { version = "0.16", optional = true } libc = "0.2" rustix = { workspace = true, features = ["fs"] } 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, From bb4e2dedad975e1fe0250235245bb1e944d79f32 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:20:56 +0000 Subject: [PATCH 4/9] feat(vm): serve the launch protocol and take configuration from Configure openshell-driver-vm serve binds the socket with only --bind-socket, --expected-peer-pid and --log-level, keeps its peer PID check, and returns UNAVAILABLE from ComputeDriver until Configure succeeds. Configure decodes the operator's [openshell.drivers.vm] table, which the driver now owns and validates, applies the gateway context, telemetry and network trust artifact, and defaults the sandbox endpoint to the gateway's listener as before. A rejected Configure leaves the driver running so the gateway can retry. preflight reads the same request from stdin and validates it without starting the driver. The standalone flag mode is unchanged. Signed-off-by: Evan Lezar --- Cargo.lock | 4 + crates/openshell-driver-vm/Cargo.toml | 6 +- crates/openshell-driver-vm/src/lib.rs | 3 + crates/openshell-driver-vm/src/main.rs | 432 ++++++++++++++++-- .../openshell-driver-vm/src/startup_config.rs | 353 ++++++++++++++ .../tests/fixtures/driver-config-vm.toml | 34 ++ .../tests/serve_configure.rs | 136 ++++++ 7 files changed, 921 insertions(+), 47 deletions(-) create mode 100644 crates/openshell-driver-vm/src/startup_config.rs create mode 100644 crates/openshell-driver-vm/tests/fixtures/driver-config-vm.toml create mode 100644 crates/openshell-driver-vm/tests/serve_configure.rs diff --git a/Cargo.lock b/Cargo.lock index 9659cc90b2..76ae8e6d2e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4850,6 +4850,7 @@ dependencies = [ "flate2", "futures", "http 1.4.0", + "hyper-util", "libc", "libloading", "miette", @@ -4857,6 +4858,7 @@ dependencies = [ "oci-client", "openshell-core", "openshell-crypto", + "openshell-driver-launch", "openshell-driver-podman", "openshell-driver-sdk", "openshell-isolation-interface", @@ -4880,7 +4882,9 @@ dependencies = [ "tempfile", "tokio", "tokio-stream", + "toml", "tonic", + "tower", "tower-http 0.6.8", "tracing", "tracing-opentelemetry", diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index a4ef8142d7..466541860b 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -54,7 +54,9 @@ openshell-crypto = { workspace = true, optional = true } url = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } -openshell-driver-sdk = { path = "../openshell-driver-sdk" } +toml = { workspace = true } +openshell-driver-sdk = { path = "../openshell-driver-sdk", features = ["clap"] } +openshell-driver-launch = { path = "../openshell-driver-launch" } oci-client = { version = "0.16", optional = true } libc = "0.2" rustix = { workspace = true, features = ["fs"] } @@ -117,6 +119,8 @@ telemetry = ["openshell-core/telemetry"] defaults-without-telemetry = ["compute-driver"] [dev-dependencies] +hyper-util = { workspace = true } +tower = { workspace = true, features = ["util"] } openshell-otel-test-support = { path = "../openshell-otel-test-support" } temp-env = "0.3" tempfile = "3" 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..6ac0cb71e4 100644 --- a/crates/openshell-driver-vm/src/main.rs +++ b/crates/openshell-driver-vm/src/main.rs @@ -7,6 +7,7 @@ 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_vm::startup_config::VmComputeConfig; #[cfg(target_os = "macos")] use openshell_driver_vm::{VM_RUNTIME_DIR_ENV, configured_runtime_dir}; use openshell_driver_vm::{ @@ -17,6 +18,7 @@ use std::net::SocketAddr; use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::pin::Pin; +use std::sync::{Arc, OnceLock}; use std::task::{Context, Poll}; use tokio::net::{UnixListener, UnixStream}; use tracing::info; @@ -275,47 +277,61 @@ struct Args { vm_mount: Vec, } -#[tokio::main] -async fn main() -> Result<()> { - let args = Args::parse(); - if let Some(request) = args.internal_prepare_image { - openshell_driver_vm::driver::run_image_preparation_worker(&request) - .await - .map_err(|error| miette::miette!("{error}"))?; - return Ok(()); - } - if args.internal_run_vm { - // The VM launcher arms procguard after resolving its runtime so its - // libkrun worker cannot outlive the launcher. - maybe_reexec_internal_vm_with_runtime_env()?; - let config = build_vm_launch_config(&args).map_err(|err| miette::miette!("{err}"))?; - run_vm(&config).map_err(|err| miette::miette!("{err}"))?; - return Ok(()); - } +/// `preflight` reads the `Configure` request the gateway would send from +/// stdin, validates it, and reports on stdout. It starts nothing and creates +/// no state. +fn run_preflight(arguments: &[std::ffi::OsString]) -> ! { + use openshell_driver_sdk::preflight::PreflightResult; + use std::io::Read as _; + + let result = if arguments.is_empty() { + let mut input = Vec::new(); + io::stdin() + .take(openshell_driver_launch::MAX_CONFIGURE_REQUEST_BYTES as u64 + 1) + .read_to_end(&mut input) + .map_err(|error| format!("failed to read the configure request: {error}")) + .and_then(|_| openshell_driver_launch::decode_configure_request(&input)) + .and_then(|request| configured_args(&request, "info".to_string())) + .and_then(|args| vm_driver_config(&args)) + .map_or_else(PreflightResult::rejected, |_| PreflightResult::ok()) + } else { + PreflightResult::rejected("usage: preflight < configure-request") + }; + println!("{}", result.to_json()); + std::process::exit(0); +} - let _tracing = openshell_otel::install_driver_tracing( - openshell_driver_vm::otel_tracing::TRACING, - openshell_otel::DriverTracingConfig { - endpoint: args.otlp.endpoint.as_deref(), - protocol: args.otlp.protocol.into(), - ca_file: args.otlp.ca_file.as_deref(), - cert_file: args.otlp.cert_file.as_deref(), - key_file: args.otlp.key_file.as_deref(), - gateway_name: args.gateway_name.as_deref(), - service_version: VERSION, - log_level: &args.log_level, - ansi: openshell_core::color::stdout_ansi(), - }, - ); - args.otlp.warn_deprecated(); +/// Bootstrap flags of `serve`, the mode a gateway launches the driver in. +/// Everything else, telemetry included, arrives in the `Configure` RPC. +#[derive(Parser)] +#[command(name = "openshell-driver-vm serve")] +struct ServeArgs { + /// Unix socket the gateway connects to. + #[arg(long)] + bind_socket: PathBuf, - let listen_mode = compute_driver_listen_mode(&args).map_err(|err| miette::miette!("{err}"))?; + /// The launching gateway's PID; only it may connect. + #[arg(long)] + expected_peer_pid: u32, - // Arm procguard so that if the gateway is killed (SIGKILL or crash) - // we also die. Without this the driver is reparented to init and - // keeps its per-sandbox VM launchers alive forever. Launchers have - // their own procguards (armed in `run_vm`) which cascade cleanup of - // the libkrun worker the moment this driver exits. + #[arg(long, default_value = "info")] + log_level: String, +} + +/// Serve `DriverLaunch` at once and build the VM driver when the gateway calls +/// `Configure`. +async fn run_serve(arguments: &[std::ffi::OsString]) -> Result<()> { + let args = ServeArgs::parse_from( + std::iter::once(std::ffi::OsString::from("openshell-driver-vm serve")) + .chain(arguments.iter().cloned()), + ); + let ansi = openshell_core::color::stdout_ansi(); + let driver_tracing = Arc::new(openshell_otel::install_deferred_driver_tracing( + openshell_driver_vm::otel_tracing::TRACING, + &args.log_level, + ansi, + )); + // If the gateway is killed, this driver and its VM launchers must die too. if let Err(err) = procguard::die_with_parent() { tracing::warn!( error = %err, @@ -323,14 +339,105 @@ async fn main() -> Result<()> { ); } - let supervisor_otlp = args.otlp.supervisor_otlp(); - let driver = VmDriver::new(VmDriverConfig { + let configured = Arc::new(OnceLock::::new()); + let slot = configured.clone(); + let log_level = args.log_level.clone(); + let (launch, compute) = openshell_driver_launch::services("vm", VERSION, move |request| { + openshell_driver_sdk::launch::enable_export( + &driver_tracing, + &request, + &log_level, + ansi, + VERSION, + ); + let config = + configured_args(&request, log_level.clone()).and_then(|args| vm_driver_config(&args)); + let slot = slot.clone(); + async move { + let config = config.map_err(tonic::Status::invalid_argument)?; + let driver = VmDriver::new(config) + .await + .map_err(tonic::Status::unavailable)?; + let _ = slot.set(driver.clone()); + info!("vm compute driver configured"); + Ok(ComputeDriverServer::new(driver)) + } + }); + + let socket_path = args.bind_socket; + prepare_compute_driver_socket(&socket_path).map_err(|err| miette::miette!("{err}"))?; + info!(socket = %socket_path.display(), "Starting vm compute driver; waiting for Configure"); + let listener = UnixListener::bind(&socket_path).into_diagnostic()?; + restrict_socket_permissions(&socket_path).map_err(|err| miette::miette!("{err}"))?; + let result = tonic::transport::Server::builder() + .layer(openshell_otel::compute_driver_rpc_layer()) + .add_service(launch) + .add_service(compute) + .serve_with_incoming_shutdown( + AuthenticatedUnixIncoming::new(listener, Some(args.expected_peer_pid)), + shutdown_signal(), + ) + .await + .into_diagnostic(); + let _ = std::fs::remove_file(&socket_path); + if let Some(driver) = configured.get() { + driver.remove_socket_root(); + } + result +} + +/// The driver's settings for a `Configure` request: the environment and +/// defaults, overlaid with the gateway's settings. +fn configured_args( + request: &openshell_driver_launch::proto::ConfigureRequest, + log_level: String, +) -> std::result::Result { + let mut args = + Args::try_parse_from(["openshell-driver-vm"]).map_err(|error| error.to_string())?; + args.log_level = log_level; + apply_configure(&mut args, request)?; + Ok(args) +} + +/// Overlay a `Configure` request onto the default flags. The request is +/// authoritative for everything it carries; a driver setting the operator +/// table leaves out keeps its default. +fn apply_configure( + args: &mut Args, + request: &openshell_driver_launch::proto::ConfigureRequest, +) -> std::result::Result<(), String> { + let gateway = request.gateway.clone().unwrap_or_default(); + args.gateway_name = (!gateway.gateway_name.is_empty()).then(|| gateway.gateway_name.clone()); + args.guest_tls_ca = + (!gateway.tls_ca_path.is_empty()).then(|| PathBuf::from(&gateway.tls_ca_path)); + openshell_driver_sdk::launch::apply_telemetry(request.telemetry.as_ref(), &mut args.otlp)?; + if let Some(trust) = &request.network_trust { + args.additional_ca_bundle = Some(PathBuf::from(&trust.artifact_path)); + 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 config: VmComputeConfig = toml::from_str(&request.driver_config_toml) + .map_err(|error| format!("invalid driver_config: {error}"))?; + let gateway_port = u16::try_from(gateway.gateway_port) + .map_err(|_| format!("gateway port {} is out of range", gateway.gateway_port))?; + let has_tls_ca = args.guest_tls_ca.is_some(); + apply_vm_config(args, config, gateway_port, has_tls_ca) +} + +/// The driver configuration the flags, environment, and any gateway settings +/// applied to `args` describe. +fn vm_driver_config(args: &Args) -> std::result::Result { + Ok(VmDriverConfig { allow_driver_config: args.admission_config_json.allow_driver_config, resource_admission: args.admission_config_json.resource_admission.clone(), grpc_endpoint: args .grpc_endpoint - .ok_or_else(|| miette::miette!("OPENSHELL_GRPC_ENDPOINT is required"))?, - supervisor_otlp, + .clone() + .ok_or_else(|| "OPENSHELL_GRPC_ENDPOINT is required".to_string())?, + supervisor_otlp: args.otlp.supervisor_otlp(), supervisor_gateway_name: args.gateway_name.clone(), state_dir: args.state_dir.clone(), launcher_bin: None, @@ -369,8 +476,66 @@ async fn main() -> Result<()> { rootfs_tar_max_bytes: args.rootfs_tar_max_bytes, enable_bind_mounts: args.enable_bind_mounts, }) - .await - .map_err(|err| miette::miette!("{err}"))?; +} + +#[tokio::main] +async fn main() -> Result<()> { + let arguments: Vec<_> = std::env::args_os().skip(1).collect(); + if arguments.first().is_some_and(|arg| arg == "serve") { + return run_serve(&arguments[1..]).await; + } + if arguments.first().is_some_and(|arg| arg == "preflight") { + run_preflight(&arguments[1..]); + } + let args = Args::parse(); + if let Some(request) = args.internal_prepare_image { + openshell_driver_vm::driver::run_image_preparation_worker(&request) + .await + .map_err(|error| miette::miette!("{error}"))?; + return Ok(()); + } + if args.internal_run_vm { + // The VM launcher arms procguard after resolving its runtime so its + // libkrun worker cannot outlive the launcher. + maybe_reexec_internal_vm_with_runtime_env()?; + let config = build_vm_launch_config(&args).map_err(|err| miette::miette!("{err}"))?; + run_vm(&config).map_err(|err| miette::miette!("{err}"))?; + return Ok(()); + } + + let _tracing = openshell_otel::install_driver_tracing( + openshell_driver_vm::otel_tracing::TRACING, + openshell_otel::DriverTracingConfig { + endpoint: args.otlp.endpoint.as_deref(), + protocol: args.otlp.protocol.into(), + ca_file: args.otlp.ca_file.as_deref(), + cert_file: args.otlp.cert_file.as_deref(), + key_file: args.otlp.key_file.as_deref(), + gateway_name: args.gateway_name.as_deref(), + service_version: VERSION, + log_level: &args.log_level, + ansi: openshell_core::color::stdout_ansi(), + }, + ); + args.otlp.warn_deprecated(); + + let listen_mode = compute_driver_listen_mode(&args).map_err(|err| miette::miette!("{err}"))?; + + // Arm procguard so that if the gateway is killed (SIGKILL or crash) + // we also die. Without this the driver is reparented to init and + // keeps its per-sandbox VM launchers alive forever. Launchers have + // their own procguards (armed in `run_vm`) which cascade cleanup of + // the libkrun worker the moment this driver exits. + if let Err(err) = procguard::die_with_parent() { + tracing::warn!( + error = %err, + "procguard arm failed; gateway crashes may orphan this driver" + ); + } + + let driver = VmDriver::new(vm_driver_config(&args).map_err(|err| miette::miette!("{err}"))?) + .await + .map_err(|err| miette::miette!("{err}"))?; let socket_cleanup = driver.clone(); let result = match listen_mode { @@ -409,6 +574,65 @@ async fn main() -> Result<()> { result } +/// Apply the driver's own table on top of the gateway context already set on +/// `args`, defaulting the sandbox endpoint to the gateway's own listener. +fn apply_vm_config( + args: &mut Args, + mut config: VmComputeConfig, + gateway_port: u16, + has_tls_ca: bool, +) -> std::result::Result<(), String> { + 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 has_tls_ca { "https" } else { "http" }; + config.grpc_endpoint = format!("{scheme}://127.0.0.1:{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"); @@ -785,10 +1009,126 @@ fn maybe_reexec_internal_vm_with_runtime_env() -> Result<()> { mod tests { use super::{ Args, ComputeDriverListenMode, PeerCredentials, authorize_peer_credentials, - compute_driver_listen_mode, parse_vm_mount_arg, + compute_driver_listen_mode, configured_args, parse_vm_mount_arg, vm_driver_config, }; use clap::Parser; - use std::path::PathBuf; + use std::path::{Path, PathBuf}; + + const VM_DRIVER_CONFIG_FIXTURE: &str = include_str!("../tests/fixtures/driver-config-vm.toml"); + + /// `Configure` supplies the settings the gateway used to pass as flags. + #[test] + fn configure_supplies_the_settings_the_gateway_used_to_pass_as_flags() { + use openshell_driver_launch::proto::{ + CollectorTls, ConfigureRequest, GatewayContext, NetworkTrust, OtlpExport, Telemetry, + }; + + let export = |endpoint: &str, protocol: &str| { + Some(OtlpExport { + endpoint: endpoint.to_string(), + protocol: protocol.to_string(), + }) + }; + let request = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(GatewayContext { + gateway_port: 8080, + tls_ca_path: "/etc/openshell/tls/ca.pem".to_string(), + gateway_name: "gateway-a".to_string(), + }), + network_trust: Some(NetworkTrust { + artifact_path: "/var/lib/openshell/trust/bundle.pem".to_string(), + digest: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + .to_string(), + certificate_count: 3, + }), + driver_config_toml: VM_DRIVER_CONFIG_FIXTURE.to_string(), + telemetry: Some(Telemetry { + traces: export("https://collector.example:4317", "grpc"), + ocsf: export("https://collector.example:4318", "http/protobuf"), + agent: export("https://collector.example:4319", "grpc"), + collector: Some(CollectorTls { + ca_file: "/etc/openshell/otlp/ca.pem".to_string(), + cert_file: "/etc/openshell/otlp/cert.pem".to_string(), + key_file: "/etc/openshell/otlp/key.pem".to_string(), + }), + trace_headers: String::new(), + }), + ..ConfigureRequest::default() + }; + let args = configured_args(&request, "debug".to_string()).unwrap(); + assert!(args.bind_socket.is_none()); + assert!(args.expected_peer_pid.is_none()); + 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); + vm_driver_config(&args).unwrap(); + } + + #[test] + fn configure_defaults_the_endpoint_to_the_gateway_listener() { + let request = openshell_driver_launch::proto::ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(openshell_driver_launch::proto::GatewayContext { + gateway_port: 9090, + tls_ca_path: String::new(), + gateway_name: "g".to_string(), + }), + ..Default::default() + }; + let args = configured_args(&request, "info".to_string()).unwrap(); + assert_eq!(args.grpc_endpoint.as_deref(), Some("http://127.0.0.1:9090")); + + let unknown = openshell_driver_launch::proto::ConfigureRequest { + driver_config_toml: "surprise = 1".to_string(), + ..request + }; + let error = configured_args(&unknown, "info".to_string()).unwrap_err(); + assert!(error.contains("surprise"), "{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..96ee9072c8 --- /dev/null +++ b/crates/openshell-driver-vm/src/startup_config.rs @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The VM driver's configuration. +//! +//! The gateway passes the operator's `[openshell.drivers.vm]` table through +//! unchanged in `Configure`; [`VmComputeConfig`] is what the driver accepts in +//! it, and the driver validates it there. + +use std::path::PathBuf; + +use openshell_core::{Error, Result, UpstreamProxyConfig}; + +/// The VM driver's own configuration: the operator's `[openshell.drivers.vm]` +/// table, which the gateway passes through in `Configure`. The driver +/// validates it there. +#[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, + } + } +} + +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/driver-config-vm.toml"); + + #[test] + fn the_fixture_driver_config_deserializes_and_validates() { + let config: VmComputeConfig = toml::from_str(FIXTURE).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 error = toml::from_str::("surprise = 1") + .unwrap_err() + .to_string(); + assert!(error.contains("surprise"), "{error}"); + } + + #[test] + fn keys_the_gateway_owns_are_rejected_in_driver_config() { + for key in ["guest_tls_ca", "driver_dir"] { + assert!( + toml::from_str::(&format!("{key} = '/x'")).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/driver-config-vm.toml b/crates/openshell-driver-vm/tests/fixtures/driver-config-vm.toml new file mode 100644 index 0000000000..48f3dfe9fe --- /dev/null +++ b/crates/openshell-driver-vm/tests/fixtures/driver-config-vm.toml @@ -0,0 +1,34 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# The operator's [openshell.drivers.vm] table as `Configure` carries it, with +# every VM setting populated. + +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 + +[resource_admission] +enabled = true + +[resource_admission.required_labels] +"openshell.ai/sandbox-attachable" = "true" diff --git a/crates/openshell-driver-vm/tests/serve_configure.rs b/crates/openshell-driver-vm/tests/serve_configure.rs new file mode 100644 index 0000000000..93e8c18b99 --- /dev/null +++ b/crates/openshell-driver-vm/tests/serve_configure.rs @@ -0,0 +1,136 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The `serve` mode a gateway launches the VM driver in: the launch +//! service answers at once, compute RPCs wait for `Configure`, and a rejected +//! `Configure` leaves the driver running so the gateway can retry. + +#![cfg(unix)] + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use hyper_util::rt::TokioIo; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; +use openshell_driver_launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_launch::proto::{ConfigureRequest, GatewayContext, GetLaunchInfoRequest}; +use tokio::net::UnixStream; +use tonic::transport::{Channel, Endpoint}; + +const FIXTURE: &str = include_str!("fixtures/driver-config-vm.toml"); + +async fn connect(socket: &Path) -> Channel { + for _ in 0..100 { + let path: PathBuf = socket.to_path_buf(); + let connected = Endpoint::from_static("http://[::]:50051") + .connect_with_connector(tower::service_fn(move |_: tonic::transport::Uri| { + let path = path.clone(); + async move { UnixStream::connect(path).await.map(TokioIo::new) } + })) + .await; + if let Ok(channel) = connected { + return channel; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("driver socket {} never came up", socket.display()); +} + +#[tokio::test] +async fn serve_waits_for_configure_and_survives_a_rejected_one() { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("run").join("compute-driver.sock"); + let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell-driver-vm")) + .arg("serve") + .arg("--bind-socket") + .arg(&socket) + .arg("--expected-peer-pid") + .arg(std::process::id().to_string()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let channel = connect(&socket).await; + + let mut launch = DriverLaunchClient::new(channel.clone()); + let info = launch + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!( + info.protocol_versions, + vec![openshell_driver_launch::PROTOCOL_VERSION] + ); + assert_eq!(info.driver_name, "vm"); + + let mut compute = ComputeDriverClient::new(channel.clone()); + let status = compute + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable, "{status:?}"); + + let invalid = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + driver_config_toml: "surprise = 1".to_string(), + ..ConfigureRequest::default() + }; + let status = launch.configure(invalid).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument, "{status:?}"); + + // A rejected `Configure` leaves the driver up for another attempt. + assert!(child.try_wait().unwrap().is_none()); + let status = compute + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable, "{status:?}"); + + child.kill().await.unwrap(); +} + +fn preflight(input: &[u8]) -> serde_json::Value { + use std::io::Write as _; + + let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_openshell-driver-vm")) + .arg("preflight") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + serde_json::from_slice(&output.stdout).unwrap() +} + +#[test] +fn preflight_validates_the_configure_request_from_stdin() { + let valid = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(GatewayContext { + gateway_port: 8080, + tls_ca_path: String::new(), + gateway_name: "gateway-a".to_string(), + }), + driver_config_toml: FIXTURE.to_string(), + ..ConfigureRequest::default() + }; + let result = preflight(&openshell_driver_launch::encode_configure_request(&valid)); + assert_eq!(result["ok"], true, "{result}"); + + let invalid = ConfigureRequest { + driver_config_toml: "surprise = 1".to_string(), + ..valid + }; + let result = preflight(&openshell_driver_launch::encode_configure_request(&invalid)); + assert_eq!(result["ok"], false); + assert!( + result["error"].as_str().unwrap().contains("surprise"), + "{result}" + ); + + let result = preflight(b"not a request"); + assert_eq!(result["ok"], false, "{result}"); +} From 2c5f6c8e8c77e5aee77abe2d21eb6fc6a07f99fb Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:30:17 +0000 Subject: [PATCH 5/9] feat(gateway): launch the VM driver with serve and Configure The gateway starts openshell-driver-vm serve with only the socket, its own PID and the log level, checks GetLaunchInfo, and sends one Configure request built by a generic launcher: the VM table serialized unchanged as opaque TOML, the gateway context, the staged network trust artifact, telemetry and typed image overrides. The OTLP and driver flags it used to pass on argv are gone. config preflight now validates the VM table by running the driver's preflight with the same request on stdin, so validation stays with the driver that owns the table. The launcher only runs a driver binary from a trusted path and stops the gateway if a launched driver exits. Signed-off-by: Evan Lezar --- Cargo.lock | 2 + crates/openshell-driver-vm/README.md | 4 +- crates/openshell-gateway/Cargo.toml | 6 +- crates/openshell-gateway/src/launcher.rs | 1344 +++++++++++++ crates/openshell-gateway/src/lib.rs | 77 +- crates/openshell-gateway/src/vm.rs | 1735 ++--------------- .../tests/config_preflight.rs | 16 +- crates/openshell-server/src/compute/mod.rs | 27 + crates/openshell-server/src/lib.rs | 4 +- 9 files changed, 1617 insertions(+), 1598 deletions(-) create mode 100644 crates/openshell-gateway/src/launcher.rs diff --git a/Cargo.lock b/Cargo.lock index 76ae8e6d2e..c00181cdbc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4923,8 +4923,10 @@ dependencies = [ "openshell-crypto", "openshell-driver-docker", "openshell-driver-kubernetes", + "openshell-driver-launch", "openshell-driver-mxc", "openshell-driver-podman", + "openshell-driver-sdk", "openshell-otel", "openshell-policy", "openshell-server", diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index cb9433d08e..4e30d2db42 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 starts the driver as `openshell-driver-vm serve --bind-socket --expected-peer-pid --log-level ` and configures it with the `Configure` RPC from `crates/openshell-driver-launch`. The driver validates its own `[openshell.drivers.vm]` table in `Configure`. `openshell-driver-vm preflight < configure-request` validates an encoded request 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-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml index 86249568ba..afc00d0cd8 100644 --- a/crates/openshell-gateway/Cargo.toml +++ b/crates/openshell-gateway/Cargo.toml @@ -15,13 +15,17 @@ 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-driver-launch = { path = "../openshell-driver-launch" } 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 } @@ -81,5 +85,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..3ce9090908 --- /dev/null +++ b/crates/openshell-gateway/src/launcher.rs @@ -0,0 +1,1344 @@ +// 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, +//! starts the driver in `serve` mode, waits for its Unix domain socket, sends +//! `Configure`, 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 and binary; the driver owns and validates its +//! configuration, which the gateway passes through as an opaque table. + +#[cfg(unix)] +use hyper_util::rt::TokioIo; +use openshell_core::{Error, Result}; +use openshell_driver_launch::proto::ConfigureRequest; +#[cfg(unix)] +use openshell_driver_launch::proto::{ + GetLaunchInfoRequest, driver_launch_client::DriverLaunchClient, +}; +#[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::future::Future; +#[cfg(unix)] +use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; +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. + 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() + )) + }) +} + +/// How long the gateway waits for `Configure`, which builds the driver and +/// contacts its backend. +#[cfg(unix)] +pub const CONFIGURE_TIMEOUT: Duration = Duration::from_mins(2); + +/// Launch a driver in `serve` mode, negotiate the launch protocol, send +/// `Configure`, and return a managed endpoint once the driver is configured. +#[cfg(unix)] +pub async fn launch_configured( + driver: &DriverProcess<'_>, + log_level: &str, + shutdown: tokio::sync::watch::Receiver, + request: ConfigureRequest, +) -> 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 mut command = Command::new(&driver_bin); + command + .kill_on_drop(true) + .stdin(Stdio::null()) + .stdout(Stdio::inherit()) + .stderr(Stdio::inherit()) + .arg("serve") + .arg("--bind-socket") + .arg(&socket_path) + .arg("--expected-peer-pid") + .arg(std::process::id().to_string()) + .arg("--log-level") + .arg(log_level); + + let mut child = command.spawn().map_err(|e| { + Error::execution(format!( + "failed to launch {name} compute driver '{}': {e}", + driver_bin.display() + )) + })?; + let channel = wait_for_launch_service(name, &socket_path, &mut child).await?; + configure_driver(name, channel.clone(), &mut child, request).await?; + 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, + )) +} + +#[cfg(unix)] +async fn configure_driver( + name: &str, + channel: Channel, + child: &mut tokio::process::Child, + request: ConfigureRequest, +) -> Result<()> { + let mut client = DriverLaunchClient::with_interceptor(channel, TraceContextInterceptor); + tokio::select! { + result = tokio::time::timeout(CONFIGURE_TIMEOUT, client.configure(request)) => match result { + Ok(Ok(_)) => Ok(()), + Ok(Err(status)) => { + let message = format!( + "{name} compute driver failed to configure: {}", + status.message() + ); + Err(match status.code() { + tonic::Code::InvalidArgument | tonic::Code::FailedPrecondition => { + Error::config(message) + } + _ => Error::execution(message), + }) + } + Err(_) => Err(Error::execution(format!( + "{name} compute driver did not finish Configure within {}s", + CONFIGURE_TIMEOUT.as_secs() + ))), + }, + status = child.wait() => Err(Error::execution(format!( + "{name} compute driver exited during Configure with status {}", + status.map_or_else(|error| error.to_string(), |status| status.to_string()) + ))), + } +} + +/// What the gateway knows about itself and a driver when it builds the +/// driver's `Configure` request. +pub struct ConfigureContext<'a> { + pub driver_name: &'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 openshell_core::NetworkSupervisorTrustBundle>, + /// The operator's driver table, passed through unchanged. + pub driver_config: &'a toml::Table, + pub image_overrides: Option, +} + +/// The `Configure` request for a launched driver. The driver's table travels +/// as opaque TOML; the gateway adds only its own context. +/// +/// # Errors +/// +/// Returns an error when the table cannot be encoded or a path is not UTF-8. +pub fn configure_request(context: &ConfigureContext<'_>) -> Result { + use openshell_driver_launch::proto::{GatewayContext, NetworkTrust}; + + let driver_config_toml = toml::to_string(context.driver_config).map_err(|error| { + Error::config(format!( + "failed to encode [openshell.drivers.{}]: {error}", + context.driver_name + )) + })?; + let tls_ca_path = context + .tls_ca + .map(|path| { + path.to_str().map(str::to_string).ok_or_else(|| { + Error::config(format!( + "guest TLS CA path is not UTF-8: {}", + path.display() + )) + }) + }) + .transpose()? + .unwrap_or_default(); + let network_trust = context + .network_trust + .map(|bundle| -> Result { + Ok(NetworkTrust { + digest: bundle.digest().to_string(), + certificate_count: u32::try_from(bundle.certificate_count()) + .map_err(|_| Error::config("network trust bundle has too many certificates"))?, + artifact_path: bundle + .artifact_path() + .to_str() + .ok_or_else(|| Error::config("network trust artifact path is not UTF-8"))? + .to_string(), + }) + }) + .transpose()?; + Ok(ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + required_features: Vec::new(), + gateway: Some(GatewayContext { + gateway_port: u32::from(context.gateway_port), + tls_ca_path, + gateway_name: context.gateway_name.to_string(), + }), + network_trust, + driver_config_toml, + image_overrides: context.image_overrides.clone(), + telemetry: context.otlp_config.map(telemetry), + }) +} + +/// The gateway's OTLP settings for the driver's own export and its supervisors. +fn telemetry(otlp: &OtlpConfig) -> openshell_driver_launch::proto::Telemetry { + use openshell_driver_launch::proto::{CollectorTls, OtlpExport, Telemetry}; + + let exports = otlp.supervisor_otlp(); + let export = |export: Option| { + export.map(|export| OtlpExport { + endpoint: export.endpoint, + protocol: export.protocol.as_str().to_string(), + }) + }; + let path = |path: Option<&Path>| { + path.map(|path| path.to_string_lossy().into_owned()) + .unwrap_or_default() + }; + Telemetry { + traces: export(exports.traces), + ocsf: export(exports.ocsf), + agent: export(exports.agent), + collector: otlp.traces.as_ref().map(|traces| CollectorTls { + ca_file: path(traces.collector.ca_file()), + cert_file: path(traces.collector.cert_file()), + key_file: path(traces.collector.key_file()), + }), + trace_headers: openshell_server::gateway_trace_headers(Some(otlp)) + .map(|headers| headers.expose_secret().to_string()) + .unwrap_or_default(), + } +} + +/// Run ` `, writing `input` to its stdin when given, 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_with_input( + binary: &Path, + args: &[&std::ffi::OsStr], + input: Option>, + timeout: Duration, + max_output: usize, +) -> std::result::Result, String> { + use std::io::{Read as _, Write as _}; + + let mut child = std::process::Command::new(binary) + .args(args) + .stdin(if input.is_some() { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|error| format!("failed to run '{}': {error}", binary.display()))?; + // Write from a thread so a driver that does not read its input cannot + // block the gateway; the pipe closes when the thread finishes. + if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) { + std::thread::spawn(move || { + let _ = stdin.write_all(&input); + }); + } + // 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) +} + +/// Have a driver launched in `serve` mode validate the `Configure` request it +/// would receive, without starting it. The request goes to `preflight` on +/// stdin, so no file is written. +/// +/// # 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_configured( + driver: &DriverProcess<'_>, + timeout: Duration, + request: &ConfigureRequest, +) -> Result<()> { + use openshell_driver_sdk::preflight::{MAX_PREFLIGHT_OUTPUT_BYTES, PreflightResult}; + + let name = driver.name; + let binary = trusted_driver_bin(driver)?; + let output = run_bounded_with_input( + &binary, + &["preflight".as_ref()], + Some(openshell_driver_launch::encode_configure_request(request)), + 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") + }))) + } +} + +/// 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) +} + +/// How long `preflight` may take before the driver counts as failed. +#[cfg(unix)] +pub const PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(10); + +#[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(()) +} + +#[cfg(not(unix))] +pub async fn launch_configured( + _driver: &DriverProcess<'_>, + _log_level: &str, + _shutdown: tokio::sync::watch::Receiver, + _request: ConfigureRequest, +) -> 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; + +/// Wait for a driver launched in `serve` mode to answer `GetLaunchInfo`, and +/// check that it speaks this gateway's launch protocol version. +#[cfg(unix)] +#[tracing::instrument( + name = "driver.wait_for_launch_service", + skip_all, + fields( + otel.name = "driver.wait_for_launch_service", + otel.status_code = tracing::field::Empty, + driver.name = %name, + ) +)] +async fn wait_for_launch_service( + name: &str, + socket_path: &Path, + child: &mut tokio::process::Child, +) -> Result { + let (channel, versions) = wait_for_socket(name, socket_path, child, |channel| async move { + let mut client = DriverLaunchClient::with_interceptor(channel, TraceContextInterceptor); + client + .get_launch_info(tonic::Request::new(GetLaunchInfoRequest {})) + .await + .map(|info| info.into_inner().protocol_versions) + .map_err(|status| status.to_string()) + }) + .await?; + if !versions.contains(&openshell_driver_launch::PROTOCOL_VERSION) { + return Err(Error::config(format!( + "{name} compute driver supports launch protocol versions {versions:?}, but this gateway needs {}", + openshell_driver_launch::PROTOCOL_VERSION + ))); + } + Ok(channel) +} + +/// Poll until the driver's socket accepts a connection and `ready` succeeds on +/// it, failing early if the driver exits. +#[cfg(unix)] +async fn wait_for_socket( + name: &str, + socket_path: &Path, + child: &mut tokio::process::Child, + mut ready: F, +) -> Result<(Channel, T)> +where + F: FnMut(Channel) -> Fut, + Fut: Future>, +{ + 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) => match ready(channel.clone()).await { + Ok(value) => return Ok((channel, value)), + Err(error) => last_error = Some(error), + }, + 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::{ + ConfigureContext, DriverProcess, check_driver_binary_trust, configure_request, + current_euid, prepare_socket_path, prepare_state_dir, resolve_driver_bin, + resolve_driver_search_dirs, socket_path, watch_for_exit, + }; + 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 configure_carries_trace_headers_and_the_driver_table() { + 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 table: toml::Table = toml::from_str("vcpus = 4\n").unwrap(); + let request = configure_request(&ConfigureContext { + driver_name: "test", + gateway_name: "g", + gateway_port: 8080, + tls_ca: None, + otlp_config: Some(&otlp), + network_trust: None, + driver_config: &table, + image_overrides: None, + }) + .unwrap(); + assert_eq!( + request.protocol_version, + openshell_driver_launch::PROTOCOL_VERSION + ); + assert_eq!( + toml::from_str::(&request.driver_config_toml).unwrap(), + table + ); + assert_eq!( + request.telemetry.unwrap().trace_headers, + "authorization=Bearer%20secret-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_with_input(&binary, &[], None, 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_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 request = openshell_driver_launch::proto::ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + ..Default::default() + }; + let result = super::preflight_configured(&driver, timeout, &request); + assert!(!state.exists(), "preflight must not create driver state"); + result + } + + #[test] + fn preflight_reports_the_drivers_verdict() { + run_preflight("echo '{\"ok\":true}'", 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_configured_preflight_receives_the_request_on_stdin() { + let dir = tempdir().unwrap(); + // The script checks it was run as `preflight` with no arguments and + // got the encoded request on stdin. + probe_script( + dir.path(), + "test \"$1\" = preflight && test $# -eq 1 && test \"$(wc -c)\" -gt 0 && echo '{\"ok\":true}'", + ); + 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 request = openshell_driver_launch::proto::ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + driver_config_toml: "network_name = \"n\"".to_string(), + ..Default::default() + }; + super::preflight_configured(&driver, Duration::from_secs(10), &request).unwrap(); + assert!(!state.exists(), "preflight must not create driver state"); + } + + #[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..95ad7298c5 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -16,6 +16,12 @@ compile_error!( build a telemetry-free gateway with `--no-default-features --features defaults-without-telemetry`" ); +#[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-vm"))] mod vm; @@ -544,6 +550,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 +576,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 +602,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/vm.rs b/crates/openshell-gateway/src/vm.rs index 1f64a329a2..18d1985aad 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -1,135 +1,35 @@ // 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. - -#[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; +//! 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 in +//! `Configure`. + +use crate::launcher::{self, DriverProcess}; +use openshell_core::{Error, NetworkSupervisorTrustBundle, Result}; +use openshell_driver_launch::proto::ConfigureRequest; 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. + pub state_dir: Option, } -impl VmComputeConfig { +impl VmLaunchSettings { /// Default working directory for VM driver state. #[must_use] pub fn default_state_dir() -> PathBuf { @@ -139,1465 +39,204 @@ 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", - )); - } - } - Ok(()) - } - - #[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 - } -} - -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, - } - } -} - -#[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() - ))); + settings.state_dir = Some(Self::default_state_dir()); + } + Ok(settings) + } + + fn state_dir(&self) -> PathBuf { + self.state_dir + .clone() + .unwrap_or_else(Self::default_state_dir) + } +} + +/// 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, +} + +/// 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 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], + let request = configure_request(&launch)?; + launcher::launch_configured( + &process, + launch.gateway_log_level, + launch.shutdown.clone(), + request, ) + .await } -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() - ))); - } - }; - 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() - )) - }) -} - -#[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 `Configure` request the gateway would send. +/// 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() - )) + 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, + }; + let request = configure_request(&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, })?; - 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); - } -} - -#[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", - )) -} - -#[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( - 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() - )) - }) + launcher::preflight_configured(&process, launcher::PREFLIGHT_TIMEOUT, &request) +} + +/// The VM driver's table: 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 +} + +/// The `Configure` request for the VM driver. +fn configure_request(launch: &VmLaunch<'_>) -> Result { + let driver_config = vm_driver_config_table(launch.driver_config.clone()); + launcher::configure_request(&launcher::ConfigureContext { + driver_name: "vm", + gateway_name: launch.gateway_name, + gateway_port: launch.gateway_port, + tls_ca: launch.tls_ca, + otlp_config: launch.otlp_config, + network_trust: launch.network_trust, + driver_config: &driver_config, + image_overrides: None, + }) } #[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 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 tempfile::tempdir; - - #[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 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")) - ); - }); - } - - #[test] - fn vm_driver_receives_the_trace_collectors_tls_file_paths() { - 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| { - let path = dir.path().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 - }); - 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", - ); + use super::{VmLaunch, VmLaunchSettings, configure_request, vm_driver_config_table}; + use openshell_core::NetworkSupervisorTrustBundle; + use std::path::{Path, PathBuf}; - 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" - ] - ); + const VM_DRIVER_CONFIG_FIXTURE: &str = + include_str!("../../openshell-driver-vm/tests/fixtures/driver-config-vm.toml"); - 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, - }), - "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", - ] - ); + fn fixture_driver_config() -> toml::Table { + toml::from_str(VM_DRIVER_CONFIG_FIXTURE).unwrap() } + /// The gateway passes the operator's table through unchanged, apart from + /// the launcher-owned `driver_dir`, and adds its own context. #[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, - }), - "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, - ), - }), - }), - "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, + fn configure_passes_the_operator_table_through_without_the_driver_dir() { + 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", - ] - ); - 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() - }, - ..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 - "#, - ) - .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", - ] - ); - } - - #[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_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::>(); + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), + ); + let expected = fixture_driver_config(); + let mut operator_table = expected.clone(); + operator_table.insert("driver_dir".into(), "/usr/libexec/openshell".into()); + let settings = VmLaunchSettings::from_table(&operator_table).unwrap(); + + let request = configure_request(&VmLaunch { + gateway_log_level: "debug", + gateway_name: "gateway-a", + gateway_port: 8080, + tls_ca: Some(Path::new("/etc/openshell/tls/ca.pem")), + otlp_config: None, + network_trust: Some(&trust), + shutdown: tokio::sync::watch::channel(false).1, + settings: &settings, + driver_config: operator_table, + }) + .unwrap(); + + let table: toml::Table = toml::from_str(&request.driver_config_toml).unwrap(); + assert_eq!(table, expected); + let gateway = request.gateway.unwrap(); + assert_eq!(gateway.gateway_port, 8080); + assert_eq!(gateway.gateway_name, "gateway-a"); + assert_eq!(gateway.tls_ca_path, "/etc/openshell/tls/ca.pem"); + assert!(request.image_overrides.is_none()); + let network_trust = request.network_trust.unwrap(); + assert_eq!(network_trust.certificate_count, 3); 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", - ] + network_trust.artifact_path, + "/var/lib/openshell/trust/bundle.pem" ); - assert!(!args.iter().any(|arg| arg.contains("user:password"))); - } - - #[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); + 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 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. From 80d624bd63f80332615839eba9104904ae9ff463 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:32:35 +0000 Subject: [PATCH 6/9] feat(podman): serve the launch protocol and add probe and preflight openshell-driver-podman serve binds the socket with only --bind-socket, --expected-peer-pid and --log-level, installs console tracing at once, and builds the driver inside Configure from the operator's [openshell.drivers.podman] table, the gateway context, telemetry, the staged network trust artifact and typed image overrides. Until then ComputeDriver returns UNAVAILABLE; a rejected Configure leaves the driver running so the gateway can retry. probe reports whether a Podman socket is reachable, for gateway auto-detection, and preflight validates a Configure request read from stdin without starting the driver. The standalone flag mode and the in-process library are unchanged. Signed-off-by: Evan Lezar --- Cargo.lock | 4 + crates/openshell-driver-podman/Cargo.toml | 4 + crates/openshell-driver-podman/src/lib.rs | 1 + crates/openshell-driver-podman/src/main.rs | 218 ++++++++++++++---- .../src/startup_config.rs | 180 +++++++++++++++ .../tests/fixtures/driver-config-podman.toml | 12 + .../tests/serve_configure.rs | 145 ++++++++++++ 7 files changed, 515 insertions(+), 49 deletions(-) create mode 100644 crates/openshell-driver-podman/src/startup_config.rs create mode 100644 crates/openshell-driver-podman/tests/fixtures/driver-config-podman.toml create mode 100644 crates/openshell-driver-podman/tests/serve_configure.rs diff --git a/Cargo.lock b/Cargo.lock index c00181cdbc..87574ef4de 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4770,6 +4770,8 @@ dependencies = [ "nix 0.29.0", "openshell-core", "openshell-crypto", + "openshell-driver-launch", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -4788,7 +4790,9 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "toml", "tonic", + "tower", "tower-http 0.6.8", "tracing", "tracing-opentelemetry", diff --git a/crates/openshell-driver-podman/Cargo.toml b/crates/openshell-driver-podman/Cargo.toml index 3fb3c51b5d..25529dfc6f 100644 --- a/crates/openshell-driver-podman/Cargo.toml +++ b/crates/openshell-driver-podman/Cargo.toml @@ -17,6 +17,8 @@ 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" } +openshell-driver-launch = { path = "../openshell-driver-launch" } openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } tar = "0.4" @@ -32,6 +34,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 } @@ -55,6 +58,7 @@ opentelemetry_sdk = { workspace = true, features = ["testing"] } prost-types = { workspace = true } rcgen = { workspace = true } temp-env = "0.3" +tower = { workspace = true, features = ["util"] } tokio = { workspace = true, features = ["test-util"] } [lints] 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..61502d2007 100644 --- a/crates/openshell-driver-podman/src/main.rs +++ b/crates/openshell-driver-podman/src/main.rs @@ -13,6 +13,7 @@ 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_configure; use openshell_driver_podman::{ComputeDriverService, PodmanComputeConfig, PodmanComputeDriver}; #[derive(Parser)] @@ -203,8 +204,123 @@ struct Args { enable_bind_mounts: bool, } +/// `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` reads the `Configure` request the gateway would send from +/// stdin, validates it, and reports on stdout. It starts nothing. +fn run_preflight(arguments: &[std::ffi::OsString]) -> ! { + use openshell_driver_sdk::preflight::PreflightResult; + use std::io::Read as _; + + let result = if arguments.is_empty() { + let mut input = Vec::new(); + std::io::stdin() + .take(openshell_driver_launch::MAX_CONFIGURE_REQUEST_BYTES as u64 + 1) + .read_to_end(&mut input) + .map_err(|error| format!("failed to read the configure request: {error}")) + .and_then(|_| openshell_driver_launch::decode_configure_request(&input)) + .and_then(|request| config_from_configure(&request)) + .map_or_else(PreflightResult::rejected, |_| PreflightResult::ok()) + } else { + PreflightResult::rejected("usage: preflight < configure-request") + }; + println!("{}", result.to_json()); + std::process::exit(0); +} + +/// Bootstrap flags of `serve`, the mode a gateway launches the driver in. +/// Everything else, telemetry included, arrives in the `Configure` RPC. +#[derive(Parser)] +#[command(name = "openshell-driver-podman serve")] +struct ServeArgs { + /// Unix socket the gateway connects to. + #[arg(long)] + bind_socket: PathBuf, + + /// The launching gateway's PID. Podman authorizes same-UID peers for now. + #[arg(long)] + expected_peer_pid: Option, + + #[arg(long, default_value = "info")] + log_level: String, +} + +/// Serve `DriverLaunch` at once and build the Podman driver when the gateway +/// calls `Configure`. +async fn run_serve(arguments: &[std::ffi::OsString]) -> Result<()> { + let args = ServeArgs::parse_from( + std::iter::once(std::ffi::OsString::from("openshell-driver-podman serve")) + .chain(arguments.iter().cloned()), + ); + // A gateway that is killed must not leave this driver running. + if let Err(error) = openshell_driver_sdk::parent::die_with_parent() { + eprintln!("warning: {error}; a gateway crash may orphan this driver"); + } + let ansi = openshell_core::color::stdout_ansi(); + let tracing = std::sync::Arc::new(openshell_otel::install_deferred_driver_tracing( + openshell_driver_podman::otel_tracing::TRACING, + &args.log_level, + ansi, + )); + + let log_level = args.log_level.clone(); + let (launch, compute) = openshell_driver_launch::services("podman", VERSION, move |request| { + openshell_driver_sdk::launch::enable_export(&tracing, &request, &log_level, ansi, VERSION); + async move { + let (config, network_trust) = + config_from_configure(&request).map_err(tonic::Status::invalid_argument)?; + let driver = PodmanComputeDriver::new(config, network_trust) + .await + .map_err(|error| tonic::Status::unavailable(error.to_string()))?; + info!("Podman compute driver configured"); + Ok(ComputeDriverServer::new(ComputeDriverService::new(driver))) + } + }); + + let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) + .map_err(|err| miette::miette!("{err}"))?; + let _cleanup = + openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); + info!(socket = %args.bind_socket.display(), "Starting Podman compute driver; waiting for Configure"); + tonic::transport::Server::builder() + .layer(openshell_otel::compute_driver_rpc_layer()) + .add_service(launch) + .add_service(compute) + .serve_with_incoming_shutdown( + openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), + shutdown_signal(), + ) + .await + .into_diagnostic() +} + #[tokio::main] async fn main() -> Result<()> { + let arguments: Vec<_> = std::env::args_os().skip(1).collect(); + if arguments.first().is_some_and(|arg| arg == "serve") { + return run_serve(&arguments[1..]).await; + } + 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 = Args::parse(); let _tracing = openshell_otel::install_driver_tracing( openshell_driver_podman::otel_tracing::TRACING, @@ -222,55 +338,59 @@ 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) = { + let supervisor_otlp = args.otlp.supervisor_otlp(); + // A standalone driver has 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..e201023045 --- /dev/null +++ b/crates/openshell-driver-podman/src/startup_config.rs @@ -0,0 +1,180 @@ +// 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's `Configure` +//! request. +//! +//! The request's `driver_config_toml` 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 builds the driver. + +use openshell_core::NetworkSupervisorTrustBundle; + +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 the gateway's `Configure` request. +/// +/// `driver_config_toml` is the operator's table, opaque to the gateway. The +/// gateway resolves the image overrides; the driver applies them and its own +/// `OPENSHELL_PODMAN_SOCKET` override over the table. +/// +/// # 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_configure( + request: &openshell_driver_launch::proto::ConfigureRequest, +) -> Result<(PodmanComputeConfig, Option), String> { + config_from_configure_with(request, |name| std::env::var(name).ok()) +} + +fn config_from_configure_with( + request: &openshell_driver_launch::proto::ConfigureRequest, + environment: impl Fn(&str) -> Option, +) -> Result<(PodmanComputeConfig, Option), String> { + let mut config: PodmanComputeConfig = toml::from_str(&request.driver_config_toml) + .map_err(|error: toml::de::Error| format!("invalid driver_config: {error}"))?; + let gateway = request.gateway.clone().unwrap_or_default(); + config.gateway_port = u16::try_from(gateway.gateway_port) + .map_err(|_| format!("gateway port {} is out of range", gateway.gateway_port))?; + config.supervisor_otlp = + openshell_driver_sdk::launch::supervisor_otlp(request.telemetry.as_ref())?; + config.supervisor_gateway_name = + (!gateway.gateway_name.is_empty()).then(|| gateway.gateway_name.clone()); + if config.guest_tls_ca.is_none() && !gateway.tls_ca_path.is_empty() { + config.guest_tls_ca = Some(gateway.tls_ca_path.into()); + } + if let Some(overrides) = &request.image_overrides { + if let Some(image) = &overrides.sandbox_runtime_image { + config.sandbox_runtime_image.clone_from(image); + } + if let Some(image) = &overrides.supervisor_image { + config.supervisor_image.clone_from(image); + } + } + if let Some(path) = environment(PODMAN_SOCKET_ENV) { + config.socket_path = Some(path.into()); + } + config + .validate_configuration() + .map_err(|error| error.to_string())?; + + let trust = request + .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( + std::path::Path::new(&trust.artifact_path), + &trust.digest, + count, + ) + }) + .transpose()?; + Ok((config, trust)) +} + +#[cfg(test)] +mod tests { + use super::*; + use openshell_driver_launch::proto::{ConfigureRequest, GatewayContext, OtlpExport, Telemetry}; + + const FIXTURE: &str = include_str!("../tests/fixtures/driver-config-podman.toml"); + + fn configure_request() -> ConfigureRequest { + ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(GatewayContext { + gateway_port: 8080, + tls_ca_path: String::new(), + gateway_name: "gateway-a".to_string(), + }), + driver_config_toml: FIXTURE.to_string(), + telemetry: Some(Telemetry { + traces: Some(OtlpExport { + endpoint: "https://collector.example:4317".to_string(), + protocol: "grpc".to_string(), + }), + ..Telemetry::default() + }), + ..ConfigureRequest::default() + } + } + + #[test] + fn the_fixture_builds_a_validated_configuration() { + let (config, trust) = config_from_configure_with(&configure_request(), |_| None).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 request = configure_request(); + request.gateway.as_mut().unwrap().tls_ca_path = ca.to_str().unwrap().to_string(); + let (config, _) = config_from_configure_with(&request, |_| None).unwrap(); + assert_eq!(config.guest_tls_ca.as_deref(), Some(ca.as_path())); + } + + #[test] + fn configure_applies_gateway_image_overrides_and_the_socket_environment() { + let mut request = configure_request(); + request.image_overrides = Some(openshell_driver_launch::proto::ImageOverrides { + sandbox_runtime_image: Some("runtime:gateway".into()), + supervisor_image: Some("supervisor:gateway".into()), + }); + let (config, _) = config_from_configure_with(&request, |name| { + (name == PODMAN_SOCKET_ENV).then(|| "/run/podman.sock".to_string()) + }) + .unwrap(); + assert_eq!(config.sandbox_runtime_image, "runtime:gateway"); + assert_eq!(config.supervisor_image, "supervisor:gateway"); + assert_eq!( + config.socket_path.as_deref(), + Some(std::path::Path::new("/run/podman.sock")) + ); + } + + #[test] + fn configure_rejects_unknown_driver_config_keys() { + let mut request = configure_request(); + request.driver_config_toml = "surprise = 1".to_string(); + let error = config_from_configure_with(&request, |_| None).unwrap_err(); + assert!(error.contains("surprise"), "{error}"); + } + + #[test] + fn an_unknown_export_protocol_is_rejected() { + let mut request = configure_request(); + request + .telemetry + .as_mut() + .unwrap() + .traces + .as_mut() + .unwrap() + .protocol = "carrier-pigeon".to_string(); + assert!(config_from_configure_with(&request, |_| None).is_err()); + } +} diff --git a/crates/openshell-driver-podman/tests/fixtures/driver-config-podman.toml b/crates/openshell-driver-podman/tests/fixtures/driver-config-podman.toml new file mode 100644 index 0000000000..c83f52c628 --- /dev/null +++ b/crates/openshell-driver-podman/tests/fixtures/driver-config-podman.toml @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# An operator's [openshell.drivers.podman] table, as the gateway passes it +# unchanged in Configure. The gateway's request test and the driver's +# configuration tests both read this file. + +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-podman/tests/serve_configure.rs b/crates/openshell-driver-podman/tests/serve_configure.rs new file mode 100644 index 0000000000..807bdba725 --- /dev/null +++ b/crates/openshell-driver-podman/tests/serve_configure.rs @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The `serve` mode a gateway launches the Podman driver in: the launch +//! service answers at once, compute RPCs wait for `Configure`, and a failed +//! `Configure` leaves the driver running so the gateway can retry. + +#![cfg(unix)] + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use hyper_util::rt::TokioIo; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; +use openshell_driver_launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_launch::proto::{ConfigureRequest, GatewayContext, GetLaunchInfoRequest}; +use tokio::net::UnixStream; +use tonic::transport::{Channel, Endpoint}; + +const FIXTURE: &str = include_str!("fixtures/driver-config-podman.toml"); + +async fn connect(socket: &Path) -> Channel { + for _ in 0..100 { + let path: PathBuf = socket.to_path_buf(); + let connected = Endpoint::from_static("http://[::]:50051") + .connect_with_connector(tower::service_fn(move |_: tonic::transport::Uri| { + let path = path.clone(); + async move { UnixStream::connect(path).await.map(TokioIo::new) } + })) + .await; + if let Ok(channel) = connected { + return channel; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + panic!("driver socket {} never came up", socket.display()); +} + +#[tokio::test] +async fn serve_waits_for_configure_and_survives_a_failed_one() { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("run").join("compute-driver.sock"); + let mut child = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell-driver-podman")) + .arg("serve") + .arg("--bind-socket") + .arg(&socket) + .env("OPENSHELL_PODMAN_SOCKET", dir.path().join("missing.sock")) + .kill_on_drop(true) + .spawn() + .unwrap(); + let channel = connect(&socket).await; + + let mut launch = DriverLaunchClient::new(channel.clone()); + let info = launch + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!( + info.protocol_versions, + vec![openshell_driver_launch::PROTOCOL_VERSION] + ); + assert_eq!(info.driver_name, "podman"); + + let mut compute = ComputeDriverClient::new(channel.clone()); + let status = compute + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable, "{status:?}"); + + let invalid = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + driver_config_toml: "surprise = 1".to_string(), + ..ConfigureRequest::default() + }; + let status = launch.configure(invalid).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument, "{status:?}"); + + let request = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(GatewayContext { + gateway_port: 8080, + tls_ca_path: String::new(), + gateway_name: "gateway-a".to_string(), + }), + driver_config_toml: FIXTURE.to_string(), + ..ConfigureRequest::default() + }; + // No Podman API behind the socket: building the driver fails, and the + // driver stays up for another attempt. + let status = launch.configure(request.clone()).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable, "{status:?}"); + assert!(child.try_wait().unwrap().is_none()); + let status = launch.configure(request).await.unwrap_err(); + assert_eq!(status.code(), tonic::Code::Unavailable, "{status:?}"); + + child.kill().await.unwrap(); +} + +fn preflight(input: &[u8]) -> serde_json::Value { + use std::io::Write as _; + + let mut child = std::process::Command::new(env!("CARGO_BIN_EXE_openshell-driver-podman")) + .arg("preflight") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + child.stdin.take().unwrap().write_all(input).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!(output.status.success()); + serde_json::from_slice(&output.stdout).unwrap() +} + +#[test] +fn preflight_validates_the_configure_request_from_stdin() { + let valid = ConfigureRequest { + protocol_version: openshell_driver_launch::PROTOCOL_VERSION, + gateway: Some(GatewayContext { + gateway_port: 8080, + tls_ca_path: String::new(), + gateway_name: "gateway-a".to_string(), + }), + driver_config_toml: FIXTURE.to_string(), + ..ConfigureRequest::default() + }; + let result = preflight(&openshell_driver_launch::encode_configure_request(&valid)); + assert_eq!(result["ok"], true, "{result}"); + + let invalid = ConfigureRequest { + driver_config_toml: "surprise = 1".to_string(), + ..valid + }; + let result = preflight(&openshell_driver_launch::encode_configure_request(&invalid)); + assert_eq!(result["ok"], false); + assert!( + result["error"].as_str().unwrap().contains("surprise"), + "{result}" + ); + + let result = preflight(b"not a request"); + assert_eq!(result["ok"], false, "{result}"); +} From 492e164f90922fd51da32bbb04d7ee53b07bbd4f Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:34:22 +0000 Subject: [PATCH 7/9] feat(gateway): launch the Podman driver as a subprocess The gateway no longer links openshell-driver-podman. It starts openshell-driver-podman serve and configures it through the same launcher as the VM driver, sending the Podman table unchanged as opaque TOML with typed image overrides, the gateway context, telemetry and the staged network trust artifact. Auto-detection runs the driver's probe, keeping the existing order and treating a missing, untrusted, failing or slow binary as unavailable. config preflight validates the Podman table with the driver's preflight. Signed-off-by: Evan Lezar --- Cargo.lock | 1 - crates/openshell-driver-podman/README.md | 24 +++ crates/openshell-gateway/Cargo.toml | 3 +- crates/openshell-gateway/src/launcher.rs | 107 ++++++++++++- crates/openshell-gateway/src/lib.rs | 79 ++++----- crates/openshell-gateway/src/podman.rs | 194 +++++++++++++++++++++++ tasks/scripts/gateway-podman.sh | 4 +- 7 files changed, 353 insertions(+), 59 deletions(-) create mode 100644 crates/openshell-gateway/src/podman.rs diff --git a/Cargo.lock b/Cargo.lock index 87574ef4de..691052ec99 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4929,7 +4929,6 @@ dependencies = [ "openshell-driver-kubernetes", "openshell-driver-launch", "openshell-driver-mxc", - "openshell-driver-podman", "openshell-driver-sdk", "openshell-otel", "openshell-policy", diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index 87a617069e..88d63d16c6 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -164,3 +164,27 @@ 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 serve --bind-socket --expected-peer-pid + --log-level `. The driver logs to stderr and serves the +`DriverLaunch` service at once; `ComputeDriver` RPCs return `UNAVAILABLE` +until the gateway calls `Configure`. That request carries the gateway's +resolved values (name, port, TLS CA, telemetry, the staged network trust +artifact, image overrides) and the operator's `[openshell.drivers.podman]` +table, which the driver deserializes and validates before it builds the +driver. A failed `Configure` can be retried. The driver 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` reads the encoded `Configure` request on + stdin, validates it, 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-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml index afc00d0cd8..21ff2fc4ff 100644 --- a/crates/openshell-gateway/Cargo.toml +++ b/crates/openshell-gateway/Cargo.toml @@ -30,7 +30,6 @@ 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 } @@ -55,7 +54,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", diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs index 3ce9090908..2a9526e42e 100644 --- a/crates/openshell-gateway/src/launcher.rs +++ b/crates/openshell-gateway/src/launcher.rs @@ -489,13 +489,28 @@ fn telemetry(otlp: &OtlpConfig) -> openshell_driver_launch::proto::Telemetry { } } -/// Run ` `, writing `input` to its stdin when given, and return -/// its standard output. +/// 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> { + run_bounded_with_input(binary, args, None, timeout, max_output) +} + +/// [`run_bounded`], writing `input` to the command's stdin when given. +#[cfg(unix)] fn run_bounded_with_input( binary: &Path, args: &[&std::ffi::OsStr], @@ -612,6 +627,36 @@ fn trusted_driver_bin(driver: &DriverProcess<'_>) -> Result { 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); @@ -1259,9 +1304,7 @@ mod tests { 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_with_input(&binary, &[], None, Duration::from_secs(5), 4096) - .unwrap(); + let output = super::run_bounded(&binary, &[], Duration::from_secs(5), 4096).unwrap(); assert_eq!(output.len(), 4097); } @@ -1271,6 +1314,60 @@ mod tests { 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); diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 95ad7298c5..bc8e05d019 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -22,6 +22,9 @@ compile_error!( ))] 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; @@ -200,17 +203,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", @@ -485,60 +482,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; diff --git a/crates/openshell-gateway/src/podman.rs b/crates/openshell-gateway/src/podman.rs new file mode 100644 index 0000000000..9e77b66592 --- /dev/null +++ b/crates/openshell-gateway/src/podman.rs @@ -0,0 +1,194 @@ +// 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 starts the driver in `serve` mode and passes the operator's +//! `[openshell.drivers.podman]` table through unchanged in `Configure`, which +//! `preflight` also validates. The Podman driver deserializes and validates it. + +use crate::launcher::{self, DriverProcess}; +use openshell_core::{NetworkSupervisorTrustBundle, Result}; +use openshell_driver_launch::proto::{ConfigureRequest, ImageOverrides}; +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. +#[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 `Configure` request the gateway would +/// send it. Values the gateway only knows once it serves, such as its TLS CA, +/// telemetry, 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, + }; + let request = configure_request( + &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, + }, + |name| std::env::var(name).ok(), + )?; + launcher::preflight_configured(&process, launcher::PREFLIGHT_TIMEOUT, &request) +} + +/// 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 request = configure_request(&launch, |name| std::env::var(name).ok())?; + launcher::launch_configured( + &process, + launch.gateway_log_level, + launch.shutdown.clone(), + request, + ) + .await +} + +/// The `Configure` request for the Podman driver. The operator's table travels +/// unchanged; the gateway adds its own context and resolved image overrides. +fn configure_request( + launch: &PodmanLaunch<'_>, + environment: impl Fn(&str) -> Option, +) -> Result { + launcher::configure_request(&launcher::ConfigureContext { + driver_name: "podman", + gateway_name: launch.gateway_name, + gateway_port: launch.gateway_port, + tls_ca: launch.tls_ca, + otlp_config: launch.otlp_config, + network_trust: launch.network_trust, + driver_config: &launch.driver_config, + image_overrides: Some(ImageOverrides { + sandbox_runtime_image: environment(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV), + supervisor_image: environment(openshell_core::config::SUPERVISOR_IMAGE_ENV), + }), + }) +} + +#[cfg(all(test, unix))] +mod tests { + use super::{PodmanLaunch, configure_request}; + use openshell_core::NetworkSupervisorTrustBundle; + use std::path::{Path, PathBuf}; + + const FIXTURE: &str = + include_str!("../../openshell-driver-podman/tests/fixtures/driver-config-podman.toml"); + + #[test] + fn configure_passes_the_driver_table_through_and_resolves_image_overrides() { + let driver_config: toml::Table = toml::from_str(FIXTURE).unwrap(); + let trust = NetworkSupervisorTrustBundle::new( + b"pem".to_vec(), + 3, + "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + PathBuf::from("/var/lib/openshell/trust/bundle.pem"), + ); + let request = configure_request( + &PodmanLaunch { + gateway_log_level: "debug", + gateway_name: "gateway-a", + gateway_port: 8080, + tls_ca: Some(Path::new("/etc/openshell/tls/ca.pem")), + otlp_config: None, + network_trust: Some(&trust), + shutdown: tokio::sync::watch::channel(false).1, + driver_config: driver_config.clone(), + }, + |name| { + (name == openshell_core::config::SUPERVISOR_IMAGE_ENV) + .then(|| "supervisor:env".to_string()) + }, + ) + .unwrap(); + + let table: toml::Table = toml::from_str(&request.driver_config_toml).unwrap(); + assert_eq!(table, driver_config); + let gateway = request.gateway.unwrap(); + assert_eq!(gateway.gateway_port, 8080); + assert_eq!(gateway.gateway_name, "gateway-a"); + assert!(request.telemetry.is_none()); + assert_eq!(gateway.tls_ca_path, "/etc/openshell/tls/ca.pem"); + let overrides = request.image_overrides.unwrap(); + assert_eq!( + overrides.supervisor_image.as_deref(), + Some("supervisor:env") + ); + assert!(overrides.sandbox_runtime_image.is_none()); + let network_trust = request.network_trust.unwrap(); + assert_eq!(network_trust.certificate_count, 3); + assert_eq!( + network_trust.artifact_path, + "/var/lib/openshell/trust/bundle.pem" + ); + } +} 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 From 39f02d49a6db7099e9d144a63cb09c74b20ae636 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:34:32 +0000 Subject: [PATCH 8/9] docs(gateway): describe how the gateway launches the VM and Podman drivers Document where the gateway finds driver binaries and which it refuses, the serve bootstrap and Configure call, the opaque driver tables, fail-fast on a driver exit, Podman probe detection, and preflight. Signed-off-by: Evan Lezar --- docs/extensibility/drivers.mdx | 4 +++ docs/how-it-works/gateways/configuration.mdx | 26 +++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) 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 4d79a1418d..2b35dd1ffb 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,24 @@ 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. + +For the VM and Podman drivers, the gateway starts the driver as `openshell-driver- serve` in a private `run/` directory under the driver's state directory, passing only its socket path, the gateway's process ID, and the log level. It then sends the rest in a `Configure` call on the driver's socket: the gateway's resolved values, telemetry settings including OTLP headers, the staged network trust artifact, and the driver's `[openshell.drivers.]` table, which the gateway does not interpret. The gateway removes only the VM driver's `driver_dir` key, which the gateway itself uses. The driver validates the table and sets up its backend while it handles the call. When it fails, the gateway reports the driver's error and stops. 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 +2130,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 +2209,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 From f1fbdc6aebbfa8627081007d52d2f0490124a478 Mon Sep 17 00:00:00 2001 From: Evan Lezar Date: Mon, 23 Nov 2026 11:34:39 +0000 Subject: [PATCH 9/9] build(packaging): ship the Podman driver binary The gateway now launches openshell-driver-podman instead of linking it, so build the binary for Linux and install it next to the VM driver in /usr/libexec/openshell in the Debian and RPM packages and the test machine artifacts. Signed-off-by: Evan Lezar --- .github/workflows/build-binaries-linux.yml | 16 ++++++++++++++++ .github/workflows/build-rpm.yml | 8 +++++++- .github/workflows/deb-package.yml | 9 ++++++++- nix/test-guest/README.md | 1 + openshell.spec | 10 ++++++++++ tasks/scripts/package-deb-install.sh | 6 ++++-- tasks/scripts/package-deb.sh | 3 +++ tasks/scripts/test-packaging-assets.sh | 11 ++++++++++- tests/tmachine/artifacts.nix | 8 ++++++++ 9 files changed, 67 insertions(+), 5 deletions(-) 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-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/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/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/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 \