From ce38bf7a1be4677e64fae274b0704c6c6ce460fa Mon Sep 17 00:00:00 2001 From: mr-miles Date: Tue, 1 Dec 2026 23:18:26 +0000 Subject: [PATCH] feat(driver): add an optional shared host supervisor OPENSHELL_VM_SHARED_SUPERVISOR=true runs one openshell-supervisor --mode=shared process for every sandbox instead of one per sandbox. Off (the default), nothing changes. The gateway serves the shared supervisor's assignment stream only for its in-process Kubernetes driver, so the driver serves it itself, with openshell-supervisor-control's controller as a one-member pool: - the stream is on /@host.sock and accepts only the driver's own uid and a token the driver mints and renews in a file; - each launch assigns the generation's gateway-issued launch credentials, and the supervisor listens on that generation's runtime-initiated Unix control socket while it hosts it, so the guest side is unchanged and the gateway sees the same per-sandbox sessions; - stopping a sandbox asks the supervisor to let go of it and treats the control socket's removal as done. It needs a supervisor that dials a unix: assignment endpoint and serves a sandbox on its own socket (fork branch feat/shared-host-unix/mr-miles, not upstream); with the current pin every shared launch fails, so leave it off until the pin carries that change. There is no failover without a gateway-signed takeover grant: if the shared supervisor exits, its VMs fail and the next launch starts a new one. Supervisor identity, the additional destination CA and an upstream proxy are refused with it. Co-Authored-By: Claude Opus 5.5 --- README.md | 49 +- vendor/openshell/Cargo.lock | 31 +- vendor/openshell/Cargo.toml | 1 + .../crates/openshell-driver-vm/Cargo.toml | 5 + .../crates/openshell-driver-vm/README.md | 9 + .../crates/openshell-driver-vm/src/driver.rs | 480 +++++++-- .../openshell-driver-vm/src/isolation/mod.rs | 55 +- .../crates/openshell-driver-vm/src/lib.rs | 2 + .../crates/openshell-driver-vm/src/main.rs | 6 + .../src/registry_cache_tests.rs | 1 + .../src/shared_supervisor.rs | 949 ++++++++++++++++++ 11 files changed, 1515 insertions(+), 73 deletions(-) create mode 100644 vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs diff --git a/README.md b/README.md index 62baaf6..082205b 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,8 @@ The driver's `OPENSHELL_VM_DEFAULT_WORKDIR` (default `/sandbox`) sets the workin sandboxes whose image has none ([Image ENV and WORKDIR](#image-env-and-workdir)). The driver's `OPENSHELL_VM_SUPERVISOR_IDENTITY*` options (optional, off by default) are in [Supervisor identity](#supervisor-identity). +The driver's `OPENSHELL_VM_SHARED_SUPERVISOR` (default `false`) runs one host supervisor for +every sandbox; see [Shared supervisor](#shared-supervisor). The driver's `OPENSHELL_VM_MAX_VCPUS` and `OPENSHELL_VM_MAX_MEM_MIB` limit what a sandbox can request with `--cpu` and `--memory`, and `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`, `OPENSHELL_VM_FILES_ROOT` and `OPENSHELL_VM_FILES_MAX_BYTES` what it can request in its `driver_config`; see @@ -733,13 +735,56 @@ Limits: - This is not SPIRE. There is one trust domain, no federation, no X.509 SVIDs, and the attestation knows only the supervisor processes this driver started. +## Shared supervisor + +By default every sandbox gets its own host supervisor process, as upstream. Set +`OPENSHELL_VM_SHARED_SUPERVISOR=true` in the driver's environment to run one supervisor for +every sandbox on the host instead. This saves one supervisor's memory per sandbox. It is +experimental and off by default. + +The gateway needs no change: it sees the same per-sandbox supervisor sessions as with dedicated +supervisors. OpenShell's own shared supervisor topology is Kubernetes-only, because the gateway +hands out sandboxes only to an in-process driver. So here the driver does that part itself: + +- On the first launch, the driver starts `openshell-supervisor --mode=shared` and serves the + supervisor's private assignment stream on a Unix socket in its private socket directory. It + accepts only its own uid and a token it mints and renews in a file. The supervisor dials the + gateway itself for every sandbox session, with the gateway's CA (`guest_tls_ca`) when the + gateway uses TLS. +- Each launch hands the supervisor that generation's launch credentials (the ones a dedicated + supervisor receives). The supervisor listens on the VM's control socket while it hosts the + sandbox, as a dedicated supervisor does, so the guest side is unchanged. +- Stopping a sandbox asks the supervisor to stop it and waits until the supervisor lets go of + it, which removes the control socket, or until the usual shutdown grace runs out. Then it + stops the VM. + +This needs a supervisor that can dial a `unix:` assignment endpoint and serve a sandbox on its +own socket. Those changes are not upstream yet (fork branch +`feat/shared-host-unix/mr-miles`). Without them every launch with the shared supervisor +fails, so leave it off unless the pinned OpenShell revision includes them. + +Limits: + +- **No failover.** Moving a running sandbox to another supervisor needs a takeover grant signed + by the gateway. If the shared supervisor exits, every VM it supervised fails with + `ProcessExited`, as one would whose dedicated supervisor exited. The driver starts a new + supervisor for later launches. +- At most 256 sandboxes per driver. +- It cannot be combined with supervisor identity (`OPENSHELL_VM_SUPERVISOR_IDENTITY`), the + network supervisor additional CA, or an upstream proxy. The driver refuses to start with + any of them. +- Agent traces are not relayed: the upstream shared supervisor has no per-sandbox collector yet. +- Its logs and token are under `/shared-supervisor/`: `supervisor.log`, + `supervisor.err.log` and `token`. + ## What does not work - No virtiofs bind mounts and no GPU passthrough on Firecracker. A sandbox that asks for either is rejected at validation, not ignored. To get host files into a guest, use [`driver_config.files`](#per-sandbox-cpu-memory-disk-size-and-files), which copies them in. -- `[openshell.supervisor.network].additional_ca_bundle` and the shared supervisor pool - are rejected by the gateway for any external driver. +- `[openshell.supervisor.network].additional_ca_bundle` and the gateway's shared supervisor + pool are rejected by the gateway for any external driver. The driver has its own + [shared supervisor](#shared-supervisor). - Rootfs tar uploads need the driver and gateway on the same filesystem and UID. - `openshell-gateway config preflight` skips host-tool checks for an external driver; `openshell-firecracker-launcher check` covers the Firecracker ones. diff --git a/vendor/openshell/Cargo.lock b/vendor/openshell/Cargo.lock index bceac5f..93c0088 100644 --- a/vendor/openshell/Cargo.lock +++ b/vendor/openshell/Cargo.lock @@ -1002,7 +1002,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2546,6 +2546,7 @@ dependencies = [ "openshell-otel-test-support", "openshell-sandbox-backend", "openshell-spiffe", + "openshell-supervisor-control", "opentelemetry", "opentelemetry_sdk", "polling", @@ -2725,6 +2726,24 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-supervisor-control" +version = "0.0.0" +source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +dependencies = [ + "openshell-core", + "openshell-otel", + "openshell-sandbox-backend", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tokio-stream", + "tonic", + "tracing", +] + [[package]] name = "openssh" version = "0.11.6" @@ -3572,7 +3591,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3630,7 +3649,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3651,7 +3670,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4374,7 +4393,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5160,7 +5179,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/vendor/openshell/Cargo.toml b/vendor/openshell/Cargo.toml index 74e9217..70ca3c9 100644 --- a/vendor/openshell/Cargo.toml +++ b/vendor/openshell/Cargo.toml @@ -20,6 +20,7 @@ repository = "https://github.com/NVIDIA/OpenShell" openshell-core = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false } openshell-isolation-interface = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-sandbox-backend = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } +openshell-supervisor-control = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-otel = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-otel-test-support = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-spiffe = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } diff --git a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml index 37c2dc6..07069b8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml +++ b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml @@ -28,6 +28,7 @@ openshell-core = { workspace = true, features = ["clap"] } openshell-isolation-interface = { workspace = true } openshell-sandbox-backend = { workspace = true } openshell-otel = { workspace = true, optional = true } +openshell-supervisor-control = { workspace = true, optional = true } base64 = { workspace = true, optional = true } bollard = { version = "0.20", features = ["ssh"], optional = true } @@ -62,6 +63,8 @@ zstd = { version = "0.14", optional = true } aws-lc-rs = { workspace = true, optional = true } axum = { version = "0.8", default-features = false, features = ["http1", "tokio"], optional = true } tonic-prost = { workspace = true, optional = true } +# Shared host supervisor (not in upstream): per-sandbox proxy CA material. +rcgen = { workspace = true, optional = true } [features] # Portable test instrumentation, independent of the compute runtime. @@ -100,6 +103,8 @@ compute-driver = [ "dep:axum", "dep:tonic-prost", "dep:tonic-build", + "dep:openshell-supervisor-control", + "dep:rcgen", ] ## Compile in telemetry support (forwards to openshell-core/telemetry). On by ## default; build with `--no-default-features` for a telemetry-free VM driver diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index 7e11538..a89fbe4 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -26,6 +26,15 @@ Changes from upstream: that attested process. It serves OIDC discovery and JWKS endpoints over HTTP. The server stub is generated in `build.rs` without `protoc`. See `src/supervisor_identity/` and "Supervisor identity" in the repository README. +- **Shared supervisor** (off by default, `OPENSHELL_VM_SHARED_SUPERVISOR`). One + `openshell-supervisor --mode=shared` process for every sandbox instead of one each. The + driver serves the supervisor's private `openshell.supervisor.host.v1` assignment stream + itself, on a private Unix socket with a driver-minted token, using + `openshell-supervisor-control`'s controller as a one-member pool. Each generation keeps the + dedicated runtime-initiated Unix control socket, which the shared supervisor listens on + while it hosts the sandbox, so the guest side is unchanged. Needs the fork's supervisor + changes (`feat/shared-host-unix/mr-miles`). See `src/shared_supervisor.rs` and "Shared + supervisor" in the repository README. - **CPU and memory limits.** Upstream ignores a template's `cpu_limit` and `memory_limit` (`sandbox create --cpu / --memory`) and reports both limits unsupported. Here they set the VM's vCPUs (whole CPUs only, up to `OPENSHELL_VM_MAX_VCPUS`, at most 32) and memory (256 MiB diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 86432b4..48762bc 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -27,6 +27,7 @@ use crate::rootfs::{ sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, validate_host_supervisor, write_rootfs_image_file, }; +use crate::shared_supervisor::{RouteState, SharedSupervisorHost, SharedSupervisorSettings}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; use bollard::Docker; use bollard::errors::Error as BollardError; @@ -264,6 +265,14 @@ const HOST_ADDITIONAL_CA_TEMP_SUFFIX: &str = ".tmp"; const DRIVER_ADMITTED_BACKEND: &str = openshell_sandbox_backend::BACKEND_NAME; const HOST_SUPERVISOR_BINARY: &str = "host-runtime/openshell-supervisor"; const VM_CONTROL_SOCKET: &str = "control.sock"; +/// Shared supervisor state under the driver's state directory (not in upstream). +const SHARED_SUPERVISOR_DIR: &str = "shared-supervisor"; +/// Shared supervisor per-sandbox files under the socket root, kept short for +/// Unix socket paths. `@` never appears in a sandbox ID, so it cannot collide +/// with a sandbox's socket directory. +const SHARED_SUPERVISOR_SOCKET_DIR: &str = "@s"; +/// The shared supervisor's assignment stream socket under the socket root. +const SHARED_SUPERVISOR_HOST_SOCKET: &str = "@host.sock"; const VM_CONTROL_PORT: u32 = 5500; /// Guest path of the driver-authored manifest enumerating which /// `init.d` drop-ins the guest init script is allowed to execute. @@ -497,6 +506,11 @@ pub struct VmDriverConfig { /// See [`crate::local_images`]. #[serde(default)] pub local_image_source: crate::local_images::LocalImageSourceConfig, + + /// Run one host supervisor for every sandbox instead of one per sandbox + /// (not in upstream). Off: one supervisor per sandbox, as upstream. + #[serde(default)] + pub shared_supervisor: bool, } /// Redacting `Debug` so a proxy URL or credential path never reaches a log. @@ -575,6 +589,7 @@ impl std::fmt::Debug for VmDriverConfig { &self.image_cache_max_idle_hours, ) .field("local_image_source", &self.local_image_source) + .field("shared_supervisor", &self.shared_supervisor) .finish() } } @@ -628,6 +643,7 @@ impl Default for VmDriverConfig { sandbox_storage: crate::sandbox_storage::SandboxStorageConfig::default(), image_cache_max_idle_hours: 0, local_image_source: crate::local_images::LocalImageSourceConfig::default(), + shared_supervisor: false, } } } @@ -665,6 +681,35 @@ impl VmDriverConfig { Ok(()) } + /// The shared supervisor runs every sandbox with the same settings and + /// without per-sandbox supervisor processes, so options that need either + /// are refused rather than silently dropped. + pub fn validate_shared_supervisor_config(&self) -> Result<(), String> { + if !self.shared_supervisor { + return Ok(()); + } + let refused = [ + ( + self.supervisor_identity.enabled, + "supervisor identity (OPENSHELL_VM_SUPERVISOR_IDENTITY) attests one supervisor process per sandbox", + ), + ( + self.additional_ca_bundle.is_some() || self.additional_ca_snapshot.is_some(), + "the shared supervisor does not support the network supervisor additional destination CA", + ), + ( + self.upstream_proxy.https_proxy.is_some(), + "the shared supervisor does not support an upstream proxy", + ), + ]; + match refused.iter().find(|(set, _)| *set) { + Some((_, reason)) => Err(format!( + "OPENSHELL_VM_SHARED_SUPERVISOR cannot be combined with this configuration: {reason}" + )), + None => Ok(()), + } + } + /// Most memory a sandbox may request: `max_mem_mib`, or `mem_mib` when /// unset. pub fn effective_max_mem_mib(&self) -> u32 { @@ -1261,10 +1306,29 @@ struct HostSupervisor { supervisor_identity: Option, } +/// A sandbox's place on the shared host supervisor (not in upstream). +#[derive(Debug)] +struct SharedAttachment { + host: Arc, + route: String, + /// The VM's control socket, which the supervisor listens on while it + /// hosts the sandbox and unlinks when it lets go of it. + control_socket: PathBuf, +} + +impl Drop for SharedAttachment { + fn drop(&mut self) { + self.host.forget(&self.route); + } +} + #[derive(Debug)] struct VmProcess { child: Child, - supervisor: Child, + /// The sandbox's dedicated host supervisor; `None` on the shared one. + supervisor: Option, + /// The sandbox's route on the shared supervisor (not in upstream). + shared: Option, supervisor_liveness: Option, /// This sandbox's Workload API, while supervisor identity is enabled. supervisor_identity: Option, @@ -1373,6 +1437,9 @@ pub struct VmDriver { supervisor_identity: Option>, /// Where the driver is in its shutdown ([`VmDriver::shutdown`]). shutdown: Arc>, + /// The host supervisor every sandbox shares, started by the first launch + /// while `shared_supervisor` is on (not in upstream). + shared_supervisor: Arc>>, } /// The driver's progress through [`VmDriver::shutdown`]. @@ -1431,6 +1498,7 @@ impl VmDriver { .map_err(|err| err.message().to_string())?; config.validate_sandbox_identity()?; config.validate_runtime_security_config()?; + config.validate_shared_supervisor_config()?; config.local_image_source.validate()?; info!( mode = config.local_image_source.mode.as_str(), @@ -1529,6 +1597,7 @@ impl VmDriver { lifecycle_extensions: Arc::new(lifecycle_extensions), shutdown: new_shutdown_state(), supervisor_identity, + shared_supervisor: Arc::default(), }; preparation::reconcile(&image_cache_root_dir(&driver.config.state_dir)) .map_err(|error| format!("reconcile image preparation staging: {error}"))?; @@ -1662,6 +1731,96 @@ impl VmDriver { .map_err(|error| Status::internal(format!("stage host additional CA: {error}"))) } + /// The shared host supervisor, started on first use (not in upstream). + async fn shared_supervisor_host( + &self, + tls_paths: Option<&VmDriverTlsPaths>, + ) -> Result, Status> { + if let Some(host) = self.shared_supervisor.get() { + return Ok(host.clone()); + } + let supervisor_binary = self.host_supervisor_binary().await?; + let (gateway_endpoint, gateway_tls_server_name) = + host_control_openshell_endpoint(&self.config.grpc_endpoint) + .map_err(Status::failed_precondition)?; + let mut environment = vec![ + ( + openshell_core::sandbox_env::LOG_LEVEL.to_string(), + self.config.log_level.clone(), + ), + ( + openshell_core::sandbox_env::TELEMETRY_ENABLED.to_string(), + openshell_core::telemetry::enabled_env_value().to_string(), + ), + ]; + if let Some(name) = &self.config.supervisor_gateway_name { + environment.push(( + openshell_core::sandbox_env::GATEWAY_NAME.to_string(), + name.clone(), + )); + } + let settings = SharedSupervisorSettings { + supervisor_binary, + dir: self.config.state_dir.join(SHARED_SUPERVISOR_DIR), + session_root: self.socket_root.join(SHARED_SUPERVISOR_SOCKET_DIR), + host_socket: self.socket_root.join(SHARED_SUPERVISOR_HOST_SOCKET), + gateway_endpoint, + gateway_tls_server_name, + gateway_ca: tls_paths.map(|paths| paths.ca.clone()), + environment, + args: self.config.ipv6_egress.supervisor_args(), + }; + self.shared_supervisor + .get_or_try_init(|| async { SharedSupervisorHost::start(settings) }) + .await + .cloned() + .map_err(|error| Status::unavailable(format!("start the shared supervisor: {error}"))) + } + + /// Hand one generation to the shared supervisor, which listens on its + /// control socket while it hosts it (not in upstream). + #[allow(clippy::too_many_arguments)] + async fn attach_shared_supervisor( + &self, + sandbox: &Sandbox, + route: &str, + runtime_descriptor: &SandboxRuntimeDescriptor, + auth_bundle: &openshell_core::jwt::SupervisorAuthBundle, + image_ref: &str, + workdir: Option<&str>, + tls_paths: Option<&VmDriverTlsPaths>, + control_socket: &Path, + ) -> Result { + let host = self.shared_supervisor_host(tls_paths).await?; + let main_process_spec = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec( + sandbox.spec.as_ref(), + ) + .map_err(|error| Status::internal(format!("encode main process spec: {error}")))?; + let (assignment, auth_epoch) = crate::shared_supervisor::InstanceLaunch { + route: route.to_string(), + sandbox_id: sandbox.id.clone(), + sandbox_name: sandbox.name.clone(), + runtime_descriptor: runtime_descriptor.clone(), + auth: auth_bundle.clone(), + main_process_spec, + workdir: workdir.map(str::to_string), + container_image: image_ref.to_string(), + } + .into_assignment() + .map_err(Status::internal)?; + // From here the attachment forgets the route if the launch fails. + let attachment = SharedAttachment { + host: host.clone(), + route: route.to_string(), + control_socket: control_socket.to_path_buf(), + }; + host.launch(assignment, auth_epoch) + .await + .map_err(Status::unavailable)?; + info!(sandbox_id = %sandbox.id, %route, "vm driver: sandbox assigned to the shared supervisor"); + Ok(attachment) + } + #[allow(clippy::too_many_arguments)] async fn spawn_host_supervisor( &self, @@ -2408,6 +2567,13 @@ impl VmDriver { server_name: channel_tls.server_name.clone(), trust_anchor_pem: channel_tls.trust_anchor_pem.clone(), }; + // The shared supervisor listens on the same control socket a dedicated + // one does, while it hosts the sandbox; a route keys the generation + // on it and never goes on the wire. + let shared_route = self + .config + .shared_supervisor + .then(openshell_sandbox_backend::runtime_routed::new_route_handle); let transport = SandboxTransport::RuntimeInitiatedUnix { socket_path: control_socket.clone(), }; @@ -2482,6 +2648,24 @@ impl VmDriver { command.arg("--vm-vcpus").arg(plan.vcpus.to_string()); command.arg("--vm-mem-mib").arg(plan.mem_mib.to_string()); let _ = tokio::fs::remove_file(&control_socket).await; + // The shared supervisor takes the generation before the VM boots and + // listens on its control socket, as a dedicated supervisor would. + let mut shared_attachment = match &shared_route { + Some(route) => Some( + self.attach_shared_supervisor( + &sandbox, + route, + &runtime_descriptor, + &launch_authentication.supervisor, + &image_ref, + workdir.as_deref(), + tls_paths.as_ref(), + &control_socket, + ) + .await?, + ), + None => None, + }; command .arg("--vm-vsock-runtime-initiated") .arg("--vm-vsock-control-port") @@ -2549,38 +2733,51 @@ impl VmDriver { launcher_pid = child.id().unwrap_or(0), "vm driver: launcher spawned" ); - let host_supervisor = match self - .spawn_host_supervisor( - &sandbox, - &state_dir, - tls_paths.as_ref(), - &runtime_descriptor, - &launch_authentication.supervisor, - sandbox_owner_state, - workdir.as_deref(), - ) - .await - { - Ok(supervisor) => supervisor, - Err(error) => { - let _ = terminate_vm_process(&mut child).await; - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::LauncherSpawnFailed, - ) - .await; - return Err(error); + let process = if let Some(shared) = shared_attachment.take() { + VmProcess { + child, + supervisor: None, + shared: Some(shared), + supervisor_liveness: None, + deleting: false, + supervisor_identity: None, + } + } else { + let host_supervisor = match self + .spawn_host_supervisor( + &sandbox, + &state_dir, + tls_paths.as_ref(), + &runtime_descriptor, + &launch_authentication.supervisor, + sandbox_owner_state, + workdir.as_deref(), + ) + .await + { + Ok(supervisor) => supervisor, + Err(error) => { + let _ = terminate_vm_process(&mut child).await; + self.lifecycle_extensions + .after_launch_failed( + &sandbox, + &state_dir, + LaunchAbortReason::LauncherSpawnFailed, + ) + .await; + return Err(error); + } + }; + VmProcess { + child, + supervisor: Some(host_supervisor.child), + shared: None, + supervisor_liveness: host_supervisor.liveness, + deleting: false, + supervisor_identity: host_supervisor.supervisor_identity, } }; - let process = Arc::new(Mutex::new(VmProcess { - child, - supervisor: host_supervisor.child, - supervisor_liveness: host_supervisor.liveness, - deleting: false, - supervisor_identity: host_supervisor.supervisor_identity, - })); + let process = Arc::new(Mutex::new(process)); let mut process_to_stop = None; let mut snapshot_to_publish = None; @@ -5389,12 +5586,25 @@ impl VmDriver { if process.deleting { return; } + let process = &mut *process; + let exited = |component: &'static str, status: ExitStatus| { + let message = status.code().map_or_else( + || format!("{component} process exited"), + |code| format!("{component} process exited with status {code}"), + ); + (component, message) + }; match process.child.try_wait() { - Ok(Some(status)) => Ok(Some(("VM", status))), - Ok(None) => process - .supervisor - .try_wait() - .map(|status| status.map(|status| ("host supervisor", status))), + Ok(Some(status)) => Ok(Some(exited("VM", status))), + Ok(None) => match (process.supervisor.as_mut(), process.shared.as_ref()) { + (Some(supervisor), _) => supervisor + .try_wait() + .map(|status| status.map(|status| exited("host supervisor", status))), + (None, Some(shared)) => { + Ok(shared_route_exit(&shared.host.route_state(&shared.route))) + } + (None, None) => Ok(None), + }, Err(error) => Err(error), } }; @@ -5425,7 +5635,7 @@ impl VmDriver { } }; - if let Some((component, status)) = exit_status { + if let Some((component, mut message)) = exit_status { let state_dir = { let registry = self.registry.lock().await; registry @@ -5447,16 +5657,17 @@ impl VmDriver { } { let mut process = process.lock().await; + // The shared supervisor's route goes with the VM either + // way; dropping the attachment withdraws it. + process.shared.take(); if component == "VM" { - let _ = terminate_vm_process(&mut process.supervisor).await; + if let Some(supervisor) = process.supervisor.as_mut() { + let _ = terminate_vm_process(supervisor).await; + } } else { let _ = terminate_vm_process(&mut process.child).await; } } - let mut message = status.code().map_or_else( - || format!("{component} process exited"), - |code| format!("{component} process exited with status {code}"), - ); if component == "host supervisor" && let Some(state_dir) = state_dir.as_deref() && let Some(stderr) = read_vm_console_tail( @@ -5598,6 +5809,7 @@ pub async fn run_image_preparation_worker(request_path: &Path) -> Result<(), Str lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let prepare = async { if let Some(overlay) = request.overlay { @@ -8207,21 +8419,31 @@ async fn terminate_sandbox_processes_within( process: &mut VmProcess, supervisor_grace: Duration, ) -> Result<(), std::io::Error> { - let supervisor_pid = process.supervisor.id(); - let supervisor_error = terminate_vm_process_within(&mut process.supervisor, supervisor_grace) - .await - .inspect(|status| { - // An orderly shutdown returns the workload's exit code, which can - // be nonzero even after the guest acknowledges termination. - if status.signal().is_some() { - warn!( - ?supervisor_pid, - %status, - "VM host supervisor was terminated by a signal; guest filesystem flush was not confirmed and recent writes may be lost" - ); - } - }) - .err(); + if let Some(shared) = process.shared.take() { + // The shared supervisor stops the workload as a dedicated one does on + // SIGTERM; the VM is killed once it has, or once the grace runs out. + stop_shared_route(&shared, &mut process.child, supervisor_grace).await; + } + let supervisor_error = match process.supervisor.as_mut() { + Some(supervisor) => { + let supervisor_pid = supervisor.id(); + terminate_vm_process_within(supervisor, supervisor_grace) + .await + .inspect(|status| { + // An orderly shutdown returns the workload's exit code, which can + // be nonzero even after the guest acknowledges termination. + if status.signal().is_some() { + warn!( + ?supervisor_pid, + %status, + "VM host supervisor was terminated by a signal; guest filesystem flush was not confirmed and recent writes may be lost" + ); + } + }) + .err() + } + None => None, + }; process.supervisor_liveness.take(); // The supervisor is gone: stop its Workload API and remove the socket // and the binary link. @@ -8238,6 +8460,54 @@ async fn terminate_sandbox_processes_within( } } +/// What a shared supervisor route's state means for its VM: the component +/// that ended and why, or `None` while it runs (not in upstream). +fn shared_route_exit(state: &RouteState) -> Option<(&'static str, String)> { + match state { + RouteState::Pending | RouteState::Running => None, + RouteState::Exited(code) => Some(( + "workload", + format!("workload process exited with status {code}"), + )), + RouteState::Failed(error) => Some(( + "shared supervisor", + format!("shared supervisor could not run the sandbox: {error}"), + )), + RouteState::Lost => Some(( + "shared supervisor", + "the shared supervisor process that ran this sandbox exited".to_string(), + )), + } +} + +/// Withdraw a sandbox from the shared supervisor and wait, up to `grace`, +/// for the supervisor to let go of it: once it has stopped the workload it +/// drops the sandbox, which unlinks the control socket, as a dedicated +/// supervisor exits. Its status is no longer reported once withdrawn, so the +/// socket is the signal. Dropping the attachment then forgets the route (not +/// in upstream). +async fn stop_shared_route(shared: &SharedAttachment, vm: &mut Child, grace: Duration) { + const POLL: Duration = Duration::from_millis(100); + shared.host.withdraw(&shared.route); + let deadline = tokio::time::Instant::now() + grace; + while tokio::time::Instant::now() < deadline { + if matches!(vm.try_wait(), Ok(Some(_)) | Err(_)) + || !shared.control_socket.exists() + || matches!( + shared.host.route_state(&shared.route), + RouteState::Exited(_) | RouteState::Failed(_) | RouteState::Lost + ) + { + return; + } + tokio::time::sleep(POLL).await; + } + warn!( + route = %shared.route, + "the shared supervisor did not confirm the sandbox stopped in time; guest filesystem flush was not confirmed and recent writes may be lost" + ); +} + fn absolute_state_dir(state_dir: &Path) -> Result { if state_dir.is_absolute() { return Ok(state_dir.to_path_buf()); @@ -11757,6 +12027,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!(driver.capabilities().default_image, "openshell/sandbox:dev"); @@ -12020,6 +12291,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12057,6 +12329,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12088,6 +12361,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12120,6 +12394,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!( @@ -12147,6 +12422,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!( @@ -12171,6 +12447,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let error = driver @@ -12205,6 +12482,57 @@ mod tests { } } + #[test] + fn shared_supervisor_refuses_settings_it_cannot_apply_per_sandbox() { + let shared = VmDriverConfig { + shared_supervisor: true, + ..VmDriverConfig::default() + }; + assert!(shared.validate_shared_supervisor_config().is_ok()); + + let mut with_identity = shared.clone(); + with_identity.supervisor_identity.enabled = true; + let error = with_identity + .validate_shared_supervisor_config() + .unwrap_err(); + assert!(error.contains("OPENSHELL_VM_SHARED_SUPERVISOR"), "{error}"); + + let mut with_proxy = shared.clone(); + with_proxy.upstream_proxy.https_proxy = Some("http://proxy.example:3128".to_string()); + assert!(with_proxy.validate_shared_supervisor_config().is_err()); + + let mut with_ca = shared; + with_ca.additional_ca_bundle = Some(PathBuf::from("/etc/openshell/extra-ca.pem")); + assert!(with_ca.validate_shared_supervisor_config().is_err()); + + // Off, the same settings are accepted, as before. + let mut dedicated = with_identity; + dedicated.shared_supervisor = false; + assert!(dedicated.validate_shared_supervisor_config().is_ok()); + } + + #[test] + fn shared_route_exit_ends_the_vm_only_when_supervision_ends() { + assert_eq!(shared_route_exit(&RouteState::Pending), None); + assert_eq!(shared_route_exit(&RouteState::Running), None); + assert_eq!( + shared_route_exit(&RouteState::Exited(3)), + Some(( + "workload", + "workload process exited with status 3".to_string() + )) + ); + assert_eq!( + shared_route_exit(&RouteState::Lost).map(|(component, _)| component), + Some("shared supervisor") + ); + assert_eq!( + shared_route_exit(&RouteState::Failed("boom".to_string())) + .map(|(component, _)| component), + Some("shared supervisor") + ); + } + #[tokio::test] async fn supervisor_identity_disabled_creates_no_issuer_or_key() { let temp = tempfile::tempdir().unwrap(); @@ -13079,6 +13407,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_file = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13109,7 +13438,8 @@ mod tests { record.state_dir = retry_state_dir; record.process = Some(Arc::new(Mutex::new(VmProcess { child: spawn_exited_child(), - supervisor: spawn_exited_child(), + supervisor: Some(spawn_exited_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13148,6 +13478,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13205,6 +13536,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13709,7 +14041,8 @@ while :; do sleep 0.05; done"#, let mut process = VmProcess { child: spawn_exited_child(), - supervisor, + supervisor: Some(supervisor), + shared: None, supervisor_liveness: Some(fs::File::from(write_end)), supervisor_identity: None, deleting: false, @@ -13791,7 +14124,8 @@ while :; do sleep 0.05; done"#, let mut process = VmProcess { child: spawn_exited_child(), - supervisor, + supervisor: Some(supervisor), + shared: None, supervisor_liveness: Some(fs::File::from(write_end)), supervisor_identity: None, deleting: false, @@ -13808,7 +14142,13 @@ while :; do sleep 0.05; done"#, "the supervisor must get its full grace before the kill: {elapsed:?}" ); assert!( - process.supervisor.try_wait().unwrap().is_some(), + process + .supervisor + .as_mut() + .unwrap() + .try_wait() + .unwrap() + .is_some(), "the supervisor is gone once the grace has expired" ); assert!(process.supervisor_liveness.is_none()); @@ -13843,7 +14183,8 @@ while :; do sleep 0.05; done"#, }; let process = Arc::new(Mutex::new(VmProcess { child, - supervisor: spawn_exited_child(), + supervisor: Some(spawn_exited_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13882,7 +14223,8 @@ while :; do sleep 0.05; done"#, ) -> Arc> { let process = Arc::new(Mutex::new(VmProcess { child: spawn_running_child(), - supervisor: spawn_running_child(), + supervisor: Some(spawn_running_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13969,7 +14311,15 @@ while :; do sleep 0.05; done"#, { let mut process = process.lock().await; assert!(process.deleting); - assert!(process.supervisor.try_wait().unwrap().is_some()); + assert!( + process + .supervisor + .as_mut() + .unwrap() + .try_wait() + .unwrap() + .is_some() + ); assert!(process.child.try_wait().unwrap().is_some()); } for marker in [SANDBOX_STOPPED_FILE, MAIN_PROCESS_EXITED_FILE] { @@ -14110,6 +14460,7 @@ while :; do sleep 0.05; done"#, lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } @@ -14458,6 +14809,7 @@ while :; do sleep 0.05; done"#, lifecycle_extensions: Arc::new(extensions), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } diff --git a/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs b/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs index e054a1b..133a346 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs @@ -102,7 +102,11 @@ impl VmBoundarySpec { tls: self.sandbox_tls, } } - SandboxTransport::RuntimeInitiatedUnix { .. } => { + // A shared supervisor's route (not in upstream): the + // guest dials the same vsock port, and the driver relays + // it to the routed listener with the route prefixed. + SandboxTransport::RuntimeInitiatedUnix { .. } + | SandboxTransport::RuntimeInitiatedRouted { .. } => { BoundaryListener::RuntimeInitiatedVsock { host_port: self.control_port, tls: self.sandbox_tls, @@ -166,6 +170,55 @@ mod tests { ); } + #[test] + fn routed_transport_keeps_the_guest_on_runtime_initiated_vsock() { + let session_id = openshell_core::SandboxSessionId::new(); + let material = generate_sandbox_tls_material(session_id).unwrap(); + let route = openshell_sandbox_backend::runtime_routed::new_route_handle(); + let provisioned = VmBoundarySpec { + boundary_id: "sandbox-1".to_string(), + generation: "generation-1".to_string(), + session_id, + session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), + auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + gateway_id: "gateway-1".to_string(), + verification_keys: Vec::new(), + image_identity: "sha256:image".to_string(), + transport: SandboxTransport::RuntimeInitiatedRouted { + authority: material.server_name.clone(), + route: route.clone(), + }, + supervisor_tls: SandboxTlsClientConfig { + server_name: material.server_name, + trust_anchor_pem: material.trust_anchor_pem, + }, + sandbox_tls: SandboxTlsServerConfig { + certificate_chain_path: "/.openshell/state/sandbox.crt".into(), + private_key_path: "/.openshell/state/sandbox.key".into(), + }, + control_port: 5500, + agent_uid: 1000, + agent_gid: 1000, + child_env: HashMap::new(), + } + .provision() + .unwrap(); + assert!(matches!( + provisioned.boundary_config.listener, + BoundaryListener::RuntimeInitiatedVsock { + host_port: 5500, + .. + } + )); + assert_eq!( + provisioned.runtime_descriptor.transport, + SandboxTransport::RuntimeInitiatedRouted { + authority: provisioned.runtime_descriptor.tls.server_name.clone(), + route, + } + ); + } + #[test] fn provisioning_binds_identical_resource_claims() { assert_provisioning_claims(); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs index 620c927..262c6e5 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs @@ -37,6 +37,8 @@ mod rootfs; #[cfg(feature = "compute-driver")] pub mod sandbox_storage; #[cfg(feature = "compute-driver")] +mod shared_supervisor; +#[cfg(feature = "compute-driver")] pub mod supervisor_identity; mod version; diff --git a/vendor/openshell/crates/openshell-driver-vm/src/main.rs b/vendor/openshell/crates/openshell-driver-vm/src/main.rs index d1a273f..0086b2f 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/main.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/main.rs @@ -236,6 +236,11 @@ struct Args { #[arg(long, env = "OPENSHELL_VM_DEFAULT_WORKDIR", default_value = "/sandbox")] default_workdir: String, + /// Run one host supervisor shared by every sandbox instead of one per + /// sandbox. Off: a dedicated supervisor per sandbox, as upstream. + #[arg(long, env = "OPENSHELL_VM_SHARED_SUPERVISOR", default_value_t = false)] + shared_supervisor: bool, + /// Issue SPIFFE JWT-SVIDs to host supervisors over a per-sandbox Workload /// API socket, and serve the JWKS that verifies them. Off: no socket, no /// JWKS listener, nothing in the supervisor's environment. @@ -422,6 +427,7 @@ async fn main() -> Result<()> { args.local_image_source_socket.as_deref(), ) .map_err(|err| miette::miette!("{err}"))?, + shared_supervisor: args.shared_supervisor, }) .await .map_err(|err| miette::miette!("{err}"))?; diff --git a/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs b/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs index 1c90c15..9df6024 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs @@ -188,6 +188,7 @@ fn driver(root: &Path) -> VmDriver { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } diff --git a/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs b/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs new file mode 100644 index 0000000..c53554d --- /dev/null +++ b/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs @@ -0,0 +1,949 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! One host supervisor shared by every sandbox of this driver (not in +//! upstream). +//! +//! With `shared_supervisor` on, the driver runs one `openshell-supervisor +//! --mode=shared` process instead of one supervisor per VM. Upstream, a +//! shared supervisor takes its sandbox instances from the gateway over the +//! private `openshell.supervisor.host.v1` stream, which the gateway serves +//! only for its in-process Kubernetes driver. Here the driver serves that +//! stream itself on a private Unix socket, so the gateway is unchanged and +//! sees the same per-sandbox supervisor sessions as with dedicated +//! supervisors: +//! +//! - The driver's [`SupervisorHostController`] is a pool of one member: this +//! host. The driver hands it the complete pool view every time a sandbox +//! starts or stops; nothing is durable, since the driver stops every VM +//! when it stops. +//! - Each sandbox's launch material is built from the same gateway-issued +//! launch credentials a dedicated supervisor receives, with the same +//! runtime-initiated Unix control socket. The supervisor listens on it for +//! as long as it hosts the sandbox, so the guest side is exactly that of a +//! dedicated supervisor. The host dials the real gateway for every sandbox +//! session (`HostAccepted.peer_endpoint`). +//! - A route keys each sandbox on the supervisor. It never goes on the wire. +//! +//! This needs a supervisor that dials a `unix:` assignment endpoint and +//! serves a sandbox on its own socket (the fork's `patched` branch, from +//! `feat/shared-host-unix/mr-miles`). +//! +//! What it does not do: move a sandbox to another supervisor. Takeover needs +//! a gateway-signed grant, so a crashed shared supervisor loses every VM it +//! supervised; the driver stops them and starts a new supervisor for the +//! next launches. + +use std::collections::BTreeMap; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::{Arc, Mutex as StdMutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use openshell_core::proto::supervisor_host::v1::supervisor_host_server::{ + SupervisorHost, SupervisorHostServer, +}; +use openshell_core::proto::supervisor_host::v1::{ + HostGatewayMessage, HostMessage, SandboxInstanceAssignment, SandboxInstancePhase, +}; +use openshell_supervisor_control::{ + DEFAULT_MAX_MEMBERS_PER_GATEWAY, HostIdentity, InstanceOwner, MemberView, ObservedInstance, + PoolLimits, PoolView, SupervisorHostController, +}; +use tokio::process::Command; +use tokio::sync::watch; +use tokio::task::JoinHandle; +use tonic::{Request, Response, Status, Streaming}; +use tracing::{debug, info, warn}; + +/// Pool member ID the shared supervisor announces; the only member. +pub const MEMBER_ID: &str = "openshell-vm-driver"; +/// Most sandboxes the shared supervisor runs. Sizes its message bounds too. +pub const MAX_INSTANCES: usize = 256; +/// Subject of the supervisor tokens the driver mints. +const TOKEN_SUBJECT: &str = "openshell-supervisor:openshell-vm-driver"; +/// Lifetime of one supervisor token. The controller ends the stream when the +/// token in use expires; the host reconnects with the renewed file. +const TOKEN_TTL: Duration = Duration::from_hours(12); +/// How often a new token is written; the previous one stays valid until it +/// expires, so a host that has not re-read the file yet keeps working. +const TOKEN_RENEWAL: Duration = Duration::from_hours(1); +/// How long a launch waits for the shared supervisor to be connected. +const CONNECT_WAIT: Duration = Duration::from_mins(1); +const RESPAWN_BACKOFF_MIN: Duration = Duration::from_secs(1); +const RESPAWN_BACKOFF_MAX: Duration = Duration::from_secs(30); +/// A supervisor that ran this long before exiting restarts with the shortest +/// backoff again. +const RESPAWN_STABLE_AFTER: Duration = Duration::from_mins(1); + +/// What the driver supplies to start the shared supervisor. +pub struct SharedSupervisorSettings { + /// The host supervisor binary, the same one dedicated supervisors run. + pub supervisor_binary: PathBuf, + /// Private directory for the token and the logs. + pub dir: PathBuf, + /// Private directory, short enough for Unix socket paths, for the + /// supervisor's per-sandbox files. + pub session_root: PathBuf, + /// The assignment stream's socket, also short enough for a socket path. + pub host_socket: PathBuf, + /// Gateway endpoint as a host supervisor dials it. + pub gateway_endpoint: String, + /// TLS server name the supervisor verifies the gateway with, when it + /// differs from the endpoint's host. + pub gateway_tls_server_name: Option, + /// The gateway's CA, when the gateway uses TLS. + pub gateway_ca: Option, + /// Extra supervisor environment (log level, telemetry). + pub environment: Vec<(String, String)>, + /// Extra supervisor arguments (policy DNS IPv6 egress, NAT64 prefixes). + pub args: Vec, +} +/// What the shared supervisor reports for one sandbox's route. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RouteState { + /// Assigned; the supervisor has not reported it running yet. + Pending, + /// The supervisor runs the sandbox. + Running, + /// The sandbox's canonical process exited. + Exited(i32), + /// The supervisor could not run the sandbox. + Failed(String), + /// The supervisor process that ran the sandbox is gone, or the route was + /// never assigned. Its workload cannot be supervised again. + Lost, +} + +/// One sandbox's route as the driver assigned it. +struct RouteEntry { + assignment: SandboxInstanceAssignment, + auth_epoch: u64, + /// Supervisor process the route was assigned to. + process_id: String, + /// Withdrawn: no longer desired, so its owner stops it, but still owned + /// so the driver can watch it stop. + withdrawn: bool, +} + +#[derive(Default)] +struct HostState { + /// The connected shared supervisor process. + process_id: Option, + routes: BTreeMap, +} + +/// The driver's shared supervisor: the process, its assignment stream, and +/// the routes of the sandboxes it supervises. +pub struct SharedSupervisorHost { + controller: SupervisorHostController, + runtime_address: SocketAddr, + state: StdMutex, + /// The connected supervisor process, `None` while there is none. + process: watch::Sender>, + tasks: StdMutex>>, +} + +impl std::fmt::Debug for SharedSupervisorHost { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SharedSupervisorHost") + .field("runtime_address", &self.runtime_address) + .finish_non_exhaustive() + } +} + +impl Drop for SharedSupervisorHost { + fn drop(&mut self) { + for task in lock(&self.tasks).drain(..) { + task.abort(); + } + } +} + +impl SharedSupervisorHost { + /// Start the assignment listener and the shared supervisor process. + /// Returns once both are running; the supervisor connects in the + /// background, and [`Self::launch`] waits for it. + pub(crate) fn start(settings: SharedSupervisorSettings) -> Result, String> { + create_private_dir(&settings.dir)?; + create_private_dir(&settings.session_root)?; + + let token_path = settings.dir.join("token"); + let tokens = Arc::new(StdMutex::new(Tokens::new()?)); + write_private_file(&token_path, lock(&tokens).current.token.as_bytes())?; + + let _ = std::fs::remove_file(&settings.host_socket); + let listener = tokio::net::UnixListener::bind(&settings.host_socket).map_err(|error| { + format!( + "listen for the shared supervisor on {}: {error}", + settings.host_socket.display() + ) + })?; + set_private_mode(&settings.host_socket)?; + // The supervisor still opens its shared runtime listener and + // advertises it, though every sandbox here has its own socket. + let runtime_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), free_port()?); + let health_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), free_port()?); + + let controller = SupervisorHostController::new(); + controller.set_pool_limits( + PoolLimits::new(MAX_INSTANCES, DEFAULT_MAX_MEMBERS_PER_GATEWAY) + .map_err(|error| format!("shared supervisor pool limits: {error}"))?, + ); + controller.set_gateway_replicas(1); + // Sandbox sessions go to the real gateway, not to this socket. + controller.set_peer_endpoint(settings.gateway_endpoint.clone()); + + let host = Arc::new(Self { + controller: controller.clone(), + runtime_address, + state: StdMutex::new(HostState::default()), + process: watch::channel(None).0, + tasks: StdMutex::new(Vec::new()), + }); + // An empty view lets the first stream receive its (empty) snapshot. + host.publish(); + + let service = HostService { + controller, + tokens: tokens.clone(), + uid: rustix::process::geteuid().as_raw(), + }; + let serve = tokio::spawn(serve_assignments(listener, service)); + let renew = tokio::spawn(renew_tokens(tokens, token_path.clone())); + let watch_members = tokio::spawn(watch_membership(Arc::downgrade(&host))); + let command = SupervisorCommand { + binary: settings.supervisor_binary, + dir: settings.dir, + session_root: settings.session_root, + assignment_endpoint: format!("unix:{}", settings.host_socket.display()), + token_path, + gateway_ca: settings.gateway_ca, + gateway_tls_server_name: settings.gateway_tls_server_name, + runtime_address, + health_address, + environment: settings.environment, + args: settings.args, + }; + let keep = tokio::spawn(keep_supervisor(command, Arc::downgrade(&host))); + lock(&host.tasks).extend([serve, renew, watch_members, keep]); + info!( + assignments = %settings.host_socket.display(), + "vm driver: shared supervisor started" + ); + Ok(host) + } + + /// Assign a sandbox generation to the shared supervisor, which starts + /// supervising it once the guest dials in. Waits for a connected + /// supervisor process. + pub(crate) async fn launch( + &self, + assignment: SandboxInstanceAssignment, + auth_epoch: u64, + ) -> Result<(), String> { + let mut process = self.process.subscribe(); + let process_id = tokio::time::timeout(CONNECT_WAIT, process.wait_for(Option::is_some)) + .await + .map_err(|_| "the shared supervisor did not connect in time".to_string())? + .map_err(|_| "the shared supervisor stopped".to_string())? + .clone() + .ok_or_else(|| "the shared supervisor is not connected".to_string())?; + { + let mut state = lock(&self.state); + let route = assignment.route.clone(); + if !state.routes.contains_key(&route) && state.routes.len() >= MAX_INSTANCES { + return Err(format!( + "the shared supervisor already runs {MAX_INSTANCES} sandboxes" + )); + } + if state.process_id.as_deref() != Some(process_id.as_str()) { + return Err("the shared supervisor restarted; retry the launch".to_string()); + } + state.routes.insert( + route, + RouteEntry { + assignment, + auth_epoch, + process_id, + withdrawn: false, + }, + ); + } + self.publish(); + Ok(()) + } + + /// Ask the shared supervisor to stop a sandbox. The route stays owned so + /// [`Self::route_state`] can watch it stop; [`Self::forget`] drops it. + pub(crate) fn withdraw(&self, route: &str) { + let changed = lock(&self.state) + .routes + .get_mut(route) + .is_some_and(|entry| !std::mem::replace(&mut entry.withdrawn, true)); + if changed { + self.publish(); + } + } + + /// Drop a stopped sandbox's route. + pub(crate) fn forget(&self, route: &str) { + if lock(&self.state).routes.remove(route).is_some() { + self.publish(); + } + } + + /// What the shared supervisor reports for `route`. + pub(crate) fn route_state(&self, route: &str) -> RouteState { + { + let state = lock(&self.state); + let Some(entry) = state.routes.get(route) else { + return RouteState::Lost; + }; + if state.process_id.as_deref() != Some(entry.process_id.as_str()) { + return RouteState::Lost; + } + } + match self.controller.observed(route) { + ObservedInstance::Reported(status) => { + match SandboxInstancePhase::try_from(status.phase) + .unwrap_or(SandboxInstancePhase::Unspecified) + { + SandboxInstancePhase::Exited => RouteState::Exited(status.exit_code), + SandboxInstancePhase::Failed => RouteState::Failed(status.error), + SandboxInstancePhase::Supervising if status.ready => RouteState::Running, + _ => RouteState::Pending, + } + } + ObservedInstance::NoHost | ObservedInstance::Pending | ObservedInstance::Absent => { + RouteState::Pending + } + } + } + + /// Replace the controller's pool view with the driver's routes. The + /// controller sends the supervisor a snapshot of the routes it owns and + /// lists withdrawn ones for it to stop. + fn publish(&self) { + let view = { + let state = lock(&self.state); + pool_view(&state, self.runtime_address) + }; + self.controller + .update_pool(view, tokio::time::Instant::now()); + } + + /// A supervisor stream connected or ended. A new supervisor process loses + /// the routes of the one before it. + fn membership_changed(&self) { + let connected = self + .controller + .connected_members() + .into_iter() + .filter(|member| member.member_id == MEMBER_ID && !member.leaving) + .max_by_key(|member| member.connected_at_ms) + .map(|member| member.process_id); + let Some(process_id) = connected else { + return; + }; + let changed = { + let mut state = lock(&self.state); + if state.process_id.as_deref() == Some(process_id.as_str()) { + false + } else { + state.process_id = Some(process_id.clone()); + state + .routes + .retain(|_, entry| entry.process_id == process_id); + true + } + }; + if changed { + info!(process = %process_id, "vm driver: shared supervisor connected"); + self.publish(); + self.process.send_replace(Some(process_id)); + } + } + + /// The supervisor process exited: every route it ran is lost. + fn process_exited(&self) { + { + let mut state = lock(&self.state); + state.process_id = None; + state.routes.clear(); + } + self.publish(); + self.process.send_replace(None); + } +} + +/// One generation's launch material for the shared supervisor: what a +/// dedicated supervisor receives as files and environment. +pub struct InstanceLaunch { + pub route: String, + pub sandbox_id: String, + pub sandbox_name: String, + /// Supervisor-side descriptor using the routed transport for `route`. + pub runtime_descriptor: openshell_sandbox_backend::boundary_protocol::SandboxRuntimeDescriptor, + pub auth: openshell_core::jwt::SupervisorAuthBundle, + pub main_process_spec: String, + pub workdir: Option, + pub container_image: String, +} + +impl InstanceLaunch { + /// Validate the registration and encode it as an assignment, with the + /// credential epoch of its launch term. + pub(crate) fn into_assignment(self) -> Result<(SandboxInstanceAssignment, u64), String> { + let auth_epoch = self.auth.auth_epoch.get(); + let registration = openshell_supervisor_control::SandboxInstanceRegistration { + route: self.route, + sandbox_id: self.sandbox_id, + sandbox_name: self.sandbox_name, + runtime_descriptor: self.runtime_descriptor, + auth: self.auth, + main_process_spec: self.main_process_spec, + workdir: self.workdir, + container_image: self.container_image, + proxy_ca: generate_proxy_ca()?, + trace_context: openshell_supervisor_control::RegistrationTraceContext::current(), + }; + registration + .validate() + .map_err(|error| format!("shared supervisor launch material: {error}"))?; + let assignment = registration + .to_assignment() + .map_err(|error| format!("shared supervisor launch material: {error}"))?; + Ok((assignment, auth_epoch)) + } +} + +/// A proxy interception CA for one generation. A dedicated supervisor makes +/// its own; a shared one receives it with the launch material. +fn generate_proxy_ca() -> Result { + use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose}; + let key = openshell_crypto::pki::generate_keypair() + .map_err(|error| format!("generate proxy CA key: {error}"))?; + let mut params = CertificateParams::default(); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params + .distinguished_name + .push(DnType::CommonName, "OpenShell Sandbox CA"); + params + .distinguished_name + .push(DnType::OrganizationName, "OpenShell"); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let certificate = openshell_crypto::pki::self_signed(params, &key) + .map_err(|error| format!("generate proxy CA certificate: {error}"))?; + Ok(openshell_supervisor_control::ProxyCaMaterial { + certificate_pem: certificate.pem(), + private_key_pem: openshell_supervisor_control::SecretPem::new( + key.serialize_pem() + .map_err(|error| format!("export proxy CA key: {error}"))?, + ), + }) +} + +/// The single-member pool view of `state`. +fn pool_view(state: &HostState, runtime_address: SocketAddr) -> PoolView { + let mut view = PoolView::default(); + if let Some(process_id) = &state.process_id { + view.members.push(MemberView { + member_id: MEMBER_ID.to_string(), + process_id: process_id.clone(), + runtime_address: runtime_address.to_string(), + leaving: false, + }); + } + for (route, entry) in &state.routes { + view.owners.insert( + route.clone(), + InstanceOwner { + member_id: MEMBER_ID.to_string(), + process_id: entry.process_id.clone(), + auth_epoch: entry.auth_epoch, + supervisor_instance_id: None, + takeover: None, + }, + ); + if !entry.withdrawn { + view.desired.insert(route.clone()); + view.assignments + .insert(route.clone(), entry.assignment.clone()); + } + } + view +} + +// --- the supervisor process --------------------------------------------- + +struct SupervisorCommand { + binary: PathBuf, + dir: PathBuf, + session_root: PathBuf, + assignment_endpoint: String, + token_path: PathBuf, + /// The gateway's CA, for the sandbox sessions when the gateway uses TLS. + gateway_ca: Option, + gateway_tls_server_name: Option, + runtime_address: SocketAddr, + health_address: SocketAddr, + environment: Vec<(String, String)>, + args: Vec, +} + +impl SupervisorCommand { + fn command(&self) -> Result { + let log = |name: &str| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(self.dir.join(name)) + .map_err(|error| format!("open shared supervisor log {name}: {error}")) + }; + let mut command = Command::new(&self.binary); + command + .env_clear() + .kill_on_drop(true) + .stdin(std::process::Stdio::null()) + .stdout(log("supervisor.log")?) + .stderr(log("supervisor.err.log")?) + .arg("--mode") + .arg("shared") + .arg("--gateway-endpoint") + .arg(&self.assignment_endpoint) + .arg("--address") + .arg(self.health_address.to_string()) + .arg("--token-file") + .arg(&self.token_path) + .arg("--runtime-listen") + .arg(self.runtime_address.to_string()) + .arg("--session-root") + .arg(&self.session_root) + .arg("--pool-member-id") + .arg(MEMBER_ID) + .arg("--pool-advertise-ip") + .arg(self.runtime_address.ip().to_string()) + .arg("--pool-max-instances") + .arg(MAX_INSTANCES.to_string()) + .args(&self.args) + .envs(self.environment.iter().map(|(key, value)| (key, value))); + if let Some(ca) = &self.gateway_ca { + command.env(openshell_core::sandbox_env::TLS_CA, ca); + } + if let Some(name) = &self.gateway_tls_server_name { + command.env(openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME, name); + } + // SAFETY: the closure only calls the async-signal-safe prctl(2). + #[cfg(target_os = "linux")] + #[allow(unsafe_code)] + unsafe { + command.pre_exec(|| { + nix::sys::prctl::set_pdeathsig(nix::sys::signal::Signal::SIGKILL) + .map_err(std::io::Error::other) + }); + } + Ok(command) + } +} + +/// Run the shared supervisor, restarting it when it exits, until the host is +/// dropped. +async fn keep_supervisor(command: SupervisorCommand, host: std::sync::Weak) { + let mut backoff = RESPAWN_BACKOFF_MIN; + loop { + if host.strong_count() == 0 { + return; + } + let started = tokio::time::Instant::now(); + let result = match command.command() { + Ok(mut command) => match command.spawn() { + Ok(mut child) => { + info!( + pid = child.id().unwrap_or(0), + "vm driver: shared supervisor process started" + ); + child + .wait() + .await + .map(|status| status.to_string()) + .map_err(|error| error.to_string()) + } + Err(error) => Err(format!( + "start shared supervisor '{}': {error}", + command.as_std().get_program().to_string_lossy() + )), + }, + Err(error) => Err(error), + }; + let Some(live) = host.upgrade() else { + return; + }; + let stderr = log_tail(&command.dir.join("supervisor.err.log")); + match result { + Ok(status) => { + warn!(%status, stderr = stderr.unwrap_or_default(), "vm driver: shared supervisor exited; its sandboxes are lost"); + } + Err(error) => warn!(%error, "vm driver: shared supervisor could not run"), + } + live.process_exited(); + drop(live); + if started.elapsed() >= RESPAWN_STABLE_AFTER { + backoff = RESPAWN_BACKOFF_MIN; + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(RESPAWN_BACKOFF_MAX); + } +} + +async fn watch_membership(host: std::sync::Weak) { + let Some(mut changes) = host + .upgrade() + .map(|host| host.controller.membership_changes()) + else { + return; + }; + while changes.changed().await.is_ok() { + let Some(host) = host.upgrade() else { + return; + }; + host.membership_changed(); + } +} + +// --- the assignment stream ---------------------------------------------- + +#[derive(Clone)] +struct HostService { + controller: SupervisorHostController, + tokens: Arc>, + /// The driver's own uid; only its processes may attach. + uid: u32, +} + +#[tonic::async_trait] +impl SupervisorHost for HostService { + type AttachStream = Pin< + Box> + Send + 'static>, + >; + + async fn attach( + &self, + request: Request>, + ) -> Result, Status> { + // The socket sits in a private directory; the peer check and the + // token are defense in depth. + let peer_uid = request + .extensions() + .get::() + .and_then(|info| info.peer_cred) + .map(|credentials| credentials.uid()); + if peer_uid != Some(self.uid) { + return Err(Status::permission_denied( + "the shared supervisor must run as the driver's user", + )); + } + let bearer = request + .metadata() + .get("authorization") + .and_then(|value| value.to_str().ok()) + .map(|value| { + value + .strip_prefix("Bearer ") + .unwrap_or(value) + .trim() + .to_string() + }) + .ok_or_else(|| Status::unauthenticated("supervisor token required"))?; + let identity = lock(&self.tokens) + .verify(&bearer, unix_seconds()) + .ok_or_else(|| Status::unauthenticated("unknown or expired supervisor token"))?; + let (member_id, outbound) = self + .controller + .attach(identity, request.into_inner(), |_, _| None) + .await?; + if member_id != MEMBER_ID { + warn!(%member_id, "vm driver: an unexpected pool member attached to the shared supervisor socket"); + } + Ok(Response::new(Box::pin(outbound))) + } +} + +/// Serve the assignment stream on the driver's private Unix socket. +async fn serve_assignments(listener: tokio::net::UnixListener, service: HostService) { + let (connections, incoming) = + tokio::sync::mpsc::channel::>(16); + let accept = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, _)) => { + if connections.send(Ok(stream)).await.is_err() { + return; + } + } + Err(error) => { + warn!(%error, "vm driver: shared supervisor socket accept failed"); + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + } + }); + let result = tonic::transport::Server::builder() + .add_service(SupervisorHostServer::new(service)) + .serve_with_incoming(tokio_stream::wrappers::ReceiverStream::new(incoming)) + .await; + accept.abort(); + if let Err(error) = result { + warn!(%error, "vm driver: shared supervisor assignment server stopped"); + } +} + +// --- supervisor tokens ------------------------------------------------------ + +/// One minted supervisor token. Only this driver verifies it, by comparing it +/// with what it minted, so it is JWT-shaped (the supervisor reads its `exp`) +/// but its signature is random. +struct Issued { + token: String, + id: String, + expires_at: i64, +} + +impl Issued { + fn mint(now: i64) -> Result { + let encode = |bytes: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes); + let random = |what: &str| { + openshell_crypto::random_bytes::<32>() + .map_err(|error| format!("generate supervisor token {what}: {error}")) + }; + let id = encode(&random("id")?[..16]); + let expires_at = now.saturating_add(i64::try_from(TOKEN_TTL.as_secs()).unwrap_or(i64::MAX)); + let header = encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = encode( + serde_json::json!({ + "sub": TOKEN_SUBJECT, + "jti": id, + "iat": now, + "exp": expires_at, + }) + .to_string() + .as_bytes(), + ); + let signature = encode(&random("signature")?); + Ok(Self { + token: format!("{header}.{payload}.{signature}"), + id, + expires_at, + }) + } +} + +struct Tokens { + current: Issued, + previous: Option, +} + +impl Tokens { + fn new() -> Result { + Ok(Self { + current: Issued::mint(unix_seconds())?, + previous: None, + }) + } + + fn renew(&mut self) -> Result<(), String> { + let next = Issued::mint(unix_seconds())?; + self.previous = Some(std::mem::replace(&mut self.current, next)); + Ok(()) + } + + /// The identity of an unexpired token this driver minted. + fn verify(&self, bearer: &str, now: i64) -> Option { + std::iter::once(&self.current) + .chain(self.previous.as_ref()) + .find(|issued| issued.expires_at > now && constant_time_eq(&issued.token, bearer)) + .map(|issued| HostIdentity { + subject: TOKEN_SUBJECT.to_string(), + token_id: issued.id.clone(), + expires_at: issued.expires_at, + }) + } +} + +async fn renew_tokens(tokens: Arc>, path: PathBuf) { + loop { + tokio::time::sleep(TOKEN_RENEWAL).await; + let renewed = { + let mut tokens = lock(&tokens); + tokens.renew().map(|()| tokens.current.token.clone()) + }; + match renewed.and_then(|token| write_private_file(&path, token.as_bytes())) { + Ok(()) => debug!("vm driver: renewed the shared supervisor token"), + Err(error) => warn!(%error, "vm driver: renewing the shared supervisor token failed"), + } + } +} + +/// The last few KiB of a log, for a diagnostic. +fn log_tail(path: &Path) -> Option { + const LIMIT: usize = 4096; + let bytes = std::fs::read(path).ok()?; + let tail = String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(LIMIT)..]) + .trim() + .to_string(); + (!tail.is_empty()).then_some(tail) +} + +fn constant_time_eq(left: &str, right: &str) -> bool { + left.len() == right.len() + && left + .bytes() + .zip(right.bytes()) + .fold(0_u8, |difference, (a, b)| difference | (a ^ b)) + == 0 +} + +// --- helpers ------------------------------------------------------------------ + +fn lock(mutex: &StdMutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn unix_seconds() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| { + i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX) + }) +} + +/// A loopback TCP port free at the moment of the call. The supervisor binds +/// it right after; it needs a concrete port because it advertises it. +fn free_port() -> Result { + std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .and_then(|listener| listener.local_addr()) + .map(|address| address.port()) + .map_err(|error| format!("find a free loopback port: {error}")) +} + +fn create_private_dir(path: &Path) -> Result<(), String> { + use std::os::unix::fs::{DirBuilderExt as _, PermissionsExt as _}; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path) + .and_then(|()| std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))) + .map_err(|error| format!("create {}: {error}", path.display())) +} + +/// Restrict a socket the driver created to its own user. +fn set_private_mode(path: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) + .map_err(|error| format!("restrict {}: {error}", path.display())) +} + +/// Write `contents` to `path` with mode 0600, replacing it atomically. +fn write_private_file(path: &Path, contents: &[u8]) -> Result<(), String> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt as _; + let temporary = path.with_extension("tmp"); + let _ = std::fs::remove_file(&temporary); + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .and_then(|mut file| file.write_all(contents).and_then(|()| file.sync_all())) + .and_then(|()| std::fs::rename(&temporary, path)) + .map_err(|error| format!("write {}: {error}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(route: &str, process_id: &str, withdrawn: bool) -> (String, RouteEntry) { + ( + route.to_string(), + RouteEntry { + assignment: SandboxInstanceAssignment { + route: route.to_string(), + sandbox_id: format!("sandbox-{route}"), + generation: "generation-1".to_string(), + launch_material: b"{}".to_vec(), + takeover: None, + }, + auth_epoch: 1, + process_id: process_id.to_string(), + withdrawn, + }, + ) + } + + #[test] + fn pool_view_owns_every_route_and_desires_only_live_ones() { + let state = HostState { + process_id: Some("process-1".to_string()), + routes: BTreeMap::from([ + entry("route-a", "process-1", false), + entry("route-b", "process-1", true), + ]), + }; + let address: SocketAddr = "127.0.0.1:5600".parse().unwrap(); + let view = pool_view(&state, address); + assert_eq!(view.members.len(), 1); + assert_eq!(view.members[0].member_id, MEMBER_ID); + assert_eq!(view.members[0].process_id, "process-1"); + assert_eq!(view.members[0].runtime_address, "127.0.0.1:5600"); + assert_eq!(view.owners.len(), 2); + assert!( + view.owners + .values() + .all(|owner| owner.process_id == "process-1" + && owner.takeover.is_none() + && owner.supervisor_instance_id.is_none()) + ); + assert_eq!(view.desired.iter().collect::>(), ["route-a"]); + assert_eq!(view.assignments.keys().collect::>(), ["route-a"]); + } + + #[test] + fn pool_view_without_a_process_has_no_member() { + let view = pool_view(&HostState::default(), "127.0.0.1:1".parse().unwrap()); + assert!(view.members.is_empty()); + assert!(view.owners.is_empty()); + } + + #[test] + fn tokens_verify_only_what_was_minted_and_unexpired() { + let mut tokens = Tokens::new().unwrap(); + let now = unix_seconds(); + let first = tokens.current.token.clone(); + assert!(openshell_core::jwt::parse_exp_secs(&first).is_some_and(|exp| exp > now)); + assert_eq!(tokens.verify(&first, now).unwrap().subject, TOKEN_SUBJECT); + assert!(tokens.verify("not-a-token", now).is_none()); + assert!(tokens.verify(&first, tokens.current.expires_at).is_none()); + + tokens.renew().unwrap(); + let second = tokens.current.token.clone(); + assert_ne!(first, second); + // The previous token keeps working until it expires. + assert!(tokens.verify(&first, now).is_some()); + assert!(tokens.verify(&second, now).is_some()); + tokens.renew().unwrap(); + assert!(tokens.verify(&first, now).is_none()); + } + + #[test] + fn constant_time_eq_compares_whole_strings() { + assert!(constant_time_eq("abc", "abc")); + assert!(!constant_time_eq("abc", "abd")); + assert!(!constant_time_eq("abc", "abcd")); + } +}