diff --git a/Cargo.lock b/Cargo.lock index aead192302..c07ba7f4ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5263,6 +5263,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "tempfile", "thiserror 2.0.20", "tokio", "tokio-stream", diff --git a/crates/openshell-core/src/external_driver_socket.rs b/crates/openshell-core/src/external_driver_socket.rs index bad51bd76e..221ecd9745 100644 --- a/crates/openshell-core/src/external_driver_socket.rs +++ b/crates/openshell-core/src/external_driver_socket.rs @@ -14,6 +14,7 @@ use tokio_stream::Stream; /// Prepare and bind a private Unix socket owned by the current effective UID. pub fn bind_private(path: &Path) -> Result { + crate::unix_socket_path::check(path).map_err(|err| err.to_string())?; let parent = path .parent() .ok_or_else(|| format!("driver socket path '{}' has no parent", path.display()))?; @@ -193,6 +194,20 @@ mod tests { assert!(err.contains("must be a directory, not a symlink")); } + #[test] + fn bind_private_rejects_overlong_path_before_creating_parent() { + let temp_dir = tempfile::tempdir().expect("create temporary directory"); + let parent = temp_dir + .path() + .join("a".repeat(crate::unix_socket_path::MAX_LEN)); + + let err = bind_private(&parent.join("compute.sock")) + .expect_err("overlong socket path must be rejected"); + + assert!(err.contains("-byte limit"), "{err}"); + assert!(!parent.exists()); + } + #[test] fn bind_private_rejects_existing_non_socket() { let temp_dir = tempfile::tempdir().expect("create temporary directory"); diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 4bc48e01d1..66a23423e7 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -75,6 +75,7 @@ pub mod token_endpoint; pub mod token_grant_failure; pub mod transport_errors; pub mod upload; +pub use openshell_extension_core::unix_socket_path; pub use config::{ AppArmorProfile, Config, ExtensionBindingPolicy, GatewayAuditConfig, GatewayAuthConfig, diff --git a/crates/openshell-credential-issuer/src/embedded.rs b/crates/openshell-credential-issuer/src/embedded.rs index 16a3a9bb91..c934378a7d 100644 --- a/crates/openshell-credential-issuer/src/embedded.rs +++ b/crates/openshell-credential-issuer/src/embedded.rs @@ -959,6 +959,25 @@ namespace = "openshell" assert!(!parsed.backend_config.contains_key("transport")); } + #[test] + fn parse_uds_driver_rejects_overlong_socket_path() { + let socket_path_toml = toml_path(&test_absolute_path( + &"a".repeat(openshell_core::unix_socket_path::MAX_LEN), + )); + let err = parse_driver_table( + "vault", + &driver_table(&format!( + r#" +transport = "uds" +socket_path = {socket_path_toml} +"#, + )), + ) + .unwrap_err(); + + assert!(err.to_string().contains("-byte limit"), "{err}"); + } + #[test] fn parse_uds_driver_rejects_relative_command() { let socket_path_toml = toml_path(&test_absolute_path("openshell-enterprise-secrets.sock")); diff --git a/crates/openshell-credential-issuer/src/embedded/driver_config.rs b/crates/openshell-credential-issuer/src/embedded/driver_config.rs index 023a768ebc..b90f0db4c0 100644 --- a/crates/openshell-credential-issuer/src/embedded/driver_config.rs +++ b/crates/openshell-credential-issuer/src/embedded/driver_config.rs @@ -262,6 +262,11 @@ pub(super) fn parse_driver_table( "[openshell.credential_drivers.{driver_name}] socket_path must be absolute" ))); } + openshell_core::unix_socket_path::check(socket_path).map_err(|err| { + Error::config(format!( + "[openshell.credential_drivers.{driver_name}] socket_path: {err}" + )) + })?; if let Some(command) = command.as_ref() && !command.is_absolute() { diff --git a/crates/openshell-driver-kubernetes-secrets/src/main.rs b/crates/openshell-driver-kubernetes-secrets/src/main.rs index 15125fbfc0..54cefd7217 100644 --- a/crates/openshell-driver-kubernetes-secrets/src/main.rs +++ b/crates/openshell-driver-kubernetes-secrets/src/main.rs @@ -78,6 +78,7 @@ fn driver_config(args: &Args) -> toml::Table { } fn prepare_socket(socket_path: &Path) -> Result<()> { + openshell_core::unix_socket_path::check(socket_path).into_diagnostic()?; let parent = socket_path.parent().ok_or_else(|| { miette!( "credential driver socket path '{}' has no parent directory", diff --git a/crates/openshell-driver-vault/src/main.rs b/crates/openshell-driver-vault/src/main.rs index 6756a6a767..d1eb665528 100644 --- a/crates/openshell-driver-vault/src/main.rs +++ b/crates/openshell-driver-vault/src/main.rs @@ -130,6 +130,7 @@ fn insert_path(config: &mut toml::Table, key: &str, value: Option<&PathBuf>) { } fn prepare_socket(socket_path: &Path) -> Result<()> { + openshell_core::unix_socket_path::check(socket_path).into_diagnostic()?; let parent = socket_path.parent().ok_or_else(|| { miette!( "credential driver socket path '{}' has no parent directory", diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index ff2ed322e2..78258b9b41 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -68,7 +68,7 @@ By default `mise run gateway:vm`: `~/.config/openshell/gateways/vm-dev/metadata.json`. It does not modify the workspace `.env`. - Persists the gateway SQLite DB under `.cache/gateway-vm/gateway.db`. -- Places the VM driver state (per-sandbox `overlay.ext4`, image cache, and the private `run/` socket directories) under `/tmp/openshell-vm-driver-$USER-vm-dev/` so the AF_UNIX socket path stays under macOS `SUN_LEN`. +- Places the VM driver state (per-sandbox `overlay.ext4` and image cache) under `/tmp/openshell-vm-driver-$USER-vm-dev/`. - Writes `.cache/gateway-vm/gateway.toml` with `[openshell.gateway].driver_dir = "$PWD/target/debug"` so the freshly built `openshell-driver-vm` is used instead of an older installed copy from `~/.local/libexec/openshell`, `/usr/libexec/openshell`, or `/usr/local/libexec`. - Enables OTLP trace export, OCSF log export, and the agent trace relay only when `OPENSHELL_DEV_OTLP_ENDPOINT` names a collector, for example `http://127.0.0.1:4317`. Otherwise, it omits the OTLP configuration. @@ -166,7 +166,7 @@ Select the VM driver with `--compute-driver vm`, `OPENSHELL_COMPUTE_DRIVER=vm`, | Configuration key | Default | Purpose | |---|---|---| | `grpc_endpoint` | empty | Required. URL the native host supervisor uses to reach the gateway. Host loopback such as `http://127.0.0.1:` is valid. Legacy guest aliases are normalized to host loopback. This endpoint is never sent into the VM. | -| `state_dir` | `target/openshell-vm-driver` | Per-sandbox overlay disks, console logs, image cache, and the private `run//driver.sock` UDS, one directory per launch. Relative paths are resolved to absolute paths at driver startup. | +| `state_dir` | `target/openshell-vm-driver` | Per-sandbox overlay disks, console logs, and image cache. Relative paths are resolved to absolute paths at driver startup. | | `driver_dir` | unset | Deprecated in this table: set `driver_dir` in `[openshell.gateway]`. The directory is searched before the standard locations. | | `default_image` | OpenShell base image | Sandbox image used when a create request omits one. | | `bootstrap_image` | unset | VM runtime image used as the immutable bootstrap root disk. Falls back only to the operator-configured `default_image`; the driver refuses to start when both are empty. | @@ -283,8 +283,8 @@ RUST_LOG=openshell_server=debug,openshell_driver_vm=debug \ mise run gateway:vm ``` -The VM guest's serial console is appended to `//console.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/run//driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions and removed with the driver's handle. On clean shutdown, the gateway finishes its work through the driver, releases it with the launch protocol's `Shutdown` call, and waits up to ten seconds for it to flush telemetry and exit. It then falls back to `SIGTERM`, waits five seconds, force-kills the driver if necessary, and removes the socket. A stop signal that reaches the driver from elsewhere, such as a service manager signalling every process of the gateway's unit, is deferred until the gateway releases the driver, the gateway exits, or 30 seconds pass. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. -The VM serial console is appended to `/sandboxes//rootfs-console.log`. Host-supervisor stdout and stderr are written beside it as `supervisor.log` and `supervisor.err.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/run//driver.sock`; each launch gets its own directory under `run/`, created with owner-only permissions, and the gateway removes it on clean shutdown via `ManagedDriverProcess::drop`. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. +The VM guest's serial console is appended to `//console.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/tmp/os-driver-/driver.sock`; each launch gets its own directory under `/tmp`, created with owner-only permissions and removed with the driver's handle. On clean shutdown, the gateway finishes its work through the driver, releases it with the launch protocol's `Shutdown` call, and waits up to ten seconds for it to flush telemetry and exit. It then falls back to `SIGTERM`, waits five seconds, force-kills the driver if necessary, and removes the socket. A stop signal that reaches the driver from elsewhere, such as a service manager signalling every process of the gateway's unit, is deferred until the gateway releases the driver, the gateway exits, or 30 seconds pass. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. +The VM serial console is appended to `/sandboxes//rootfs-console.log`. Host-supervisor stdout and stderr are written beside it as `supervisor.log` and `supervisor.err.log`. Sandbox IDs must match `[A-Za-z0-9._-]{1,128}` before the driver uses them in host paths. The gateway-owned compute-driver socket lives at `/tmp/os-driver-/driver.sock`; each launch gets its own directory under `/tmp`, created with owner-only permissions, and the gateway removes it on clean shutdown via `ManagedDriverProcess::drop`. UDS clients must match the driver UID and provide the expected gateway process PID by default. Standalone same-UID UDS mode requires the explicit `--allow-same-uid-peer` development flag. TCP mode is disabled by default because it is unauthenticated; use `--allow-unauthenticated-tcp --bind-address 127.0.0.1:50061` only for local development. ## Network isolation diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..ab8dc63e4a 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1470,7 +1470,9 @@ impl VmDriver { .env(openshell_core::sandbox_env::SANDBOX, &sandbox.name) .env( openshell_core::sandbox_env::SSH_SOCKET_PATH, - sandbox_socket_dir(&self.socket_root, &sandbox.id).join("ssh.sock"), + sandbox_socket_dir(&self.socket_root, &sandbox.id) + .map_err(|err| Status::internal(format!("sandbox socket dir: {err}")))? + .join("ssh.sock"), ) .env( openshell_core::sandbox_env::PROXY_TLS_DIR, @@ -2067,10 +2069,10 @@ impl VmDriver { } let console_output = state_dir.join("rootfs-console.log"); - create_sandbox_socket_dir(&self.socket_root_fd, &self.socket_root, &sandbox.id) - .map_err(|err| Status::internal(format!("create socket dir failed: {err}")))?; let control_socket = - sandbox_socket_dir(&self.socket_root, &sandbox.id).join(VM_CONTROL_SOCKET); + create_sandbox_socket_dir(&self.socket_root_fd, &self.socket_root, &sandbox.id) + .map_err(|err| Status::internal(format!("create socket dir failed: {err}")))? + .join(VM_CONTROL_SOCKET); let session_id = launch_authentication.supervisor.session_id; let channel_tls = generate_sandbox_tls_material(session_id) .map_err(|error| Status::internal(error.to_string()))?; @@ -6793,11 +6795,20 @@ async fn restrict_owner_only_dir(_path: &Path) -> Result<(), std::io::Error> { } const SOCKET_ROOT_ALLOC_RETRIES: usize = 16; -/// macOS `sun_path` is 104 bytes including the NUL terminator. -const MAX_SUN_PATH_LEN: usize = 103; -fn sandbox_socket_dir(socket_root: &Path, sandbox_id: &str) -> PathBuf { - socket_root.join(sandbox_id) +/// Name of a sandbox's socket directory under the socket root. Sandbox IDs can +/// be 128 bytes, so a fixed-length digest keeps socket paths short. +fn sandbox_socket_leaf(sandbox_id: &str) -> Result { + let digest = openshell_crypto::sha256(sandbox_id.as_bytes()).map_err(std::io::Error::other)?; + let mut leaf = String::with_capacity(32); + for byte in &digest[..16] { + write!(&mut leaf, "{byte:02x}").expect("writing to String cannot fail"); + } + Ok(leaf) +} + +fn sandbox_socket_dir(socket_root: &Path, sandbox_id: &str) -> Result { + Ok(socket_root.join(sandbox_socket_leaf(sandbox_id)?)) } fn allocate_socket_root() -> Result<(PathBuf, OwnedFd), std::io::Error> { @@ -6846,34 +6857,34 @@ fn create_sandbox_socket_dir( socket_root: &Path, sandbox_id: &str, ) -> Result { - let longest = socket_root.join(sandbox_id).join(VM_CONTROL_SOCKET); - if longest.as_os_str().len() > MAX_SUN_PATH_LEN { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "socket path {} exceeds sun_path limit ({MAX_SUN_PATH_LEN} bytes)", - longest.display() - ), - )); - } - match rustix::fs::mkdirat(root_fd, sandbox_id, rustix::fs::Mode::from_raw_mode(0o700)) { + let leaf = sandbox_socket_leaf(sandbox_id)?; + let dir = socket_root.join(&leaf); + openshell_core::unix_socket_path::check(&dir.join(VM_CONTROL_SOCKET))?; + match rustix::fs::mkdirat( + root_fd, + leaf.as_str(), + rustix::fs::Mode::from_raw_mode(0o700), + ) { Ok(()) | Err(rustix::io::Errno::EXIST) => {} Err(e) => return Err(e.into()), } - Ok(socket_root.join(sandbox_id)) + Ok(dir) } fn remove_sandbox_socket_dir(root_fd: &OwnedFd, sandbox_id: &str) { + let Ok(leaf) = sandbox_socket_leaf(sandbox_id) else { + return; + }; if let Ok(leaf_fd) = rustix::fs::openat( root_fd, - sandbox_id, + leaf.as_str(), rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::NOFOLLOW, rustix::fs::Mode::empty(), ) { let _ = rustix::fs::unlinkat(&leaf_fd, VM_CONTROL_SOCKET, rustix::fs::AtFlags::empty()); let _ = rustix::fs::unlinkat(&leaf_fd, "ssh.sock", rustix::fs::AtFlags::empty()); } - let _ = rustix::fs::unlinkat(root_fd, sandbox_id, rustix::fs::AtFlags::REMOVEDIR); + let _ = rustix::fs::unlinkat(root_fd, leaf.as_str(), rustix::fs::AtFlags::REMOVEDIR); } #[allow(clippy::result_large_err)] @@ -8337,7 +8348,8 @@ mod tests { use tonic::Code; fn test_socket_root() -> (PathBuf, Arc) { - let dir = std::env::temp_dir().join(format!( + // Production socket roots live under /tmp; macOS TMPDIR is too long. + let dir = Path::new("/tmp").join(format!( "os-test-{:016x}", u64::from_ne_bytes(openshell_crypto::random_bytes::<8>().expect("test entropy")) )); @@ -10568,20 +10580,23 @@ mod tests { } #[test] - fn create_sandbox_socket_dir_rejects_over_long_ids() { + fn create_sandbox_socket_dir_accepts_longest_sandbox_id() { let (root, fd) = test_socket_root(); - let err = create_sandbox_socket_dir(&fd, &root, &"x".repeat(128)).unwrap_err(); - assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); - assert!(!root.join("x".repeat(128)).exists()); + let sandbox_id = "x".repeat(128); + let dir = create_sandbox_socket_dir(&fd, &root, &sandbox_id).unwrap(); + assert!(dir.is_dir()); + assert_eq!(dir, sandbox_socket_dir(&root, &sandbox_id).unwrap()); + std::os::unix::net::UnixListener::bind(dir.join(VM_CONTROL_SOCKET)).unwrap(); + remove_sandbox_socket_dir(&fd, &sandbox_id); + assert!(!dir.exists()); let _ = std::fs::remove_dir_all(root); - } - #[test] - fn sandbox_socket_dir_fits_macos_sun_path() { - let sandbox_id = "3eb2ad45-bead-4c2e-bd10-1a4a7f3a2721"; + let sandbox_id = "x".repeat(128); let worst_root = "/tmp/os-4294967295-00000000000000000000000000000000"; - let control = sandbox_socket_dir(Path::new(worst_root), sandbox_id).join(VM_CONTROL_SOCKET); - let ssh = sandbox_socket_dir(Path::new(worst_root), sandbox_id).join("ssh.sock"); + let dir = sandbox_socket_dir(Path::new(worst_root), &sandbox_id).unwrap(); + let control = dir.join(VM_CONTROL_SOCKET); + let ssh = dir.join("ssh.sock"); + assert_ne!(dir, sandbox_socket_dir(Path::new(worst_root), "y").unwrap()); assert!( control.as_os_str().len() < 104, "control socket path exceeds macOS sun_path: {}", diff --git a/crates/openshell-driver-vm/src/listener.rs b/crates/openshell-driver-vm/src/listener.rs index 04283b7482..8e11c9cce5 100644 --- a/crates/openshell-driver-vm/src/listener.rs +++ b/crates/openshell-driver-vm/src/listener.rs @@ -29,6 +29,7 @@ pub async fn shutdown_signal() { } pub fn prepare_compute_driver_socket(socket_path: &Path) -> Result<(), String> { + openshell_core::unix_socket_path::check(socket_path).map_err(|err| err.to_string())?; let Some(parent) = socket_path.parent() else { return Err(format!( "vm compute driver socket path '{}' has no parent directory", diff --git a/crates/openshell-driver-vm/src/main.rs b/crates/openshell-driver-vm/src/main.rs index 407ad3e150..f5ca5bfda9 100644 --- a/crates/openshell-driver-vm/src/main.rs +++ b/crates/openshell-driver-vm/src/main.rs @@ -452,6 +452,7 @@ fn compute_driver_listen_mode(args: &Args) -> std::result::Result Result<(), TransportError if !matches!(&config.server_trust, ExtensionServerTrust::PlatformRoots) && !is_https { return Err(TransportError::CustomCaRequiresHttps); } - if let Some(path) = config.endpoint.strip_prefix("unix://") - && (path.is_empty() || !PathBuf::from(path).is_absolute()) - { - return Err(TransportError::InvalidUnixPath); + if let Some(path) = config.endpoint.strip_prefix("unix://") { + if path.is_empty() || !PathBuf::from(path).is_absolute() { + return Err(TransportError::InvalidUnixPath); + } + crate::unix_socket_path::check(path.as_ref()).map_err(TransportError::UnixPathTooLong)?; } Ok(()) } @@ -271,7 +274,7 @@ mod tests { } #[test] - fn rejects_unsupported_schemes_and_relative_unix_paths() { + fn rejects_unsupported_schemes_and_invalid_unix_paths() { assert!(matches!( validate_config(&ExtensionChannelConfig::new("tcp://middleware:50051")), Err(TransportError::UnsupportedScheme) @@ -280,6 +283,11 @@ mod tests { validate_config(&ExtensionChannelConfig::new("unix://relative.sock")), Err(TransportError::InvalidUnixPath) )); + let long = format!("unix:///{}", "a".repeat(crate::unix_socket_path::MAX_LEN)); + assert!(matches!( + validate_config(&ExtensionChannelConfig::new(long)), + Err(TransportError::UnixPathTooLong(_)) + )); } #[test] diff --git a/crates/openshell-extension-core/src/unix_socket_path.rs b/crates/openshell-extension-core/src/unix_socket_path.rs new file mode 100644 index 0000000000..daa3f1ee83 --- /dev/null +++ b/crates/openshell-extension-core/src/unix_socket_path.rs @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Unix domain socket pathname limit. + +use std::io; +use std::path::Path; + +/// Longest Unix socket pathname, in bytes, without the terminating NUL. +/// +/// `sockaddr_un.sun_path` holds 108 bytes on Linux and 104 on macOS. +/// Abstract socket addresses have different limits and are not pathnames. +pub const MAX_LEN: usize = if cfg!(target_os = "linux") { 107 } else { 103 }; + +/// Reject a socket pathname that does not fit in `sockaddr_un.sun_path`. +/// +/// Call it before creating directories, removing a stale socket or retrying a +/// connection. The error names the path and its length. The kernel error says +/// only that the path must be shorter than `SUN_LEN`. +pub fn check(path: &Path) -> io::Result<()> { + let len = path.as_os_str().len(); + if len <= MAX_LEN { + return Ok(()); + } + Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!( + "Unix socket path '{}' is {len} bytes, over the {MAX_LEN}-byte limit on this platform", + path.display() + ), + )) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_the_limit_and_rejects_one_byte_more() { + let at_limit = format!("/{}", "a".repeat(MAX_LEN - 1)); + check(Path::new(&at_limit)).unwrap(); + + let over = format!("{at_limit}a"); + let error = check(Path::new(&over)).unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidInput); + assert!(error.to_string().contains(&over), "{error}"); + assert!( + error.to_string().contains(&format!( + "{} bytes, over the {MAX_LEN}-byte limit", + MAX_LEN + 1 + )), + "{error}" + ); + + #[cfg(unix)] + { + // macOS TMPDIR is too long to leave room for the probe name. + let dir = tempfile::Builder::new() + .prefix("os-sock-len-") + .tempdir_in("/tmp") + .unwrap(); + let prefix = dir.path().join("s"); + let fill = MAX_LEN - prefix.as_os_str().len(); + let at_limit = format!("{}{}", prefix.display(), "a".repeat(fill)); + let bound = std::os::unix::net::UnixListener::bind(&at_limit); + let over = std::os::unix::net::UnixListener::bind(format!("{at_limit}b")); + bound.unwrap(); + over.unwrap_err(); + } + } +} diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs index 29a35ee813..d0d0652e92 100644 --- a/crates/openshell-gateway/src/launcher.rs +++ b/crates/openshell-gateway/src/launcher.rs @@ -157,48 +157,55 @@ impl LaunchDir { } } -/// Create a private directory for one launch's socket under `base`. +/// Create a private socket directory under `base`, or under `/tmp` when absent. /// /// Every launch gets its own directory, so a launch only configures and /// cleans up its own child: a second startup under the same account cannot /// remove a running driver's socket. The directory is removed with the /// driver's handle once the launch owns it, and by the returned guard until /// then. -pub fn prepare_socket(base: &Path) -> Result { - let euid = rustix::process::geteuid().as_raw(); - std::fs::create_dir_all(base).map_err(|error| { - Error::execution(format!( - "failed to create compute driver socket dir '{}': {error}", - base.display() - )) - })?; - let metadata = std::fs::symlink_metadata(base).map_err(|error| { - Error::execution(format!( - "failed to stat socket dir '{}': {error}", - base.display() - )) - })?; - if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() { - return Err(Error::execution(format!( - "compute driver socket dir '{}' is not a plain directory", - base.display() - ))); - } - if metadata.uid() != euid { - return Err(Error::execution(format!( - "compute driver socket dir '{}' is owned by uid {} but the gateway runs as {euid}", - base.display(), - metadata.uid() - ))); +pub fn prepare_socket(base: Option<&Path>) -> Result { + if let Some(base) = base { + let euid = rustix::process::geteuid().as_raw(); + std::fs::create_dir_all(base).map_err(|error| { + Error::execution(format!( + "failed to create compute driver socket dir '{}': {error}", + base.display() + )) + })?; + let metadata = std::fs::symlink_metadata(base).map_err(|error| { + Error::execution(format!( + "failed to stat socket dir '{}': {error}", + base.display() + )) + })?; + if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() { + return Err(Error::execution(format!( + "compute driver socket dir '{}' is not a plain directory", + base.display() + ))); + } + if metadata.uid() != euid { + return Err(Error::execution(format!( + "compute driver socket dir '{}' is owned by uid {} but the gateway runs as {euid}", + base.display(), + metadata.uid() + ))); + } + std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o700)).map_err( + |error| { + Error::execution(format!( + "failed to restrict socket dir '{}': {error}", + base.display() + )) + }, + )?; } - std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o700)).map_err(|error| { - Error::execution(format!( - "failed to restrict socket dir '{}': {error}", - base.display() - )) - })?; + // Use /tmp explicitly: macOS TMPDIR can exceed the socket path limit. + let prefix = if base.is_none() { "os-driver-" } else { "" }; + let base = base.unwrap_or_else(|| Path::new("/tmp")); let dir = tempfile::Builder::new() - .prefix("") + .prefix(prefix) .tempdir_in(base) .map_err(|error| { Error::execution(format!( @@ -215,6 +222,8 @@ pub fn prepare_socket(base: &Path) -> Result { }, )?; let socket = dir.path().join(SOCKET_NAME); + openshell_core::unix_socket_path::check(&socket) + .map_err(|error| Error::config(error.to_string()))?; Ok(LaunchDir { dir: Some(dir), socket, @@ -355,8 +364,8 @@ pub struct LaunchRequest<'a> { pub binary: &'a Path, /// The driver table as TOML text. pub table: &'a str, - /// A directory the gateway owns, made private (`0700`) for the socket. - pub socket_dir: &'a Path, + /// A gateway-owned base directory, or `None` for a short path under `/tmp`. + pub socket_dir: Option<&'a Path>, pub log_level: &'a str, } @@ -542,7 +551,7 @@ pub async fn launch( request.name.to_string(), request.binary.to_path_buf(), request.table.to_string(), - request.socket_dir.to_path_buf(), + request.socket_dir.map(Path::to_path_buf), request.log_level.to_string(), ); let outcome = tokio::task::spawn_blocking(move || { @@ -550,7 +559,7 @@ pub async fn launch( name: &owned.0, binary: &owned.1, table: &owned.2, - socket_dir: &owned.3, + socket_dir: owned.3.as_deref(), log_level: &owned.4, }) }) diff --git a/crates/openshell-gateway/src/launcher/tests.rs b/crates/openshell-gateway/src/launcher/tests.rs index 348e8709d1..af972fdd7b 100644 --- a/crates/openshell-gateway/src/launcher/tests.rs +++ b/crates/openshell-gateway/src/launcher/tests.rs @@ -36,7 +36,7 @@ async fn run(binary: &Path, table: &str, dir: &Path) -> Result { name: "fake", binary, table, - socket_dir: &dir.join("run"), + socket_dir: Some(&dir.join("run")), log_level: "info", }, ConfigureRequest::default().into(), @@ -291,13 +291,13 @@ fn a_launch_directory_is_removed_unless_it_is_kept() { let dir = tempfile::tempdir().unwrap(); let base = dir.path().join("run"); - let dropped = prepare_socket(&base).unwrap(); + let dropped = prepare_socket(Some(&base)).unwrap(); let dropped_dir = dropped.socket().parent().unwrap().to_path_buf(); assert!(dropped_dir.exists()); drop(dropped); assert!(!dropped_dir.exists(), "a dropped launch left its directory"); - let kept = prepare_socket(&base).unwrap(); + let kept = prepare_socket(Some(&base)).unwrap(); let socket = kept.keep(); assert!(socket.parent().unwrap().exists()); } @@ -311,7 +311,7 @@ fn a_launch_that_cannot_spawn_leaves_no_directory_behind() { name: "fake", binary: Path::new("/nonexistent/openshell-driver-fake"), table: "", - socket_dir: &base, + socket_dir: Some(&base), log_level: "info", }) .err() @@ -354,8 +354,8 @@ fn every_launch_gets_its_own_private_socket_directory() { std::fs::create_dir(&base).unwrap(); std::fs::set_permissions(&base, std::fs::Permissions::from_mode(0o755)).unwrap(); - let first = prepare_socket(&base).unwrap(); - let second = prepare_socket(&base).unwrap(); + let first = prepare_socket(Some(&base)).unwrap(); + let second = prepare_socket(Some(&base)).unwrap(); assert_ne!( first.socket().parent(), @@ -380,7 +380,7 @@ fn every_launch_gets_its_own_private_socket_directory() { // Another launch's socket is never touched. std::fs::write(first.socket(), b"first").unwrap(); - prepare_socket(&base).unwrap(); + prepare_socket(Some(&base)).unwrap(); assert_eq!(std::fs::read(first.socket()).unwrap(), b"first"); } @@ -671,7 +671,7 @@ async fn an_unreachable_backend_is_retried_a_bounded_number_of_times() { name: "fake", binary: &binary, table: "", - socket_dir: &dir.path().join("run"), + socket_dir: Some(&dir.path().join("run")), log_level: "info", }, ConfigureRequest::default().into(), @@ -703,7 +703,7 @@ async fn an_invalid_table_or_a_crash_is_not_retried() { name: "fake", binary: &binary, table: "", - socket_dir: &dir.path().join(format!("{name}-run")), + socket_dir: Some(&dir.path().join(format!("{name}-run"))), log_level: "info", }, ConfigureRequest::default().into(), diff --git a/crates/openshell-gateway/src/local_driver.rs b/crates/openshell-gateway/src/local_driver.rs index d79815d8d8..51eecd18aa 100644 --- a/crates/openshell-gateway/src/local_driver.rs +++ b/crates/openshell-gateway/src/local_driver.rs @@ -124,7 +124,7 @@ impl LocalDriver { name: self.name, binary: &binary, table: &plan.table, - socket_dir, + socket_dir: Some(socket_dir), log_level: context.gateway_log_level, }) { Ok(StartOutcome::Started(started)) => { @@ -160,7 +160,7 @@ impl LocalDriver { name, binary: &binary, table: &plan.table, - socket_dir, + socket_dir: Some(socket_dir), log_level: gateway_log_level, }; let outcome = match self.retry_unavailable { diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index cd388c85d1..6f988ba316 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -17,7 +17,6 @@ use openshell_server::AcquiredRemoteDriverEndpoint; use crate::launcher::{self, ConfigureInputs, LaunchOutcome, LaunchRequest, PreflightFailure}; const DRIVER_BIN_NAME: &str = "openshell-driver-vm"; -const COMPUTE_DRIVER_SOCKET_RUN_DIR: &str = "run"; const DRIVER_BIN_HINT: &str = "set driver_dir in [openshell.gateway], install it 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"; /// The gateway's view of the `[openshell.drivers.vm]` table. @@ -25,8 +24,7 @@ const DRIVER_BIN_HINT: &str = "set driver_dir in [openshell.gateway], install it pub struct VmLaunchPlan { /// Where to look for the driver binary before the conventional locations. pub driver_dir: Option, - /// The driver's state directory, under which the gateway keeps the - /// private socket directory. + /// The driver's persistent state directory. pub state_dir: PathBuf, /// The table to forward, without gateway-owned keys. pub table: String, @@ -82,10 +80,6 @@ impl VmLaunchPlan { |dir| dir.join("vm-driver"), ) } - - fn socket_dir(&self) -> PathBuf { - self.state_dir.join(COMPUTE_DRIVER_SOCKET_RUN_DIR) - } } /// Resolve the trusted `openshell-driver-vm` binary. @@ -191,7 +185,7 @@ pub async fn spawn( name: "vm", binary: &binary, table: &plan.table, - socket_dir: &plan.socket_dir(), + socket_dir: None, log_level: gateway_log_level, }, configure, diff --git a/crates/openshell-gateway/src/vm/tests.rs b/crates/openshell-gateway/src/vm/tests.rs index 45554db430..26940b0318 100644 --- a/crates/openshell-gateway/src/vm/tests.rs +++ b/crates/openshell-gateway/src/vm/tests.rs @@ -46,16 +46,6 @@ fn a_non_string_gateway_key_is_rejected() { assert!(VmLaunchPlan::from_table(table("driver_dir = 3"), None).is_err()); } -#[test] -fn socket_dir_is_the_private_run_dir_under_the_state_dir() { - let plan = - VmLaunchPlan::from_table(table("state_dir = \"/tmp/openshell-vm-state\""), None).unwrap(); - assert_eq!( - plan.socket_dir(), - PathBuf::from("/tmp/openshell-vm-state/run") - ); -} - #[test] fn resolve_driver_bin_uses_driver_dir_when_binary_present() { let dir = tempdir().unwrap(); @@ -161,3 +151,135 @@ fn the_admission_policy_is_not_forwarded_in_the_driver_table() { ); assert!(!plan.table.contains("resource_admission"), "{}", plan.table); } + +#[tokio::test] +async fn spawn_keeps_sockets_short_and_preserves_long_state_dirs() { + use openshell_driver_sdk::launch::{Launch, LaunchInfo}; + use std::time::Duration; + + let dir = tempdir().unwrap(); + let state = dir.path().join("persistent-state".repeat(10)); + let plan = VmLaunchPlan::from_table( + table(&format!("state_dir = {:?}", state.to_str().unwrap())), + Some(dir.path()), + ) + .unwrap(); + assert!(state.as_os_str().len() > openshell_core::unix_socket_path::MAX_LEN); + let binary = dir.path().join(DRIVER_BIN_NAME); + let record = dir.path().join("socket"); + // The child records bootstrap arguments; this test serves the launch protocol. + std::fs::write(&binary, format!( + "#!/bin/sh\ncat > '{}'\nprintf '%s' \"$3\" > '{}'\nprintf '%s' \"$5\" > '{}'\nexec sleep 60\n", + dir.path().join("stdin").display(), record.display(), dir.path().join("peer").display() + )).unwrap(); + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap(); + let inputs = ConfigureInputs::from_environment( + "127.0.0.1:8080".parse().unwrap(), + None, + "test", + None, + None, + None, + ); + let startup = spawn(&plan, "info", &inputs); + let server = async { + let socket = loop { + if let Ok(path) = std::fs::read_to_string(&record) + && !path.is_empty() + { + break PathBuf::from(path); + } + tokio::time::sleep(Duration::from_millis(10)).await; + }; + assert_eq!(socket.parent().unwrap().parent(), Some(Path::new("/tmp"))); + assert!(!socket.starts_with(&state)); + assert_eq!( + std::fs::metadata(socket.parent().unwrap()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o700 + ); + let launch = Launch::new( + LaunchInfo { + driver_name: "vm".to_string(), + driver_version: "1.0".to_string(), + features: Vec::new(), + }, + |_| async { Ok(()) }, + ); + let listener = tokio::net::UnixListener::bind(socket).unwrap(); + tonic::transport::Server::builder() + .add_service(launch.into_server()) + .serve_with_incoming(tokio_stream::wrappers::UnixListenerStream::new(listener)) + .await + .unwrap(); + }; + let endpoint = tokio::time::timeout( + Duration::from_secs(10), + Box::pin(async { + tokio::select! { + result = startup => result.unwrap(), + () = server => panic!("launch server exited"), + } + }), + ) + .await + .unwrap(); + let socket = PathBuf::from(std::fs::read_to_string(&record).unwrap()); + assert_eq!( + std::fs::read_to_string(dir.path().join("peer")).unwrap(), + std::process::id().to_string() + ); + let forwarded: toml::Value = + toml::from_str(&std::fs::read_to_string(dir.path().join("stdin")).unwrap()).unwrap(); + assert_eq!( + forwarded["state_dir"].as_str().unwrap(), + state.to_str().unwrap() + ); + std::fs::write(state.join("persistent"), "keep").unwrap(); + drop(endpoint); + assert!(!socket.parent().unwrap().exists()); + assert_eq!( + std::fs::read_to_string(state.join("persistent")).unwrap(), + "keep" + ); + + // Retain failure and cancellation cleanup coverage through the same entry point. + let script = std::fs::read_to_string(&binary).unwrap(); + for command in ["exit 23", "exec sleep 60"] { + std::fs::remove_file(&record).unwrap(); + std::fs::write(&binary, script.replace("exec sleep 60", command)).unwrap(); + let mut startup = Box::pin(spawn(&plan, "info", &inputs)); + if command == "exit 23" { + assert!(startup.await.is_err()); + } else { + tokio::time::timeout(Duration::from_secs(5), async { + loop { + tokio::select! { + result = &mut startup => panic!("driver returned before cancellation: {result:?}"), + () = tokio::time::sleep(Duration::from_millis(10)) => {} + } + if std::fs::read_to_string(&record).is_ok_and(|path| !path.is_empty()) { + break; + } + } + }).await.unwrap(); + drop(startup); + } + let socket = PathBuf::from(std::fs::read_to_string(&record).unwrap()); + // The shared launcher's blocking startup finishes within its 30-second budget. + tokio::time::timeout(Duration::from_secs(35), async { + while socket.parent().unwrap().exists() { + tokio::time::sleep(Duration::from_millis(10)).await; + } + }) + .await + .unwrap(); + assert_eq!( + std::fs::read_to_string(state.join("persistent")).unwrap(), + "keep" + ); + } +} diff --git a/crates/openshell-sandbox-backend/src/runtime_initiated.rs b/crates/openshell-sandbox-backend/src/runtime_initiated.rs index 8599c06eb9..bad3780a2a 100644 --- a/crates/openshell-sandbox-backend/src/runtime_initiated.rs +++ b/crates/openshell-sandbox-backend/src/runtime_initiated.rs @@ -207,6 +207,7 @@ impl Listener { #[cfg(unix)] fn bind_unix(path: &std::path::Path) -> std::io::Result { use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; + openshell_core::unix_socket_path::check(path)?; // The driver owns the containing directory. Never replace a live socket, // another user's inode, or a non-socket (including symlinks). match std::fs::symlink_metadata(path) { diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 7a74565139..83d7874a00 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -4838,6 +4838,7 @@ mod linux { }) } BoundaryListenerConfig::Unix { socket_path, tls } => { + openshell_core::unix_socket_path::check(socket_path)?; remove_owned_stale_control_socket(socket_path)?; let listener = std::os::unix::net::UnixListener::bind(socket_path)?; // Mutual TLS makes a same-UID pathname replacement a diff --git a/crates/openshell-server/src/compute/driver_config.rs b/crates/openshell-server/src/compute/driver_config.rs index f79239ff11..cc359d1835 100644 --- a/crates/openshell-server/src/compute/driver_config.rs +++ b/crates/openshell-server/src/compute/driver_config.rs @@ -221,12 +221,13 @@ fn apply_remote_driver_overrides( } fn validate_remote_driver_config(cfg: &RemoteDriverConfig, name: &str) -> Result<()> { - if !cfg.socket_path.as_os_str().is_empty() { - return Ok(()); + if cfg.socket_path.as_os_str().is_empty() { + return Err(Error::config(format!( + "remote compute driver '{name}' requires socket_path" + ))); } - Err(Error::config(format!( - "remote compute driver '{name}' requires socket_path" - ))) + openshell_core::unix_socket_path::check(&cfg.socket_path) + .map_err(|err| Error::config(format!("remote compute driver '{name}' socket_path: {err}"))) } #[cfg(test)] @@ -526,12 +527,26 @@ socket_path = "/run/openshell/kyma.sock" } #[test] - fn remote_driver_config_rejects_missing_socket_path() { + fn remote_driver_config_rejects_invalid_socket_paths() { let err = remote_driver_config_from_context(test_context(None), "kyma").unwrap_err(); assert!( err.to_string() .contains("remote compute driver 'kyma' requires socket_path") ); + + let socket_path = PathBuf::from(format!( + "/{}/kyma.sock", + "a".repeat(openshell_core::unix_socket_path::MAX_LEN) + )); + let endpoint_overrides = BTreeMap::from([("kyma".to_string(), socket_path)]); + + let err = remote_driver_config_from_context( + test_context_with_endpoint_overrides(None, &endpoint_overrides), + "kyma", + ) + .unwrap_err(); + + assert!(err.to_string().contains("-byte limit"), "{err}"); } } diff --git a/crates/openshell-supervisor-process/src/ssh.rs b/crates/openshell-supervisor-process/src/ssh.rs index a11eddbd21..81d390a89e 100644 --- a/crates/openshell-supervisor-process/src/ssh.rs +++ b/crates/openshell-supervisor-process/src/ssh.rs @@ -124,6 +124,9 @@ fn ssh_server_init( // shared socket retains group access. Linux abstract sockets avoid a // workload-replaceable filesystem inode. let abstract_socket = crate::unix_socket::is_abstract(listen_path); + if !abstract_socket { + openshell_core::unix_socket_path::check(listen_path).into_diagnostic()?; + } if !abstract_socket && let Some(parent) = listen_path.parent() { std::fs::create_dir_all(parent).into_diagnostic()?; #[cfg(unix)] diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..0997cb80a1 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -304,6 +304,7 @@ fn prepare_control_readiness_path(path: &std::path::Path) -> Result<()> { "supervisor readiness socket path must be absolute" )); } + openshell_core::unix_socket_path::check(path).into_diagnostic()?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .into_diagnostic() diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 404cbfd454..a8d6e67f65 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1075,7 +1075,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. +In-process compute drivers read their backend-specific settings from `[openshell.drivers.]`. An external driver's gateway table supplies only its `socket_path`. The gateway rejects a Unix socket path longer than 107 bytes on Linux or 103 bytes on macOS. 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 @@ -1307,7 +1307,7 @@ The gateway validates snapshot structure and provider-profile semantics. It trea Set `credential_drivers` only when the gateway should store provider secrets in an external credential backend. Provider secrets include injectable credentials and gateway-only refresh material such as OAuth refresh tokens, client secrets, and service-account private keys. OpenShell supports at most one enabled credential driver at a time. When `credential_drivers` is omitted, the gateway uses its default encrypted database credential storage. `credential_drivers = []` is invalid in the TOML file; omit the field for the default encrypted store, or select a backend such as `kubernetes-secrets` or `vault`. -Credential driver tables are backend-owned and live under `[openshell.credential_drivers.]`. Built-in drivers default to in-tree transport, so they do not need a `transport` field. Use `transport = "uds"` with an absolute `socket_path` only for a remote gRPC driver over a Unix domain socket. +Credential driver tables are backend-owned and live under `[openshell.credential_drivers.]`. Built-in drivers default to in-tree transport, so they do not need a `transport` field. Use `transport = "uds"` with an absolute `socket_path` only for a remote gRPC driver over a Unix domain socket. The gateway rejects a `socket_path` longer than 107 bytes on Linux or 103 bytes on macOS. ```toml [openshell.gateway.credential_storage] @@ -2167,6 +2167,8 @@ kid_path = "/etc/openshell/jwt/kid" gateway_id = "openshell" [openshell.drivers.vm] +# Persistent VM state stays here. The gateway keeps the driver control socket +# in a private temporary directory under /tmp, independent of state_dir. state_dir = "/var/lib/openshell/vm" default_image = "nvcr.io/nvidia/base/ubuntu:24.04" # Optional override. When omitted, the gateway derives diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index bafaadbc71..65fe26130c 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -59,7 +59,7 @@ if [ "${E2E_TEST_OVERRIDE}" = "additional_ca" ]; then fi SANDBOX_IMAGE="${OPENSHELL_SANDBOX_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}" -# The VM driver places `compute-driver.sock` under `[openshell.drivers.vm].state_dir`. +# This script binds the external VM driver's `compute-driver.sock` under the run state dir. # AF_UNIX SUN_LEN is 104 bytes on macOS (108 on Linux), so paths anchored # in the workspace's `target/` blow the limit on typical developer # machines — e.g. a ~100-char `~/.superset/worktrees/.../target/...` @@ -169,7 +169,7 @@ print(s.getsockname()[1]) s.close()')" # Per-run state dir so concurrent e2e runs don't collide on the UDS or -# sandbox state. The VM driver creates `/compute-driver.sock` +# sandbox state. The external VM driver binds `/compute-driver.sock` # and `/sandboxes//overlay.ext4` under here. Keep the # basename short — see the SUN_LEN comment above. RUN_STATE_DIR="${STATE_DIR_ROOT}/os-vm-e2e-${HOST_PORT}-$$" diff --git a/tasks/scripts/gateway-vm.sh b/tasks/scripts/gateway-vm.sh index e30d0e7e4e..70b396e7c0 100755 --- a/tasks/scripts/gateway-vm.sh +++ b/tasks/scripts/gateway-vm.sh @@ -13,9 +13,8 @@ # - Plaintext HTTP on 127.0.0.1:18081 # - Gateway installation and CLI registration name "vm-dev" # - Persistent gateway state (SQLite DB) under .cache/gateway-vm -# - Per-sandbox VM driver state (rootfs + compute-driver.sock) under -# /tmp/openshell-vm-driver-- so the AF_UNIX socket -# path stays under macOS SUN_LEN +# - Per-sandbox VM driver state (rootfs and image cache) under +# /tmp/openshell-vm-driver-- # # Common overrides: # OPENSHELL_SERVER_PORT=18091 mise run gateway:vm @@ -267,10 +266,8 @@ if port_is_in_use "${PORT}"; then exit 2 fi -# AF_UNIX SUN_LEN on macOS is 104 bytes; the VM driver places -# `compute-driver.sock` directly under VM_DRIVER_STATE_DIR, so anchor it -# under /tmp instead of `${ROOT}/.cache` (which is typically too long on -# macOS dev boxes with worktree paths). +# Keep VM driver state outside the worktree. The gateway places the driver +# socket in its own /tmp directory, so this path length does not matter. STATE_LABEL="$(printf '%s' "${GATEWAY_NAME}" | tr -cs '[:alnum:]._-' '-')" if [ -z "${STATE_LABEL}" ]; then STATE_LABEL="vm-dev"