From eb7e604ae1f92e6973521f0ea14f9594e9f4fa9a Mon Sep 17 00:00:00 2001 From: Shiju Date: Tue, 17 Nov 2026 18:44:18 +0530 Subject: [PATCH 1/3] feat(compute)!: check service ports before provisioning Save the driver's allowed ports and loopback destination with the sandbox. Check requested ports before creation and forwarding, including reused HTTP connections and routes delivered to the supervisor. Signed-off-by: Shiju --- crates/openshell-cli/src/run.rs | 133 +++++- crates/openshell-cli/src/ssh.rs | 15 +- .../openshell-core/src/extension_protocol.rs | 3 + crates/openshell-core/src/forward.rs | 77 ++-- crates/openshell-core/src/ingress.rs | 97 +++++ crates/openshell-core/src/lib.rs | 1 + crates/openshell-driver-docker/src/lib.rs | 22 +- .../openshell-driver-kubernetes/src/driver.rs | 1 + .../openshell-driver-kubernetes/src/grpc.rs | 6 +- crates/openshell-driver-mxc/src/driver.rs | 2 +- crates/openshell-driver-mxc/src/grpc.rs | 4 +- crates/openshell-driver-podman/src/driver.rs | 2 +- crates/openshell-driver-podman/src/grpc.rs | 6 +- crates/openshell-driver-vm/src/driver.rs | 8 +- .../src/proto_json.rs | 1 + .../src/runtime.rs | 1 + crates/openshell-sdk/README.md | 4 + crates/openshell-sdk/src/client.rs | 9 +- crates/openshell-sdk/src/types.rs | 7 + crates/openshell-sdk/tests/client_mock.rs | 4 + .../tests/sandbox_status_compatibility.rs | 8 +- crates/openshell-server/src/compute/mod.rs | 393 ++++++++++++------ crates/openshell-server/src/grpc/mod.rs | 42 +- crates/openshell-server/src/grpc/sandbox.rs | 323 +++++++++++++- .../src/grpc/sandbox/image_update_tests.rs | 19 +- crates/openshell-server/src/grpc/service.rs | 24 +- .../openshell-server/src/service_routing.rs | 71 +++- crates/openshell-server/src/storage_proto.rs | 15 +- crates/openshell-server/src/test_support.rs | 22 +- crates/openshell-tui/src/app.rs | 5 +- crates/openshell-tui/src/event.rs | 6 +- crates/openshell-tui/src/lib.rs | 124 +++--- crates/openshell-tui/src/ui/create_sandbox.rs | 2 +- docs/extensibility/isolation-backends.mdx | 5 + docs/how-it-works/sandboxes/overview.mdx | 7 + examples/isolation-backend-v8/src/driver.rs | 5 +- proto/compute_driver.proto | 6 +- proto/openshell.proto | 5 + proto/sandbox.proto | 21 + tests/testkit/testkit/src/context.rs | 9 +- 40 files changed, 1206 insertions(+), 309 deletions(-) create mode 100644 crates/openshell-core/src/ingress.rs diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 3a7e45582c..80eee62fc6 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -1225,6 +1225,11 @@ pub async fn sandbox_create( )), await_main_process_attachment, workload_template: template.unwrap_or_default().to_string(), + forward_ports: forward + .as_ref() + .map(|spec| u32::from(spec.port)) + .into_iter() + .collect(), service_exposures: expose .map(|target_port| SandboxServiceExposure { service: String::new(), @@ -2227,6 +2232,17 @@ where println!(" {} {}", "Id:".dimmed(), id); println!(" {} {}", "Name:".dimmed(), name); println!(" {} {}", "Phase:".dimmed(), phase_name(sandbox.phase())); + println!( + " {} {}", + "Service ports:".dimmed(), + service_port_summary( + sandbox + .status + .as_ref() + .and_then(|s| s.ingress_admission.as_ref()) + ), + ); + if let Some(status) = sandbox.status.as_ref() { for condition in &status.conditions { if matches!( @@ -2708,8 +2724,12 @@ pub async fn service_forward_tcp( let (bind_addr, bind_port) = parse_tcp_forward_spec(local, target_port)?; let mut client = grpc_client(server, tls).await?; - let mut replica = fetch_ready_sandbox_for_forward(&mut client, name, workspace).await?; + let (mut replica, scope) = + fetch_ready_sandbox_for_forward(&mut client, name, workspace, target_port).await?; + if scope == openshell_core::proto::IngressScope::SharedHostLoopback { + eprintln!("Target is an admitted shared-host loopback service."); + } let listener = tokio::net::TcpListener::bind((bind_addr.as_str(), bind_port)) .await .into_diagnostic() @@ -2742,7 +2762,12 @@ pub async fn service_forward_tcp( } _ = health_check.tick() => { - replica = fetch_ready_sandbox_for_forward(&mut client, name, workspace).await?; + let (owner, current_scope) = + fetch_ready_sandbox_for_forward(&mut client, name, workspace, target_port).await?; + if current_scope != scope { + return Err(miette::miette!("sandbox ingress scope changed to {}; restart the service forward", ingress_scope_name(current_scope as i32))); + } + replica = owner; } accepted = listener.accept() => { @@ -2813,7 +2838,11 @@ async fn fetch_ready_sandbox_for_forward( client: &mut GrpcClient, name: &str, workspace: &str, -) -> Result> { + target_port: u16, +) -> Result<( + Option, + openshell_core::proto::IngressScope, +)> { let response = match client .get_sandbox(with_owner_hint(GetSandboxRequest { name: name.to_string(), @@ -2846,7 +2875,17 @@ async fn fetch_ready_sandbox_for_forward( )); } - Ok(replica) + let scope = openshell_core::ingress::IngressAdmission::from_status( + sandbox + .status + .as_ref() + .and_then(|status| status.ingress_admission.as_ref()), + false, + ) + .and_then(|admission| admission.admit_port(u32::from(target_port))) + .map_err(|error| miette::miette!("{error}"))?; + + Ok((replica, scope)) } #[derive(Debug)] @@ -3551,6 +3590,44 @@ fn configuration_failure_message(sandbox: &Sandbox) -> Option<&str> { .filter(|message| !message.is_empty()) } +fn ingress_scope_name(scope: i32) -> &'static str { + use openshell_core::proto::IngressScope; + match IngressScope::try_from(scope) { + Ok(IngressScope::IsolatedLoopback) => "isolated_loopback", + Ok(IngressScope::SharedHostLoopback) => "shared_host_loopback", + Ok(IngressScope::Unsupported) => "unsupported", + Ok(IngressScope::Unspecified) | Err(_) => "unknown", + } +} + +fn service_port_summary( + admission: Option<&openshell_core::proto::SandboxIngressAdmission>, +) -> String { + use openshell_core::proto::IngressScope; + let Some(admission) = admission else { + return "unknown (legacy forwarding)".into(); + }; + let target = match IngressScope::try_from(admission.scope) { + Ok(IngressScope::IsolatedLoopback) => "sandbox loopback", + Ok(IngressScope::SharedHostLoopback) => "shared host loopback", + Ok(IngressScope::Unsupported) => return "unsupported".into(), + Ok(IngressScope::Unspecified) | Err(_) => return "unavailable".into(), + }; + let ports = if admission.all_ports { + "all".into() + } else if admission.ports.is_empty() { + "none".into() + } else { + admission + .ports + .iter() + .map(u32::to_string) + .collect::>() + .join(", ") + }; + format!("{ports} ({target})") +} + fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { use openshell_core::proto::ConfigurationAdmissionState; @@ -3662,6 +3739,11 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { "conditions": conditions, "endpoint_statuses": endpoint_statuses, "last_token_grant_failure": last_token_grant_failure, + "ingress_admission": sandbox.status.as_ref().and_then(|status| status.ingress_admission.as_ref()).map(|ingress| serde_json::json!({ + "scope": ingress_scope_name(ingress.scope), + "all_ports": ingress.all_ports, + "ports": ingress.ports, + })), "configuration_admission": admission, "provisioning": provisioning, "created_from_workload_template": created_from_workload_template, @@ -9910,6 +9992,49 @@ mod tests { .error .clear(); assert_eq!(super::configuration_failure_message(&sandbox), None); + assert!(super::sandbox_to_json(&sandbox)["ingress_admission"].is_null()); + let mut admission = openshell_core::proto::SandboxIngressAdmission::default(); + assert_eq!(super::service_port_summary(Some(&admission)), "unavailable"); + admission.scope = openshell_core::proto::IngressScope::SharedHostLoopback as i32; + assert_eq!( + super::service_port_summary(Some(&admission)), + "none (shared host loopback)" + ); + admission.ports.push(8080); + assert_eq!( + super::service_port_summary(Some(&admission)), + "8080 (shared host loopback)" + ); + for (scope, expected) in [ + ( + openshell_core::proto::IngressScope::IsolatedLoopback as i32, + "isolated_loopback", + ), + ( + openshell_core::proto::IngressScope::SharedHostLoopback as i32, + "shared_host_loopback", + ), + ( + openshell_core::proto::IngressScope::Unsupported as i32, + "unsupported", + ), + (0, "unknown"), + (99, "unknown"), + ] { + sandbox.status.as_mut().unwrap().ingress_admission = + Some(openshell_core::proto::SandboxIngressAdmission { + scope, + ports: vec![8080], + all_ports: false, + }); + let output = super::sandbox_to_json(&sandbox); + assert_eq!(output["ingress_admission"]["scope"], expected); + assert_eq!( + output["ingress_admission"]["ports"], + serde_json::json!([8080]) + ); + assert_eq!(output["ingress_admission"]["all_ports"], false); + } } #[test] diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index 202cca4c8e..9769f5d72c 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -110,6 +110,7 @@ struct SshSessionConfig { target: SshTarget, client: GrpcClient, main_terminal: bool, + ingress_admission: Option, } impl SshSessionConfig { @@ -157,6 +158,7 @@ async fn ssh_session_config( Ok(SshSessionConfig { target, client, + ingress_admission: sandbox.status.and_then(|status| status.ingress_admission), main_terminal: sandbox.spec.as_ref().is_none_or(|spec| spec.tty), }) } @@ -688,9 +690,18 @@ pub async fn sandbox_forward( tls: &TlsOptions, workspace: &str, ) -> Result<()> { - openshell_core::forward::check_port_available(spec)?; - let session = ssh_session_config(server, name, tls, workspace).await?; + let scope = openshell_core::ingress::IngressAdmission::from_status( + session.ingress_admission.as_ref(), + false, + ) + .and_then(|admission| admission.admit_port(u32::from(spec.port))) + .map_err(|error| miette::miette!("{error}"))?; + if scope == openshell_core::proto::IngressScope::SharedHostLoopback { + eprintln!("Target is an admitted shared-host loopback service."); + } + + openshell_core::forward::check_port_available(spec)?; let proxy = session.prepare().await?; let command = TokioCommand::from(ssh_forward_command( diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..4cbfb31f3d 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -46,6 +46,8 @@ pub const COMPUTE_SUSPEND_RESUME: &str = "openshell.compute.suspend-resume"; /// Optional stopped-state workload configuration updates retaining the resource and storage. pub const COMPUTE_UPDATE_SANDBOX_CONFIGURATION: &str = "openshell.compute.update-sandbox-configuration"; +/// Immutable per-sandbox forwarding and service exposure admission. +pub const COMPUTE_INGRESS_ADMISSION: &str = "openshell.compute.ingress-admission"; /// Capability for supervisor middleware that implements HTTP hooks. /// @@ -160,6 +162,7 @@ pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata { supported_capabilities.push(COMPUTE_LAUNCH_AUTHENTICATION.to_string()); supported_capabilities.push(COMPUTE_ISOLATION_BACKEND.to_string()); supported_capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string()); + supported_capabilities.push(COMPUTE_INGRESS_ADMISSION.to_string()); } ExtensionFamily::SupervisorMiddleware => { supported_capabilities.push(SUPERVISOR_MIDDLEWARE_HTTP_HOOKS.to_string()); diff --git a/crates/openshell-core/src/forward.rs b/crates/openshell-core/src/forward.rs index d65aa53321..4ee95240c2 100644 --- a/crates/openshell-core/src/forward.rs +++ b/crates/openshell-core/src/forward.rs @@ -10,7 +10,7 @@ use crate::paths::{create_dir_restricted, xdg_config_dir}; use crate::ssh_host_key::HostKeyCheck; use miette::{IntoDiagnostic, Result, WrapErr}; use std::borrow::Cow; -use std::net::TcpListener; +use std::net::ToSocketAddrs; use std::path::{Component, PathBuf}; use std::process::Command; @@ -751,9 +751,25 @@ impl std::fmt::Display for ForwardSpec { pub fn check_port_available(spec: &ForwardSpec) -> Result<()> { let port = spec.port; - // Fast path: try binding on the requested address. If this fails, the - // port is definitely taken on this address family. - let bind_ok = TcpListener::bind((spec.bind_addr.as_str(), port)).is_ok(); + // Probe local availability before sandbox creation without opening a listener. + let bind_ok = (spec.bind_addr.as_str(), port) + .to_socket_addrs() + .is_ok_and(|mut addrs| { + addrs.any(|addr| { + let socket = if addr.is_ipv4() { + tokio::net::TcpSocket::new_v4() + } else { + tokio::net::TcpSocket::new_v6() + }; + socket + .and_then(|socket| { + #[cfg(not(windows))] + socket.set_reuseaddr(true)?; + socket.bind(addr) + }) + .is_ok() + }) + }); // Also ask the OS whether *any* process is listening on this port, // regardless of address family. This catches situations where e.g. a @@ -1129,6 +1145,7 @@ mod tests { use super::*; use crate::ssh_host_key::KnownHostsPin; use crate::test_environment::Environment; + use std::net::TcpListener; #[test] fn direct_ssh_requires_one_explicit_capability_value() { @@ -1554,7 +1571,7 @@ mod tests { } #[test] - fn check_port_available_free_port() { + fn local_forward_accepts_a_released_port() { // Bind to port 0 to get an OS-assigned free port, then drop the // listener so the port is released before we test it. On busy CI // hosts, another process can claim that single ephemeral port before @@ -1581,42 +1598,20 @@ mod tests { } #[test] - fn check_port_available_occupied_port() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - // Keep the listener alive so the port stays occupied. - - let result = check_port_available(&ForwardSpec::new(port)); - assert!(result.is_err()); - let msg = result.unwrap_err().to_string(); - assert!( - msg.contains("already in use"), - "expected 'already in use' in error message, got: {msg}" - ); - } - - #[cfg(not(target_os = "windows"))] - #[test] - fn check_port_available_occupied_ipv6_wildcard() { - // Bind on [::]:0 (IPv6 wildcard) — this simulates a server like - // `python3 -m http.server` which listens on [::] by default. The - // IPv4-only TcpListener::bind("127.0.0.1", port) might succeed, but - // lsof should detect the listener and the check should still fail. - let Ok(listener) = TcpListener::bind("[::]:0") else { - return; // IPv6 not available, skip - }; - let port = listener.local_addr().unwrap().port(); - - let result = check_port_available(&ForwardSpec::new(port)); - assert!( - result.is_err(), - "expected error for IPv6-occupied port {port}" - ); - let msg = result.unwrap_err().to_string(); - assert!( - msg.contains("already in use"), - "expected 'already in use' in error message, got: {msg}" - ); + fn local_forward_rejects_ports_already_in_use() { + let ipv4 = TcpListener::bind("127.0.0.1:0").unwrap(); + let listeners = std::iter::once(ipv4); + // An IPv6 wildcard listener can also occupy the requested IPv4 port. + #[cfg(not(target_os = "windows"))] + let listeners = listeners.chain(TcpListener::bind("[::]:0").ok()); + for listener in listeners { + let address = listener.local_addr().unwrap(); + let error = check_port_available(&ForwardSpec::new(address.port())).unwrap_err(); + assert!( + error.to_string().contains("already in use"), + "{address}: {error}" + ); + } } #[test] diff --git a/crates/openshell-core/src/ingress.rs b/crates/openshell-core/src/ingress.rs new file mode 100644 index 0000000000..4afc41f437 --- /dev/null +++ b/crates/openshell-core/src/ingress.rs @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Check service ports against the compute driver's decision for a sandbox. + +use crate::proto::{IngressScope, SandboxIngressAdmission}; +use std::collections::BTreeSet; + +impl SandboxIngressAdmission { + /// The backend can reach every TCP port on the sandbox's own loopback. + pub const ALL_ISOLATED_LOOPBACK_PORTS: Self = Self { + scope: IngressScope::IsolatedLoopback as i32, + all_ports: true, + ports: Vec::new(), + }; + + /// The backend cannot forward service connections. + pub const UNSUPPORTED: Self = Self { + scope: IngressScope::Unsupported as i32, + all_ports: false, + ports: Vec::new(), + }; +} + +/// Validated ingress scope and port set for one sandbox. +#[derive(Debug)] +pub struct IngressAdmission { + scope: IngressScope, + // An absent set allows every valid port. + ports: Option>, +} + +impl IngressAdmission { + /// Read the saved decision. Drivers using legacy forwarding may omit it. + pub fn from_status( + admission: Option<&SandboxIngressAdmission>, + required: bool, + ) -> Result { + let Some(admission) = admission else { + return if required { + Err("no saved service ports for this sandbox. Recreate the sandbox") + } else { + Ok(Self { + scope: IngressScope::Unspecified, + ports: None, + }) + }; + }; + let scope = IngressScope::try_from(admission.scope) + .map_err(|_| "unknown service forwarding destination")?; + if scope == IngressScope::Unspecified { + return Err( + "allowed service ports are unavailable for this sandbox. Recreate the sandbox", + ); + } + if (admission.all_ports && !admission.ports.is_empty()) + || (scope == IngressScope::Unsupported + && (admission.all_ports || !admission.ports.is_empty())) + || admission.ports.len() > 65535 + { + return Err("invalid service port list from the compute driver"); + } + let mut ports = BTreeSet::new(); + for &port in &admission.ports { + if !(1..=65535).contains(&port) || !ports.insert(port) { + return Err("allowed service ports must be unique and between 1 and 65535"); + } + } + Ok(Self { + scope, + ports: (!admission.all_ports).then_some(ports), + }) + } + + /// The network used by admitted service connections. + pub fn scope(&self) -> IngressScope { + self.scope + } + + /// Return the network scope if the driver admits the target port. + pub fn admit_port(&self, port: u32) -> Result { + if !(1..=65535).contains(&port) { + return Err("target port must be between 1 and 65535"); + } + if self.scope == IngressScope::Unsupported { + return Err("the compute driver does not support service forwarding"); + } + if self + .ports + .as_ref() + .is_some_and(|ports| !ports.contains(&port)) + { + return Err("the compute driver does not allow this target port"); + } + Ok(self.scope) + } +} diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 4bc48e01d1..6213a0bc40 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -37,6 +37,7 @@ pub mod gpu; pub mod grpc_client; pub mod host_pattern; pub mod image; +pub mod ingress; pub mod isolation_registration; pub mod jwt; pub mod local_api_socket; diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 75e894bd5e..2603b3a622 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -1098,6 +1098,13 @@ impl DockerComputeDriver { } fn capabilities(&self) -> GetCapabilitiesResponse { + use openshell_core::extension_protocol::{ + COMPUTE_INGRESS_ADMISSION, COMPUTE_UPDATE_SANDBOX_CONFIGURATION, + }; + let mut capabilities = vec![COMPUTE_INGRESS_ADMISSION.to_string()]; + if self.config.workspace_storage == workspace::Storage::Persistent { + capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string()); + } GetCapabilitiesResponse { resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { allow_driver_config: self.config.allow_driver_config, @@ -1128,14 +1135,7 @@ impl DockerComputeDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/docker", openshell_core::VERSION, - if self.config.workspace_storage == workspace::Storage::Persistent { - vec![ - openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION - .to_string(), - ] - } else { - Vec::new() - }, + capabilities, )), } } @@ -3514,7 +3514,11 @@ impl ComputeDriver for DockerComputeDriver { CdiGpuDefaultSelector::peek_device_ids, ) .await?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some( + openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, + ), + })) } async fn get_sandbox( diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..b596f0b7d7 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1325,6 +1325,7 @@ impl KubernetesComputeDriver { [ openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION .to_string(), + openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string(), ], )), }) diff --git a/crates/openshell-driver-kubernetes/src/grpc.rs b/crates/openshell-driver-kubernetes/src/grpc.rs index 6ce79654ef..fae57d9080 100644 --- a/crates/openshell-driver-kubernetes/src/grpc.rs +++ b/crates/openshell-driver-kubernetes/src/grpc.rs @@ -102,7 +102,11 @@ impl ComputeDriver for ComputeDriverService { .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.driver.validate_sandbox_create(&sandbox).await?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some( + openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, + ), + })) }) .await } diff --git a/crates/openshell-driver-mxc/src/driver.rs b/crates/openshell-driver-mxc/src/driver.rs index ee2de97e98..c769043a15 100644 --- a/crates/openshell-driver-mxc/src/driver.rs +++ b/crates/openshell-driver-mxc/src/driver.rs @@ -479,7 +479,7 @@ impl MxcComputeBackend { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/mxc", openshell_core::VERSION, - [], + [openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string()], )), } } diff --git a/crates/openshell-driver-mxc/src/grpc.rs b/crates/openshell-driver-mxc/src/grpc.rs index ca834987cb..05e129bfe0 100644 --- a/crates/openshell-driver-mxc/src/grpc.rs +++ b/crates/openshell-driver-mxc/src/grpc.rs @@ -70,7 +70,9 @@ impl ComputeDriver for ComputeDriverService { .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.backend.validate_sandbox_create(&sandbox)?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some(openshell_core::proto::SandboxIngressAdmission::UNSUPPORTED), + })) } async fn get_sandbox( diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index a263bcf7d2..c4013ac644 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -751,7 +751,7 @@ impl PodmanComputeDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/podman", openshell_core::VERSION, - [], + [openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string()], )), }) } diff --git a/crates/openshell-driver-podman/src/grpc.rs b/crates/openshell-driver-podman/src/grpc.rs index 5318b3f833..d13c01ea60 100644 --- a/crates/openshell-driver-podman/src/grpc.rs +++ b/crates/openshell-driver-podman/src/grpc.rs @@ -100,7 +100,11 @@ impl ComputeDriver for ComputeDriverService { .validate_sandbox_create(&sandbox) .await .map_err(Status::from)?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some( + openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, + ), + })) }) .await } diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..55e2bda6b2 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1552,7 +1552,7 @@ impl VmDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/vm", openshell_core::VERSION, - [], + [openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string()], ); extension .required_capabilities @@ -5351,7 +5351,11 @@ impl ComputeDriver for VmDriver { .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.validate_sandbox(&sandbox)?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some( + openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, + ), + })) } async fn create_sandbox( diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index f34c791adc..0763d7bf1d 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -322,6 +322,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }; let bytes = request.encode_to_vec(); let json = codec diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index a92391e9e6..5ad7f97bd9 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -1130,6 +1130,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }; let bytes = request.encode_to_vec(); diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index fb7c4f3dce..4e0d4ef2d2 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -268,3 +268,7 @@ These helpers use the raw client's authentication slot. They do not perform OIDC - Async-only. Tonic is async-native; callers needing a blocking call can wrap with their own runtime. - The curated surface will grow as more RPCs graduate from `raw`. + +## Next minor API migration + +Full Rust struct literals for `SandboxSpec`, `SandboxTemplateCreateSpec`, and raw `CreateSandboxRequest` now need `forward_ports`. Use `vec![]` for no local forwards. Raw `SandboxStatus` and `ValidateSandboxCreateResponse` also gain `ingress_admission`. Drivers advertising port admission must return `Some(...)`. diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..1eb237741a 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1050,12 +1050,12 @@ impl OpenShellClient { } /// Retrying create shared by every create surface. - async fn create_with_retry( + fn create_with_retry( &self, request: proto::CreateSandboxRequest, workspace: &str, options: CreateRetryOptions, - ) -> Result { + ) -> impl Future> { self.create_with_retry_using( request, workspace, @@ -1063,7 +1063,6 @@ impl OpenShellClient { create_retry_seed(), tokio::time::sleep, ) - .await } /// [`OpenShellClient::create_with_retry`] with the jitter seed and the @@ -1840,6 +1839,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { command, tty, service_exposures, + forward_ports, restart_policy, } = spec; let template = image.map(|image| proto::SandboxTemplate { @@ -1867,6 +1867,7 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { workspace_scope: Some(proto::workspace_selector("default")), await_main_process_attachment: false, workload_template: String::new(), + forward_ports: forward_ports.into_iter().map(u32::from).collect(), service_exposures: service_exposures .into_iter() .map(|exposure| proto::SandboxServiceExposure { @@ -1892,6 +1893,7 @@ fn create_sandbox_from_template_request( tty, policy, service_exposures, + forward_ports, } = spec; proto::CreateSandboxRequest { request_id: String::new(), @@ -1908,6 +1910,7 @@ fn create_sandbox_from_template_request( workspace_scope: Some(proto::workspace_selector("default")), workload_template: template_name, await_main_process_attachment: false, + forward_ports: forward_ports.into_iter().map(u32::from).collect(), service_exposures: service_exposures .into_iter() .map(|exposure| proto::SandboxServiceExposure { diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index aaf6231dca..0ed8cbb3f4 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -323,6 +323,8 @@ pub struct SandboxSpec { pub tty: bool, /// Loopback HTTP services to expose when the sandbox is created. pub service_exposures: Vec, + /// Target ports the gateway checks before creating the sandbox. + pub forward_ports: Vec, /// Restart behavior after the canonical main process exits. pub restart_policy: SandboxRestartPolicy, } @@ -374,6 +376,8 @@ pub struct SandboxTemplateCreateSpec { pub tty: bool, /// Loopback HTTP services to expose when the sandbox is created. pub service_exposures: Vec, + /// Target ports the gateway checks before creating the sandbox. + pub forward_ports: Vec, /// Create-time sandbox policy. The named workload template supplies runtime /// workload fields; policy remains part of the sandbox's governance spec. pub policy: Option, @@ -415,6 +419,8 @@ pub struct SandboxTemplateListOptions { #[derive(Clone, Debug)] #[non_exhaustive] pub struct SandboxRef { + /// Service ports the driver allows. Legacy forwarding leaves this field empty. + pub ingress_admission: Option, pub id: String, pub name: String, pub workspace: String, @@ -474,6 +480,7 @@ impl SandboxRef { }); let meta = sandbox.metadata.unwrap_or_default(); Self { + ingress_admission: sandbox.status.and_then(|status| status.ingress_admission), id: meta.id, name: meta.name, workspace: meta.workspace, diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 39d2f6b01e..ef9502118e 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -1395,6 +1395,7 @@ async fn create_sandbox_passes_spec_through() { image: Some("ghcr.io/foo:bar".to_string()), labels: labels.clone(), gpu: true, + forward_ports: vec![8080], service_exposures: vec![ServiceExposure { service: "web".to_string(), target_port: 8080, @@ -1420,6 +1421,7 @@ async fn create_sandbox_passes_spec_through() { assert_eq!(observed.name, "my-box"); assert_eq!(observed.labels, labels); assert!(observed.annotations.is_empty()); + assert_eq!(observed.forward_ports, vec![8080]); assert_eq!(observed.service_exposures.len(), 1); assert_eq!(observed.service_exposures[0].service, "web"); assert_eq!(observed.service_exposures[0].target_port, 8080); @@ -1451,6 +1453,7 @@ async fn create_sandbox_from_template_passes_template_name() { .create_sandbox_from_template(SandboxTemplateCreateSpec { name: Some("from-template".to_string()), template_name: "python".to_string(), + forward_ports: vec![9090], providers: vec!["openai".to_string()], command: vec!["python".to_string(), "-m".to_string(), "agent".to_string()], tty: false, @@ -1467,6 +1470,7 @@ async fn create_sandbox_from_template_passes_template_name() { let observed = state.last_create.lock().await.clone().unwrap(); assert_eq!(observed.name, "from-template"); assert_eq!(observed.workload_template, "python"); + assert_eq!(observed.forward_ports, [9090]); let observed_spec = observed.spec.unwrap(); assert_eq!(observed_spec.providers, vec!["openai".to_string()]); assert_eq!(observed_spec.command, vec!["python", "-m", "agent"]); diff --git a/crates/openshell-sdk/tests/sandbox_status_compatibility.rs b/crates/openshell-sdk/tests/sandbox_status_compatibility.rs index 7a080a381f..3270906c73 100644 --- a/crates/openshell-sdk/tests/sandbox_status_compatibility.rs +++ b/crates/openshell-sdk/tests/sandbox_status_compatibility.rs @@ -1,14 +1,13 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Compile-time source-compatibility fixture for the v0.1.5 public status shape. +//! Checks the full raw `SandboxStatus` literal for the next minor release. use openshell_sdk::raw::proto::SandboxStatus; #[test] -fn baseline_exhaustive_sandbox_status_literal_still_compiles() { - // Intentionally no `..Default::default()`: adding even an optional public - // field breaks existing downstream Rust exhaustive struct literals. +fn sandbox_status_supports_an_exhaustive_rust_literal() { + // List every field so a schema change fails to compile here. let status = SandboxStatus { agent_pod: String::new(), agent_fd: String::new(), @@ -26,6 +25,7 @@ fn baseline_exhaustive_sandbox_status_literal_still_compiles() { next_restart_time: None, main_process_started_time: None, last_token_grant_failure: None, + ingress_admission: None, }; assert_eq!(status, SandboxStatus::default()); } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..b542135f85 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -46,9 +46,9 @@ use openshell_core::proto::compute::v1::{ compute_driver_server::ComputeDriver, watch_sandboxes_event, }; use openshell_core::proto::{ - PlatformEvent, Sandbox, SandboxCondition, SandboxPhase, SandboxPolicy as ProtoSandboxPolicy, - SandboxRestartPolicy, SandboxSpec, SandboxStatus, SandboxTemplate, SandboxWorkloadTemplate, - ServiceEndpoint, SshSession, + PlatformEvent, Sandbox, SandboxCondition, SandboxIngressAdmission, SandboxPhase, + SandboxPolicy as ProtoSandboxPolicy, SandboxRestartPolicy, SandboxSpec, SandboxStatus, + SandboxTemplate, SandboxWorkloadTemplate, ServiceEndpoint, SshSession, }; use openshell_core::rpc_error::{is_mutation_lock_timeout, rebuild_with_message}; use openshell_core::telemetry::TelemetryComputeDriver; @@ -100,6 +100,12 @@ pub type SharedComputeDriverConfigurationUpdates = Arc< + Sync, >; +fn supports_ingress_admission(capabilities: &[String]) -> bool { + capabilities.iter().any(|capability| { + capability == openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION + }) +} + fn supports_isolation_registration(capabilities: &[String]) -> bool { capabilities.iter().any(|capability| { capability == openshell_core::extension_protocol::COMPUTE_ISOLATION_BACKEND @@ -1116,7 +1122,7 @@ struct RemoteComputeDriver { client: RemoteComputeDriverClient, app_endpoints_client: openshell_core::proto::compute::v1::compute_driver_app_endpoints_client::ComputeDriverAppEndpointsClient>, configuration_updates_client: openshell_core::proto::compute::v1::compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient>, - admission_acknowledgement: Arc>>, + admission_handshake: Arc>, } type RemoteComputeDriverClient = ComputeDriverClient< @@ -1129,7 +1135,7 @@ impl RemoteComputeDriver { client: ComputeDriverClient::with_interceptor(channel.clone(), TraceContextInterceptor), app_endpoints_client: openshell_core::proto::compute::v1::compute_driver_app_endpoints_client::ComputeDriverAppEndpointsClient::with_interceptor(channel.clone(), TraceContextInterceptor), configuration_updates_client: openshell_core::proto::compute::v1::compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient::with_interceptor(channel, TraceContextInterceptor), - admission_acknowledgement: Arc::new(StdMutex::new(None)), + admission_handshake: Arc::new(OnceLock::new()), } } @@ -1138,11 +1144,9 @@ impl RemoteComputeDriver { } async fn verify_admission_policy(&self, external_isolation: bool) -> Result<(), Status> { - let expected = self - .admission_acknowledgement - .lock() - .map_err(|_| Status::internal("admission handshake lock poisoned"))? - .clone() + let (expected, negotiated_ingress) = self + .admission_handshake + .get() .ok_or_else(|| Status::failed_precondition("driver admission handshake required"))?; let current = self .client() @@ -1160,7 +1164,16 @@ impl RemoteComputeDriver { "remote compute driver no longer supports isolation backend registration; restart the gateway after upgrading the driver", )); } - if current.resource_admission_policy != expected { + let current_ingress = current + .extension + .as_ref() + .is_some_and(|metadata| supports_ingress_admission(&metadata.supported_capabilities)); + if current_ingress != *negotiated_ingress { + return Err(Status::failed_precondition( + "remote compute driver ingress admission capability changed; restart the gateway to renegotiate", + )); + } + if ¤t.resource_admission_policy != expected { return Err(Status::failed_precondition( "remote driver admission policy changed; restart gateway after configuring matching policy", )); @@ -1197,10 +1210,13 @@ impl ComputeDriver for RemoteComputeDriver { { let mut client = self.client(); let response = client.get_capabilities(request).await?; - self.admission_acknowledgement - .lock() - .map_err(|_| Status::internal("admission handshake lock poisoned"))? - .get_or_insert_with(|| response.get_ref().resource_admission_policy.clone()); + self.admission_handshake.get_or_init(|| { + let capabilities = response.get_ref(); + let ingress = capabilities.extension.as_ref().is_some_and(|metadata| { + supports_ingress_admission(&metadata.supported_capabilities) + }); + (capabilities.resource_admission_policy.clone(), ingress) + }); Ok(response) } @@ -1918,13 +1934,51 @@ impl ComputeRuntime { } } + pub(crate) fn supports_ingress_admission(&self) -> bool { + supports_ingress_admission(&self.driver_info.negotiated_extension.supported_capabilities) + } + + pub(crate) fn ingress_admission( + &self, + sandbox: &Sandbox, + ) -> Result { + openshell_core::ingress::IngressAdmission::from_status( + sandbox + .status + .as_ref() + .and_then(|status| status.ingress_admission.as_ref()), + self.supports_ingress_admission(), + ) + .map_err(Status::failed_precondition) + } + + pub(crate) fn admit_ingress_port(&self, sandbox: &Sandbox, port: u32) -> Result<(), Status> { + self.ingress_admission(sandbox)? + .admit_port(port) + .map(|_| ()) + .map_err(Status::failed_precondition) + } + + pub(crate) fn project_ingress_admission(&self, sandbox: &mut Sandbox) { + if self.supports_ingress_admission() { + // Older sandboxes can lack a saved decision even when the driver now requires one. + sandbox + .status + .get_or_insert_with(Default::default) + .ingress_admission + .get_or_insert_with(Default::default); + } + } + pub async fn validate_sandbox_create(&self, sandbox: &Sandbox) -> Result<(), Status> { self.validate_sandbox_create_with_runtime_inputs( sandbox, &SandboxCreateRuntimeInputs::default(), false, + [], ) .await + .map(|_| ()) } pub(crate) async fn validate_sandbox_create_with_runtime_inputs( @@ -1932,7 +1986,8 @@ impl ComputeRuntime { sandbox: &Sandbox, runtime_inputs: &SandboxCreateRuntimeInputs, await_main_process_attachment: bool, - ) -> Result<(), Status> { + requested_ports: impl IntoIterator, + ) -> Result, Status> { self.validate_caller_driver_config( sandbox .spec @@ -1954,7 +2009,8 @@ impl ComputeRuntime { let staged = self.rootfs_tar_staging.peek(&token)?; set_rootfs_tar_path(&mut driver_sandbox, &staged); } - self.driver + let response = self + .driver .call( openshell_otel::rpc::VALIDATE_SANDBOX_CREATE, Some(sandbox.object_id()), @@ -1966,8 +2022,26 @@ impl ComputeRuntime { .await }, ) - .await - .map(|_| ()) + .await? + .into_inner(); + let admission = if self.supports_ingress_admission() { + Some(response.ingress_admission.ok_or_else(|| { + Status::failed_precondition( + "compute driver advertised service port checks but returned no decision", + ) + })?) + } else { + None + }; + let allowed = + openshell_core::ingress::IngressAdmission::from_status(admission.as_ref(), false) + .map_err(Status::failed_precondition)?; + for port in requested_ports { + allowed + .admit_port(port) + .map_err(|reason| Status::failed_precondition(format!("port {port}: {reason}")))?; + } + Ok(admission) } pub async fn create_sandbox( @@ -2050,8 +2124,8 @@ impl ComputeRuntime { launch_authentication, ..Default::default() }, - lifecycle_guard, - mutation_guard, + None, + (lifecycle_guard, mutation_guard), )) .await } @@ -2075,8 +2149,8 @@ impl ComputeRuntime { sandbox_token, await_main_process_attachment, runtime_inputs, - lifecycle_guard, - mutation_guard, + None, + (lifecycle_guard, mutation_guard), )) .await } @@ -2087,8 +2161,8 @@ impl ComputeRuntime { sandbox_token: Option, await_main_process_attachment: bool, runtime_inputs: SandboxCreateRuntimeInputs, - lifecycle_guard: SandboxLifecycleGuard, - mutation_guard: MutationGuard, + validated_ingress: Option, + (lifecycle_guard, mutation_guard): (SandboxLifecycleGuard, MutationGuard), ) -> Result { // Defend the internal create path too, before consuming a staged archive // or persisting the sandbox. The gRPC handler checks before driver validation. @@ -2115,6 +2189,25 @@ impl ComputeRuntime { self.isolation_backend_name().into(), ); + let admission = match validated_ingress { + None if self.supports_ingress_admission() => { + self.validate_sandbox_create_with_runtime_inputs( + &sandbox, + &runtime_inputs, + await_main_process_attachment, + [], + ) + .await? + } + admission => admission, + }; + if admission.is_some() || sandbox.status.is_some() { + sandbox + .status + .get_or_insert_with(Default::default) + .ingress_admission = admission; + } + // Strip the staging token from the public sandbox before anything // persists it: the object store copy is readable by every member of the // workspace, and the token is a bearer credential for the staged @@ -8279,6 +8372,7 @@ fn public_status_from_driver( next_restart_time: None, main_process_started_time: None, last_token_grant_failure: None, + ingress_admission: None, } } @@ -8435,6 +8529,9 @@ fn apply_driver_snapshot( .configuration_admission .clone_from(¤t_status.configuration_admission); status.configuration_activated = current_status.configuration_activated; + status + .ingress_admission + .clone_from(¤t_status.ingress_admission); status.provisioning.clone_from(¤t_status.provisioning); } if old_phase != phase { @@ -9176,7 +9273,7 @@ impl ComputeDriver for NoopTestDriver { Status, > { Ok(tonic::Response::new( - openshell_core::proto::compute::v1::ValidateSandboxCreateResponse {}, + openshell_core::proto::compute::v1::ValidateSandboxCreateResponse::default(), )) } @@ -10075,7 +10172,9 @@ mod tests { .lock() .expect("validated sandbox observation lock poisoned") .push(request.into_inner().sandbox.expect("validation sandbox")); - Ok(tonic::Response::new(ValidateSandboxCreateResponse {})) + Ok(tonic::Response::new( + ValidateSandboxCreateResponse::default(), + )) } async fn get_sandbox( @@ -10626,7 +10725,9 @@ mod tests { &self, _request: Request, ) -> Result, Status> { - Ok(tonic::Response::new(ValidateSandboxCreateResponse {})) + Ok(tonic::Response::new( + ValidateSandboxCreateResponse::default(), + )) } async fn get_sandbox( @@ -11037,7 +11138,12 @@ mod tests { }); let inputs = SandboxCreateRuntimeInputs::default(); runtime - .validate_sandbox_create_with_runtime_inputs(&sandbox, &inputs, attachment_expected) + .validate_sandbox_create_with_runtime_inputs( + &sandbox, + &inputs, + attachment_expected, + [], + ) .await .expect("preflight"); runtime @@ -17584,59 +17690,78 @@ mod tests { } #[tokio::test] - async fn apply_sandbox_update_without_status_preserves_existing_status() { - let runtime = test_runtime(Arc::new(TestDriver::default())).await; - let mut sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Ready); - sandbox.status = Some(SandboxStatus { - conditions: vec![SandboxCondition { - r#type: "Ready".to_string(), - status: "True".to_string(), - reason: "DependenciesReady".to_string(), - message: "Pod is Ready".to_string(), - transition_time: None, - }], - current_policy_version: 7, - ..Default::default() - }); - sandbox.set_phase(SandboxPhase::Ready as i32); - runtime.store.put_message(&sandbox).await.unwrap(); + async fn driver_updates_preserve_gateway_owned_sandbox_status() { + for observed_status in [ + None, + Some(make_driver_status(DriverCondition { + status: "True".into(), + ..make_driver_condition("DependenciesReady", "Pod is Ready") + })), + ] { + let mut runtime = test_runtime(Arc::new(TestDriver::default())).await; + runtime.driver_info.driver_reports_runtime_readiness = true; + let mut sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Ready); + sandbox.status = Some(SandboxStatus { + conditions: vec![SandboxCondition { + r#type: "Ready".to_string(), + status: "True".to_string(), + reason: "DependenciesReady".to_string(), + message: "Pod is Ready".to_string(), + transition_time: None, + }], + current_policy_version: 7, + ..Default::default() + }); + sandbox.set_phase(SandboxPhase::Ready as i32); + let ingress = SandboxIngressAdmission { + scope: openshell_core::proto::IngressScope::SharedHostLoopback as i32, + all_ports: false, + ports: vec![8080], + }; + sandbox.status.as_mut().unwrap().ingress_admission = Some(ingress.clone()); + runtime.store.put_message(&sandbox).await.unwrap(); - runtime - .apply_sandbox_update(DriverSandbox { - id: "sb-1".to_string(), - name: "sandbox-a".to_string(), - namespace: "default".to_string(), - spec: None, - status: None, - workspace: "default".to_string(), - }) - .await - .unwrap(); + runtime + .apply_sandbox_update(DriverSandbox { + id: "sb-1".to_string(), + name: "sandbox-a".to_string(), + namespace: "default".to_string(), + spec: None, + status: observed_status, + workspace: "default".to_string(), + }) + .await + .unwrap(); - let stored = runtime - .store - .get_message::("sb-1") - .await - .unwrap() - .unwrap(); - assert_eq!( - SandboxPhase::try_from(stored.phase()).unwrap(), - SandboxPhase::Ready - ); - assert_eq!(stored.current_policy_version(), 7); - let ready = stored - .status - .as_ref() - .and_then(|status| { - status - .conditions - .iter() - .find(|condition| condition.r#type == "Ready") - }) - .unwrap(); - assert_eq!(ready.status, "True"); - assert_eq!(ready.reason, "DependenciesReady"); - assert_eq!(ready.message, "Pod is Ready"); + let stored = runtime + .store + .get_message::("sb-1") + .await + .unwrap() + .unwrap(); + assert_eq!( + SandboxPhase::try_from(stored.phase()).unwrap(), + SandboxPhase::Ready + ); + assert_eq!(stored.current_policy_version(), 7); + assert_eq!( + stored.status.as_ref().unwrap().ingress_admission.as_ref(), + Some(&ingress) + ); + let ready = stored + .status + .as_ref() + .and_then(|status| { + status + .conditions + .iter() + .find(|condition| condition.r#type == "Ready") + }) + .unwrap(); + assert_eq!(ready.status, "True"); + assert_eq!(ready.reason, "DependenciesReady"); + assert_eq!(ready.message, "Pod is Ready"); + } } #[tokio::test] @@ -20103,59 +20228,71 @@ endpoint = { kind = "unix", socket_path = "/run/agent-substrate/isolation.sock" #[tokio::test] #[cfg(unix)] - async fn remote_compute_driver_rejects_policy_changes_before_forwarding() { + async fn changed_driver_port_support_or_resource_policy_blocks_mutations() { use crate::test_support::{FakeComputeDriver, FakeComputeDriverCall}; - let dir = tempfile::tempdir().unwrap(); - let socket_path = dir.path().join("admission.sock"); - let driver = FakeComputeDriver::new(); - let _server = driver.serve_uds(&socket_path).unwrap(); - let endpoint = connect_remote_compute_driver("external-test", &socket_path) - .await - .unwrap(); - let remote = RemoteComputeDriver::new(endpoint.channel); - remote - .get_capabilities(Request::new(GetCapabilitiesRequest { - gateway: Some(gateway_metadata(ExtensionFamily::Compute)), - })) - .await - .unwrap(); - driver.set_admission_acknowledgement(String::new()); - driver.clear_calls(); - let sandbox = DriverSandbox::default(); - let status = remote - .validate_sandbox_create(Request::new(ValidateSandboxCreateRequest { - sandbox: Some(sandbox.clone()), - })) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::FailedPrecondition); - assert!( + for (initial_ingress, current_ingress) in [(true, true), (true, false), (false, true)] { + let dir = tempfile::tempdir().unwrap(); + let socket_path = dir.path().join("admission.sock"); + let driver = FakeComputeDriver::new(); + driver.set_validate_create_response( + initial_ingress.then(ValidateSandboxCreateResponse::default), + ); + let _server = driver.serve_uds(&socket_path).unwrap(); + let endpoint = connect_remote_compute_driver("external-test", &socket_path) + .await + .unwrap(); + let remote = RemoteComputeDriver::new(endpoint.channel); remote - .create_sandbox(Request::new(CreateSandboxRequest { - sandbox: Some(sandbox) + .get_capabilities(Request::new(GetCapabilitiesRequest { + gateway: Some(gateway_metadata(ExtensionFamily::Compute)), })) .await - .is_err() - ); - assert!( - remote - .start_sandbox(Request::new(StartSandboxRequest::default())) + .unwrap(); + if initial_ingress == current_ingress { + driver.set_admission_acknowledgement(String::new()); + } else { + driver.set_validate_create_response( + current_ingress.then(ValidateSandboxCreateResponse::default), + ); + } + driver.clear_calls(); + let sandbox = DriverSandbox::default(); + let status = remote + .validate_sandbox_create(Request::new(ValidateSandboxCreateRequest { + sandbox: Some(sandbox.clone()), + })) .await - .is_err() - ); - let status = openshell_core::compute::ComputeDriver::update_sandbox_configuration( - &remote, - Request::new( - openshell_core::proto::compute::v1::UpdateSandboxConfigurationRequest::default(), - ), - ) - .await - .unwrap_err(); - assert_eq!(status.code(), Code::FailedPrecondition); - assert_eq!( - driver.calls(), - vec![FakeComputeDriverCall::GetCapabilities; 4] - ); + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!( + remote + .create_sandbox(Request::new(CreateSandboxRequest { + sandbox: Some(sandbox) + })) + .await + .is_err() + ); + assert!( + remote + .start_sandbox(Request::new(StartSandboxRequest::default())) + .await + .is_err() + ); + let status = openshell_core::compute::ComputeDriver::update_sandbox_configuration( + &remote, + Request::new( + openshell_core::proto::compute::v1::UpdateSandboxConfigurationRequest::default( + ), + ), + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert_eq!( + driver.calls(), + vec![FakeComputeDriverCall::GetCapabilities; 4] + ); + } } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..07ae75d2d3 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -271,7 +271,12 @@ impl openshell_core::proto::sandbox_updates_server::SandboxUpdates for OpenShell [mutation_audit::requested("sandbox", &request.name)], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } } @@ -359,7 +364,12 @@ impl OpenShell for OpenShellService { [mutation_audit::requested("sandbox", &request.name)], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } async fn begin_rootfs_tar_staging( @@ -478,7 +488,12 @@ impl OpenShell for OpenShellService { ], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } async fn detach_sandbox_provider( @@ -495,7 +510,12 @@ impl OpenShell for OpenShellService { ], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } async fn get_sandbox_provider_status( @@ -537,7 +557,12 @@ impl OpenShell for OpenShellService { [mutation_audit::requested("sandbox", &request.name)], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } async fn start_sandbox( @@ -551,7 +576,12 @@ impl OpenShell for OpenShellService { [mutation_audit::requested("sandbox", &request.name)], ) }; - mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await + let mut response = + mutation_audit::audited(targets, mutation_replay::run(&self.state, request)).await?; + if let Some(sandbox) = response.get_mut().sandbox.as_mut() { + self.state.compute.project_ingress_admission(sandbox); + } + Ok(response) } async fn suspend_sandbox( diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..67446635cc 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -84,7 +84,7 @@ use crate::persistence::current_time_ms; const TCP_FORWARD_CHUNK_SIZE: usize = 64 * 1024; const NO_LOGIN_SHELL_ENV: (&str, &str) = ("OPENSHELL_NO_LOGIN_SHELL", "1"); const MAX_TEMPLATES_PER_WORKSPACE: u32 = 1000; -const MAX_CREATE_SERVICE_EXPOSURES: usize = 32; +const MAX_CREATE_INGRESS_PORTS: usize = 32; const SANDBOX_CAS_RETRY_LIMIT: usize = 16; #[cfg(test)] @@ -370,7 +370,7 @@ pub(super) async fn handle_update_sandbox( Ok(Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), })) } @@ -783,12 +783,18 @@ async fn handle_create_sandbox_inner( state .compute .validate_launch_signer_configured(state.sandbox_session_jwt_authority.is_some())?; - state + let ingress_admission = state .compute .validate_sandbox_create_with_runtime_inputs( &sandbox, &runtime_inputs, await_main_process_attachment, + request.forward_ports.iter().copied().chain( + request + .service_exposures + .iter() + .map(|exposure| exposure.target_port), + ), ) .await .map_err(|status| { @@ -826,8 +832,8 @@ async fn handle_create_sandbox_inner( sandbox_token, await_main_process_attachment, runtime_inputs, - sandbox_lifecycle_guard, - mutation_guard, + ingress_admission, + (sandbox_lifecycle_guard, mutation_guard), )) .await?; @@ -894,11 +900,18 @@ async fn handle_create_sandbox_inner( Ok(Response::new(SandboxResponse { application_service_urls, gateway_service_urls, - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls, })) } +/// Project gateway-owned evidence on every outward sandbox value without +/// rewriting retained legacy records or accepting driver-supplied evidence. +fn project_public_sandbox(state: &ServerState, mut sandbox: Sandbox) -> Sandbox { + state.compute.project_ingress_admission(&mut sandbox); + sandbox +} + fn validate_create_sandbox_request_pre_io( request: &CreateSandboxRequest, workload_template_name: &str, @@ -907,9 +920,23 @@ fn validate_create_sandbox_request_pre_io( crate::grpc::validation::validate_labels(&request.labels)?; crate::grpc::validation::validate_caller_annotations(&request.annotations, "annotations")?; - if request.service_exposures.len() > MAX_CREATE_SERVICE_EXPOSURES { + if request.forward_ports.len() > MAX_CREATE_INGRESS_PORTS { + return Err(Status::invalid_argument(format!( + "forward_ports must contain at most {MAX_CREATE_INGRESS_PORTS} entries" + ))); + } + if request + .forward_ports + .iter() + .any(|port| !(1..=65535).contains(port)) + { + return Err(Status::invalid_argument( + "forward_ports must be between 1 and 65535", + )); + } + if request.service_exposures.len() > MAX_CREATE_INGRESS_PORTS { return Err(Status::invalid_argument(format!( - "service_exposures must contain at most {MAX_CREATE_SERVICE_EXPOSURES} entries" + "service_exposures must contain at most {MAX_CREATE_INGRESS_PORTS} entries" ))); } let mut service_names = HashSet::with_capacity(request.service_exposures.len()); @@ -1101,7 +1128,7 @@ pub(super) async fn handle_get_sandbox( let mut response = Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), }); if let Some(value) = owner.and_then(|owner| owner.parse().ok()) { @@ -1163,11 +1190,14 @@ pub(super) async fn handle_list_sandboxes( label_selector: selector, }, }; - let page = state + let mut page = state .store .list_message_page::(query, after.as_ref(), pagination.page_size()) .await .map_err(|e| Status::internal(format!("list sandboxes failed: {e}")))?; + for sandbox in &mut page.messages { + state.compute.project_ingress_admission(sandbox); + } let next_page_token = pagination.next_object_token(page.next_cursor.as_ref()); Ok(Response::new(ListSandboxesResponse { sandboxes: page.messages, @@ -1695,7 +1725,7 @@ pub(super) async fn handle_attach_sandbox_provider( ); Ok(Response::new(AttachSandboxProviderResponse { - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), attached, receipt: Some(receipt), })) @@ -1823,7 +1853,7 @@ pub(super) async fn handle_detach_sandbox_provider( ); Ok(Response::new(DetachSandboxProviderResponse { - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), detached, receipt: Some(receipt), })) @@ -1935,7 +1965,7 @@ async fn handle_stop_sandbox_inner( Ok(Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), })) } @@ -1995,7 +2025,7 @@ async fn handle_start_sandbox_inner( Ok(Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), })) } @@ -2038,7 +2068,7 @@ async fn handle_suspend_sandbox_inner( Ok(Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), })) } @@ -2099,7 +2129,7 @@ async fn handle_resume_sandbox_inner( Ok(Response::new(SandboxResponse { application_service_urls: HashMap::new(), gateway_service_urls: HashMap::new(), - sandbox: Some(sandbox), + sandbox: Some(project_public_sandbox(state, sandbox)), service_urls: HashMap::new(), })) } @@ -2297,7 +2327,7 @@ pub(super) async fn handle_watch_sandbox( .send(Ok(SandboxStreamEvent { payload: Some( openshell_core::proto::sandbox_stream_event::Payload::Sandbox( - sandbox.clone(), + project_public_sandbox(&state, sandbox.clone()), ), ), // Status snapshots are re-read, not resumed by cursor. @@ -2577,7 +2607,7 @@ pub(super) async fn handle_watch_sandbox( match state.store.get_message::(&sandbox_id).await { Ok(Some(sandbox)) => { state.sandbox_index.update_from_sandbox(&sandbox); - if tx.send(Ok(SandboxStreamEvent { payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(sandbox.clone())), cursor: String::new() })).await.is_err() { + if tx.send(Ok(SandboxStreamEvent { payload: Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(project_public_sandbox(&state, sandbox.clone()))), cursor: String::new() })).await.is_err() { return; } if stop_on_terminal { @@ -2949,6 +2979,10 @@ pub(super) async fn handle_forward_tcp( ) .await?; + if let relay_open::Target::Tcp(target) = &target { + state.compute.admit_ingress_port(&sandbox, target.port)?; + } + // The main process may finish between minting the SSH token and opening // its transport. Keep the relay reachable until terminal delivery is // finalized so fast commands can attach without a readiness race. @@ -4615,6 +4649,241 @@ mod tests { assert!(driver.calls().is_empty(), "{:?}", driver.calls()); } + async fn ingress_test_state( + negotiated: bool, + admission: Option, + ) -> ( + Arc, + Arc, + ) { + use openshell_core::proto::compute::v1::ValidateSandboxCreateResponse; + let driver = Arc::new(crate::test_support::FakeComputeDriver::new()); + driver.set_validate_create_response(negotiated.then_some(ValidateSandboxCreateResponse { + ingress_admission: admission, + })); + let mut state = test_server_state().await; + let compute = crate::compute::ComputeRuntime::from_driver( + "test".into(), + driver.clone(), + None, + state.store.clone(), + crate::sandbox_index::SandboxIndex::new(), + crate::sandbox_watch::SandboxWatchBus::new(), + crate::tracing_bus::TracingLogBus::new(), + Arc::new(crate::supervisor_session::SupervisorSessionRegistry::new()), + ) + .await + .unwrap(); + Arc::get_mut(&mut state).unwrap().compute = compute; + (state, driver) + } + + #[tokio::test] + async fn create_checks_forward_and_http_ports_before_provisioning() { + use crate::test_support::FakeComputeDriverCall; + use openshell_core::proto::{IngressScope, SandboxIngressAdmission}; + use tonic::Code; + + let exact = SandboxIngressAdmission { + scope: IngressScope::SharedHostLoopback as i32, + ports: vec![8080], + all_ports: false, + }; + let denied = Some(( + Code::FailedPrecondition, + "the compute driver does not allow this target port", + )); + // Both request fields must reject a denied port before the driver creates anything. + for (negotiated, admission, port, forward, error) in [ + (true, Some(exact.clone()), 8080, false, None), + (true, Some(exact.clone()), 8080, true, None), + (true, Some(exact.clone()), 8081, false, denied), + (true, Some(exact.clone()), 8081, true, denied), + (false, None, 8081, true, None), + ( + true, + None, + 8080, + true, + Some(( + Code::FailedPrecondition, + "advertised service port checks but returned no decision", + )), + ), + ( + true, + Some(SandboxIngressAdmission::default()), + 8080, + true, + Some(( + Code::FailedPrecondition, + "allowed service ports are unavailable for this sandbox. Recreate the sandbox", + )), + ), + ( + true, + Some(SandboxIngressAdmission::UNSUPPORTED), + 8080, + true, + Some(( + Code::FailedPrecondition, + "does not support service forwarding", + )), + ), + ( + true, + Some(exact), + 0, + true, + Some(( + Code::InvalidArgument, + "forward_ports must be between 1 and 65535", + )), + ), + ( + true, + Some(SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS), + 8081, + true, + None, + ), + ] { + let (state, driver) = ingress_test_state(negotiated, admission.clone()).await; + let result = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "ingress".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + spec: Some(SandboxSpec { + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + forward_ports: if forward { vec![port] } else { vec![] }, + service_exposures: if forward { + vec![] + } else { + vec![SandboxServiceExposure { + target_port: port, + ..Default::default() + }] + }, + ..Default::default() + }), + ) + .await; + if let Some((code, diagnostic)) = error { + let status = result.unwrap_err(); + assert_eq!(status.code(), code, "{status}"); + assert!(status.message().contains(diagnostic), "{status}"); + } else { + result.unwrap(); + } + let accepted = error.is_none(); + let provisioned = driver + .calls() + .iter() + .any(|call| matches!(call, FakeComputeDriverCall::CreateSandbox { .. })); + assert_eq!(provisioned, accepted); + let stored = state + .store + .get_message_by_name::("default", "ingress") + .await + .unwrap(); + assert_eq!(stored.is_some(), accepted); + if accepted { + let sandbox = stored.unwrap(); + assert_eq!( + sandbox.status.as_ref().unwrap().ingress_admission, + admission + ); + if let Some(approved) = &admission { + assert_eq!( + state.compute.ingress_admission(&sandbox).unwrap().scope() as i32, + approved.scope + ); + } + if forward && admission.as_ref().is_some_and(|ingress| !ingress.all_ports) { + let status = super::super::service::expose_service_endpoint( + &state, + "default", + &sandbox, + "unadmitted", + 8081, + ServiceAuthorizationMode::Strip, + ServiceBackendHttpVersion::Http1, + ) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!( + status + .message() + .contains("the compute driver does not allow this target port") + ); + assert!( + state + .store + .get_message_by_name::( + "default", + "ingress--unadmitted" + ) + .await + .unwrap() + .is_none() + ); + } + } + } + } + + #[tokio::test] + async fn direct_create_validates_driver_ports_before_saving_them() { + use openshell_core::proto::{IngressScope, SandboxIngressAdmission}; + + let approved = SandboxIngressAdmission { + scope: IngressScope::SharedHostLoopback as i32, + ports: vec![8080], + all_ports: false, + }; + let duplicate = SandboxIngressAdmission { + ports: vec![8080, 8080], + ..approved.clone() + }; + let conflicting = SandboxIngressAdmission { + all_ports: true, + ..approved.clone() + }; + for (admission, error) in [ + (Some(approved), None), + (None, None), + ( + Some(duplicate), + Some("allowed service ports must be unique and between 1 and 65535"), + ), + ( + Some(conflicting), + Some("invalid service port list from the compute driver"), + ), + ] { + let (state, _) = ingress_test_state(admission.is_some(), admission.clone()).await; + let mut sandbox = test_sandbox("direct-create", vec![]); + sandbox.status.as_mut().unwrap().ingress_admission = + Some(SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS); + let id = sandbox.object_id().to_owned(); + let result = state.compute.create_sandbox(sandbox, None, false).await; + let stored = state.store.get_message::(&id).await.unwrap(); + if let Some(reason) = error { + let status = result.unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + assert_eq!(status.message(), reason); + assert!(stored.is_none()); + } else { + result.unwrap(); + assert_eq!(stored.unwrap().status.unwrap().ingress_admission, admission); + } + } + } + #[tokio::test] async fn missing_launch_signer_precedes_driver_validation_and_preserves_staged_archive() { let directory = tempfile::tempdir().unwrap(); @@ -7562,6 +7831,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -7637,6 +7907,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -7675,6 +7946,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -7757,6 +8029,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8154,6 +8427,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8217,6 +8491,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8542,6 +8817,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8613,6 +8889,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8664,6 +8941,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -8708,6 +8986,7 @@ mod tests { await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9368,6 +9647,7 @@ mod tests { workload_template: "gpu-kata".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9457,6 +9737,7 @@ mod tests { workload_template: "default-image".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9511,6 +9792,7 @@ mod tests { workload_template: "default-gpu".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9552,6 +9834,7 @@ mod tests { workload_template: "corrupt-template".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9594,6 +9877,7 @@ mod tests { workload_template: "gpu-kata".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9621,6 +9905,7 @@ mod tests { workload_template: "Invalid_Template_Name".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9651,6 +9936,7 @@ mod tests { workload_template: "missing-template".to_string(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await @@ -9681,6 +9967,7 @@ mod tests { workload_template: String::new(), await_main_process_attachment: false, service_exposures: Vec::new(), + forward_ports: Vec::new(), }), ) .await diff --git a/crates/openshell-server/src/grpc/sandbox/image_update_tests.rs b/crates/openshell-server/src/grpc/sandbox/image_update_tests.rs index e83d786ee0..e00ccd1d21 100644 --- a/crates/openshell-server/src/grpc/sandbox/image_update_tests.rs +++ b/crates/openshell-server/src/grpc/sandbox/image_update_tests.rs @@ -135,7 +135,10 @@ async fn state() -> (Arc, Arc, Sandbox) { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/image-test", "test", - [openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION.into()], + [ + openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION.into(), + openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.into(), + ], )), ..Default::default() }), @@ -258,6 +261,20 @@ async fn public_image_update_replays_without_reapplying_or_touching_same_name_re .sandbox .unwrap(); assert_eq!(updated.object_id(), sandbox.object_id()); + assert_eq!( + updated.status.as_ref().unwrap().ingress_admission, + Some(openshell_core::proto::SandboxIngressAdmission::default()) + ); + let stored = state + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + assert!( + stored.status.as_ref().unwrap().ingress_admission.is_none(), + "inspection projection must not invent durable admission evidence" + ); assert_eq!( updated .spec diff --git a/crates/openshell-server/src/grpc/service.rs b/crates/openshell-server/src/grpc/service.rs index 5c95fef3b0..78c2128138 100644 --- a/crates/openshell-server/src/grpc/service.rs +++ b/crates/openshell-server/src/grpc/service.rs @@ -132,6 +132,7 @@ pub(super) async fn expose_service_endpoint( }) .ok_or_else(|| Status::not_found("sandbox removed"))?; let sandbox = ¤t; + state.compute.admit_ingress_port(sandbox, target_port)?; let sandbox_name = sandbox.object_name(); let now = crate::persistence::current_time_ms(); @@ -454,6 +455,10 @@ pub(super) fn configured_app_routes_from_endpoints( if !state.config.supervisor_app_listener.enabled { return Ok(Vec::new()); } + let Ok(admission) = state.compute.ingress_admission(sandbox) else { + // Withhold routes while continuing to deliver the sandbox's policy. + return Ok(Vec::new()); + }; let mut service_routes: Vec<_> = endpoints .into_iter() .filter(|ep| { @@ -463,6 +468,7 @@ pub(super) fn configured_app_routes_from_endpoints( .metadata .as_ref() .is_none_or(|m| m.deletion_time.is_none()) + && admission.admit_port(ep.target_port).is_ok() }) .map(|ep| { Ok(openshell_core::proto::SandboxServiceRoute { @@ -902,17 +908,31 @@ mod tests { .await .unwrap() .unwrap(); - let sandbox = state + let mut sandbox = state .store .get_message::(&stored.sandbox_id) .await .unwrap() .unwrap(); - let routes = configured_app_routes_from_endpoints(&state, &sandbox, vec![stored]).unwrap(); + let routes = + configured_app_routes_from_endpoints(&state, &sandbox, vec![stored.clone()]).unwrap(); assert_eq!( routes[0].backend_http_version, ServiceBackendHttpVersion::Http2 as i32 ); + + // A retained endpoint may predate the sandbox's current ingress contract. + sandbox.status.as_mut().unwrap().ingress_admission = + Some(openshell_core::proto::SandboxIngressAdmission { + scope: openshell_core::proto::IngressScope::IsolatedLoopback as i32, + ports: vec![8080], + all_ports: false, + }); + assert!( + configured_app_routes_from_endpoints(&state, &sandbox, vec![stored]) + .unwrap() + .is_empty() + ); } #[tokio::test] diff --git a/crates/openshell-server/src/service_routing.rs b/crates/openshell-server/src/service_routing.rs index dfd84ff9d6..bf68a4fa4d 100644 --- a/crates/openshell-server/src/service_routing.rs +++ b/crates/openshell-server/src/service_routing.rs @@ -733,6 +733,23 @@ async fn proxy_to_endpoint( return Err(err); } + if state + .compute + .admit_ingress_port(&sandbox, endpoint.target_port) + .is_err() + { + let err = ServiceRouteError::endpoint_unavailable(); + emit_service_http_failure( + &state, + &req, + &sandbox_name, + &service_name, + Some(&endpoint), + &err, + ); + return Err(err); + } + let websocket_upgrade = is_websocket_upgrade(&req); let downstream_upgrade = websocket_upgrade.then(|| hyper::upgrade::on(&mut req)); @@ -2422,19 +2439,53 @@ mod tests { } #[tokio::test] - async fn pool_hands_back_a_ready_upstream() { - let pool = ServiceUpstreamPool::default(); - let (sender, _sandbox) = test_upstream().await; - - pool.put("ep-a|8080", sender); - + async fn denied_service_port_leaves_the_pooled_connection_available() { + use openshell_core::proto::{IngressScope, SandboxIngressAdmission}; + let state = crate::grpc::test_support::test_server_state().await; + let endpoint = endpoint(); + let mut sandbox = Sandbox { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: endpoint.sandbox_id.clone(), + name: endpoint.sandbox.clone(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + sandbox.status.as_mut().unwrap().ingress_admission = Some(SandboxIngressAdmission { + scope: IngressScope::SharedHostLoopback as i32, + all_ports: false, + ports: vec![9090], + }); + state.store.put_message(&sandbox).await.unwrap(); + state.store.put_message(&endpoint).await.unwrap(); + let key = upstream_pool_key(endpoint.object_id(), 8080); + let (sender, _peer) = test_upstream().await; + state.service_upstreams.put(&key, sender); + let result = tokio::time::timeout( + Duration::from_millis(250), + proxy_to_endpoint( + state.clone(), + Request::builder().uri("/").body(Body::empty()).unwrap(), + "default", + endpoint.sandbox, + endpoint.name, + ), + ) + .await + .expect("an unadmitted route must reject before pooled I/O"); + assert_eq!( + result.unwrap_err().reason, + ServiceRouteError::endpoint_unavailable().reason + ); assert!( - pool.take("ep-a|8080").is_some(), - "put upstream should be reusable" + state.service_upstreams.take(&key).is_some(), + "admission must precede taking any pooled connection" ); assert!( - pool.take("ep-a|8080").is_none(), - "an upstream in use must not be handed out twice" + state.service_upstreams.take(&key).is_none(), + "a pooled connection can only be checked out once" ); } diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..3a45087878 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,14 +251,16 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. + // Ingress admission adds one status message and scope enum to both schemas. + // Older sandboxes decode with no envelope. Forward ports are request-only. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "b6302b1c51b8e9c8f05503dabfd4ccf7faafbfc95278557cbb67efce94ffc129"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "2f8aa1d5c2bb7ada8d1c72f7a0e8255572dc92a554f46514647d801c5b1e13d7"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; + "4bc5207a374b50b60ce07e872429a0676a208888b2422c7f2b904f1cbcb17519"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -817,9 +819,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), - (104, 23), - (88, 23), + (370, 33), + (105, 24), + (89, 24), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 @@ -883,6 +885,7 @@ mod tests { assert!(status.configuration_admission.is_none()); assert_eq!(status.configuration_activated, None); assert!(status.provisioning.is_none()); + assert!(status.ingress_admission.is_none()); assert!(!crate::policy_store::permits_initial_static_policy_repair( &sandbox )); diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 969e05928b..5ee7dc6260 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -167,6 +167,7 @@ pub struct FakeComputeDriver { #[derive(Debug)] struct FakeComputeDriverState { capabilities: GetCapabilitiesResponse, + validate_create_response: Option, sandboxes: HashMap, calls: Vec, traceparents: Vec, @@ -189,10 +190,16 @@ impl FakeComputeDriver { self } + /// Configuring a validation reply also advertises the driver's service-port capability. + pub fn set_validate_create_response(&self, response: Option) { + self.with_state(|state| state.validate_create_response = response); + } + #[must_use] pub fn new() -> Self { Self { state: Arc::new(Mutex::new(FakeComputeDriverState { + validate_create_response: None, capabilities: GetCapabilitiesResponse { resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig::default() @@ -446,7 +453,15 @@ impl ComputeDriver for FakeComputeDriver { self.record_traceparent(request.metadata()); let response = self.with_state(|state| { state.calls.push(FakeComputeDriverCall::GetCapabilities); - state.capabilities.clone() + let mut response = state.capabilities.clone(); + if state.validate_create_response.is_some() + && let Some(extension) = &mut response.extension + { + extension + .supported_capabilities + .push(openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.into()); + } + response }); Ok(Response::new(response)) } @@ -457,14 +472,15 @@ impl ComputeDriver for FakeComputeDriver { ) -> Result, Status> { self.record_traceparent(request.metadata()); let request = request.into_inner(); - self.with_state(|state| { + let response = self.with_state(|state| { state .calls .push(FakeComputeDriverCall::ValidateSandboxCreate { sandbox: request.sandbox, }); + state.validate_create_response.clone().unwrap_or_default() }); - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(response)) } async fn get_sandbox( diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 8c18c8ccb4..88bd8ea83a 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -324,7 +324,7 @@ pub struct CreateSandboxForm { /// When the create animation started (for pacman timing). pub anim_start: Option, /// Buffered create result — held until min display time elapses. - pub create_result: Option>, + pub create_result: Option>, } // --------------------------------------------------------------------------- @@ -720,8 +720,6 @@ pub struct App { // Create sandbox modal pub create_form: Option, pub pending_create_sandbox: bool, - /// Forward specs to apply after sandbox creation completes. - pub pending_forward_ports: Vec, /// Parsed arguments to exec via SSH after sandbox creation completes. pub pending_exec_command: Vec, /// Animation ticker handle — aborted when animation stops. @@ -1080,7 +1078,6 @@ impl App { policy_viewport_height: 0, create_form: None, pending_create_sandbox: false, - pending_forward_ports: Vec::new(), pending_exec_command: Vec::new(), anim_handle: None, sandbox_log_lines: Vec::new(), diff --git a/crates/openshell-tui/src/event.rs b/crates/openshell-tui/src/event.rs index 36831d6b48..c898c2cfe7 100644 --- a/crates/openshell-tui/src/event.rs +++ b/crates/openshell-tui/src/event.rs @@ -24,8 +24,8 @@ pub enum Event { ListRefreshCompleted(crate::ListRefreshResult), /// Completed per-sandbox draft-count refresh from a background task. DraftCountsRefreshCompleted(crate::DraftCountsRefreshResult), - /// Identity returned by the create sandbox request. - CreateResult(Result), + /// The created sandbox and its forwarding results. + CreateResult(Result), /// Result of creating a provider on the gateway: `Ok(name)` or `Err(message)`. ProviderCreateResult(Result), /// Provider detail fetched from gateway. @@ -55,8 +55,6 @@ pub enum Event { SandboxSettingSetResult(Result), /// Sandbox setting delete result: `Ok(revision)` or `Err(message)`. SandboxSettingDeleteResult(Result), - /// Non-fatal warnings from port-forward setup after sandbox creation. - ForwardWarnings(Vec), } pub struct EventHandler { diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index c6464157a9..b68b1dfd8c 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -24,7 +24,9 @@ use openshell_bootstrap::list_gateways_with_source; use openshell_core::auth::EdgeAuthInterceptor; use openshell_core::metadata::{ObjectId, ObjectLabels, ObjectName, ObjectWorkspace}; use openshell_core::proto::open_shell_client::OpenShellClient; -use openshell_core::proto::{SandboxPhase, SandboxRestartPolicy}; +use openshell_core::proto::{ + IngressScope, SandboxIngressAdmission, SandboxPhase, SandboxRestartPolicy, +}; use openshell_core::ssh_handoff::{SshCleanup, SshTarget}; use ratatui::Terminal; use ratatui::backend::CrosstermBackend; @@ -45,6 +47,12 @@ const DRAFT_COUNT_REFRESH_CONCURRENCY: usize = 16; type ProviderProfileCache = HashMap<(String, String), openshell_core::proto::ProviderProfile>; type TuiClient = OpenShellClient>; +#[derive(Debug)] +pub(crate) struct CreatedSandbox { + target: SshTarget, + message: String, +} + #[derive(Debug)] pub(crate) struct ListRefreshResult { generation: u64, @@ -176,12 +184,7 @@ pub async fn run_with_gateway_insecure( } if app.pending_create_sandbox { app.pending_create_sandbox = false; - spawn_create_sandbox( - &mut app, - events.sender(), - &mut create_tasks, - &ssh_cleanup, - ); + spawn_create_sandbox(&app, events.sender(), &mut create_tasks, &ssh_cleanup); start_anim_ticker(&mut app, events.sender()); } // --- Provider CRUD --- @@ -384,9 +387,6 @@ pub async fn run_with_gateway_insecure( } fetch_sandbox_detail(&mut app).await; } - Some(Event::ForwardWarnings(warnings)) => { - app.status_text = format!("port forward issues: {}", warnings.join("; ")); - } Some(Event::Mouse(mouse)) => match mouse.kind { MouseEventKind::ScrollUp if app.focus == Focus::SandboxLogs => { app.scroll_logs(-3); @@ -445,33 +445,23 @@ pub async fn run_with_gateway_insecure( h.abort(); } match result { - Some(Ok(target)) => { + Some(Ok(CreatedSandbox { target, message })) => { app.create_form = None; - let ports = std::mem::take(&mut app.pending_forward_ports); let command = std::mem::take(&mut app.pending_exec_command); - let port_info = if ports.is_empty() { - String::new() + if command.is_empty() { + app.status_text = message; } else { - let list = ports - .iter() - .map(ToString::to_string) - .collect::>() - .join(", "); - format!(" (forwarding port(s) {list})") - }; - app.status_text = - format!("Created sandbox: {}{port_info}", target.name); - - // If a command was specified, suspend TUI and exec it. - if !command.is_empty() { run_sandbox_ssh( &mut app, &mut terminal, &mut events, &target, &command, + Some(&message), ) .await?; + app.status_text.push_str(". "); + app.status_text.push_str(&message); } app.cancel_list_refresh(); spawn_list_refresh(&mut app, events.sender()); @@ -1000,7 +990,7 @@ async fn handle_shell_connect( ); target.cleanup.clone_from(cleanup); target.gateway_insecure = app.gateway_insecure; - run_sandbox_ssh(app, terminal, events, &target, &[]).await + run_sandbox_ssh(app, terminal, events, &target, &[], None).await } async fn run_sandbox_ssh( @@ -1009,6 +999,7 @@ async fn run_sandbox_ssh( events: &mut EventHandler, target: &SshTarget, args: &[String], + create_message: Option<&str>, ) -> Result<()> { if target.gateway_name != app.gateway_name || target.endpoint != app.endpoint @@ -1064,6 +1055,9 @@ async fn run_sandbox_ssh( .into_diagnostic()?; disable_raw_mode().into_diagnostic()?; + if let Some(message) = create_message { + eprintln!("{message}"); + } if let Some(warning) = &unverified_warning { eprintln!("{warning}"); } @@ -1358,7 +1352,7 @@ fn start_anim_ticker(app: &mut App, tx: mpsc::UnboundedSender) { // --------------------------------------------------------------------------- fn spawn_create_sandbox( - app: &mut App, + app: &App, tx: mpsc::UnboundedSender, create_tasks: &mut tokio::task::JoinSet<()>, cleanup: &SshCleanup, @@ -1368,9 +1362,6 @@ fn spawn_create_sandbox( return; }; - // Stash ports so we can include them in the status text. - app.pending_forward_ports.clone_from(&ports); - let endpoint = app.endpoint.clone(); let gateway_name = app.gateway_name.clone(); let gateway_insecure = app.gateway_insecure; @@ -1415,6 +1406,7 @@ fn spawn_create_sandbox( await_main_process_attachment: false, workload_template: String::new(), service_exposures: Vec::new(), + forward_ports: ports.iter().map(|spec| u32::from(spec.port)).collect(), }; let created = @@ -1447,27 +1439,34 @@ fn spawn_create_sandbox( ); target.cleanup = cleanup; target.gateway_insecure = gateway_insecure; + let mut message = format!("Created sandbox: {}", target.name); // If ports or command are set, wait for Ready before finishing. if need_ready { - if let Err(error) = wait_for_ssh_target(&mut client, &mut target).await { - let _ = tx.send(Event::CreateResult(Err(error.to_string()))); - return; - } + let admission = match wait_for_ssh_target(&mut client, &mut target).await { + Ok(admission) => admission, + Err(error) => { + let _ = tx.send(Event::CreateResult(Err(error.to_string()))); + return; + } + }; - // Start port forwards if requested. if !ports.is_empty() { - let forward_warnings = start_port_forwards(&target, &client, &ports).await; - if !forward_warnings.is_empty() { - let _ = tx.send(Event::ForwardWarnings(forward_warnings)); - } + let details = + start_port_forwards(&target, &client, &ports, admission.as_ref()).await; + message.push_str(" ("); + message.push_str(&details.join(". ")); + message.push(')'); } } - let _ = tx.send(Event::CreateResult(Ok(target))); + let _ = tx.send(Event::CreateResult(Ok(CreatedSandbox { target, message }))); }); } -async fn wait_for_ssh_target(client: &mut TuiClient, target: &mut SshTarget) -> Result<()> { +async fn wait_for_ssh_target( + client: &mut TuiClient, + target: &mut SshTarget, +) -> Result> { tokio::time::timeout(Duration::from_mins(5), async { loop { tokio::time::sleep(Duration::from_secs(2)).await; @@ -1485,7 +1484,11 @@ async fn wait_for_ssh_target(client: &mut TuiClient, target: &mut SshTarget) -> }; let phase = target.observe_lookup(&response)?.phase(); if phase == SandboxPhase::Ready as i32 { - return Ok(()); + return Ok(response + .into_inner() + .sandbox + .and_then(|sandbox| sandbox.status) + .and_then(|status| status.ingress_admission)); } if phase == SandboxPhase::Error as i32 { return Err(miette::miette!("sandbox entered error state")); @@ -1504,8 +1507,24 @@ async fn start_port_forwards( target: &SshTarget, client: &TuiClient, specs: &[openshell_core::forward::ForwardSpec], + admission: Option<&SandboxIngressAdmission>, ) -> Vec { - let mut warnings = Vec::new(); + let admission = match openshell_core::ingress::IngressAdmission::from_status(admission, false) { + Ok(admission) => admission, + Err(error) => return vec![format!("Forwarding skipped: {error}")], + }; + for spec in specs { + if let Err(error) = admission.admit_port(u32::from(spec.port)) { + return vec![format!( + "Forwarding skipped for port {}: {error}", + spec.port + )]; + } + } + let mut details = Vec::new(); + if admission.scope() == IngressScope::SharedHostLoopback { + details.push("Target uses shared-host loopback".to_string()); + } let sandbox_id = &target.id; for spec in specs { let proxy = match tokio::time::timeout( @@ -1516,21 +1535,21 @@ async fn start_port_forwards( { Ok(Ok(proxy)) => proxy, Ok(Err(error)) => { - warnings.push(format!( + details.push(format!( "SSH session failed for forwards: {}", first_line(&error) )); break; } Err(_) => { - warnings.push("SSH session timed out for forwards".into()); + details.push("SSH session timed out for forwards".into()); break; } }; if let Some(warning) = proxy.command().unverified_warning() - && !warnings.contains(&warning) + && !details.contains(&warning) { - warnings.push(warning); + details.push(warning); } let ssh_forward_arg = spec.ssh_forward_arg(); let port_val = spec.port; @@ -1541,6 +1560,8 @@ async fn start_port_forwards( .args(sandbox_ssh_args(proxy.command(), "ERROR")) .arg("-o") .arg("ConnectTimeout=15") + .arg("-o") + .arg("ExitOnForwardFailure=yes") .arg("-N") .arg("-f") .arg("-o") @@ -1568,6 +1589,7 @@ async fn start_port_forwards( match result { Ok(true) => { + details.push(format!("Forwarding {spec}")); if let Some(pid) = openshell_core::forward::find_ssh_forward_pid( &target.workspace, &target.name, @@ -1585,13 +1607,13 @@ async fn start_port_forwards( } } Ok(false) => { - warnings.push(format!("SSH forward exited with error for port {port_val}")); + details.push(format!("SSH forward exited with error for port {port_val}")); } - Err(e) => warnings.push(format!("forward failed for port {port_val}: {e}")), + Err(e) => details.push(format!("forward failed for port {port_val}: {e}")), } } - warnings + details } // --------------------------------------------------------------------------- diff --git a/crates/openshell-tui/src/ui/create_sandbox.rs b/crates/openshell-tui/src/ui/create_sandbox.rs index 83ce8683ca..3678249739 100644 --- a/crates/openshell-tui/src/ui/create_sandbox.rs +++ b/crates/openshell-tui/src/ui/create_sandbox.rs @@ -282,7 +282,7 @@ fn draw_creating(frame: &mut Frame<'_>, app: &App, area: Rect) { // Header — changes once result arrives. let (header, header_style) = match &form.create_result { - Some(Ok(target)) => (format!("Created sandbox: {}", target.name), t.status_ok), + Some(Ok(created)) => (created.message.clone(), t.status_ok), Some(Err(msg)) => (format!("Failed: {msg}"), t.status_err), None => ("Creating sandbox...".to_string(), t.text), }; diff --git a/docs/extensibility/isolation-backends.mdx b/docs/extensibility/isolation-backends.mdx index 0e50b59dbc..6562871eea 100644 --- a/docs/extensibility/isolation-backends.mdx +++ b/docs/extensibility/isolation-backends.mdx @@ -39,6 +39,11 @@ accept an operator-selected `IsolationBackendRegistration`, including its Unix, TCP, or vsock endpoint. The driver provisions the resource and delivers the backend's trusted launch metadata to the supervisor. +Drivers that advertise `openshell.compute.ingress-admission` return the allowed +ports and loopback destination from `ValidateSandboxCreate`. The gateway checks +TCP and HTTP routes. The isolation backend checks each SSH forwarding target +because the gateway carries an encrypted SSH session. + ## Who Owns What | Component | Owns | diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 74df07460d..18f4e6d436 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -837,6 +837,13 @@ Press `c` in the Sandboxes panel to create a sandbox. In the optional Command fi ## Port Forwarding +`openshell sandbox create --forward ` checks the target before creating +the sandbox. `openshell sandbox get` shows which ports the driver allows and +whether they reach the sandbox or the compute host's loopback. + +Upgrade gateway replicas together. If an existing sandbox reports +`Service ports: unavailable` after the upgrade, recreate it. + Forward a local port to a running sandbox to access services inside it, such as a web server or database: ```shell diff --git a/examples/isolation-backend-v8/src/driver.rs b/examples/isolation-backend-v8/src/driver.rs index 5bbdc8bcef..259309ec55 100644 --- a/examples/isolation-backend-v8/src/driver.rs +++ b/examples/isolation-backend-v8/src/driver.rs @@ -348,6 +348,7 @@ impl compute_driver_server::ComputeDriver for DriverService { [ extension_protocol::COMPUTE_LAUNCH_AUTHENTICATION.into(), extension_protocol::COMPUTE_ISOLATION_BACKEND.into(), + extension_protocol::COMPUTE_INGRESS_ADMISSION.into(), ], ); extension @@ -384,7 +385,9 @@ impl compute_driver_server::ComputeDriver for DriverService { .as_ref() .ok_or_else(|| Status::invalid_argument("sandbox required"))?, )?; - Ok(Response::new(ValidateSandboxCreateResponse {})) + Ok(Response::new(ValidateSandboxCreateResponse { + ingress_admission: Some(openshell_core::proto::SandboxIngressAdmission::UNSUPPORTED), + })) } async fn create_sandbox( &self, diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index 88d090fc18..828b351629 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -449,7 +449,11 @@ message ValidateSandboxCreateRequest { DriverSandbox sandbox = 1; } -message ValidateSandboxCreateResponse {} +message ValidateSandboxCreateResponse { + // Drivers advertising openshell.compute.ingress-admission must return a concrete + // scope and the ports their configuration allows for this sandbox's lifetime. + openshell.sandbox.v1.SandboxIngressAdmission ingress_admission = 1; +} message GetSandboxRequest { // Stable sandbox ID stored by the gateway. diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..36339f441f 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1398,6 +1398,9 @@ message SandboxStatus { // failures before a configured endpoint or credential could be selected. // Matching grant success or a policy, provider, or supervisor reset clears it. TokenGrantFailureObservation last_token_grant_failure = 17; + // The driver's decision at creation. Legacy forwarding omits this field. + // A gateway that requires a decision but has none reports UNSPECIFIED. + openshell.sandbox.v1.SandboxIngressAdmission ingress_admission = 19; } // User-facing sandbox condition derived from platform or gateway observations. @@ -1484,6 +1487,8 @@ message CreateSandboxRequest { // registered after the sandbox has been persisted and route only while the // sandbox is ready. repeated SandboxServiceExposure service_exposures = 9; + // Local forward targets to check before provisioning. The client opens the listeners. + repeated uint32 forward_ports = 10; } // Update selected configuration of a stopped sandbox. Omitted fields are unchanged. diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..a2a503760c 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -17,6 +17,27 @@ import "datamodel.proto"; // - Public sandbox resource types live in `openshell.proto`. // - Internal compute-driver sandbox observation types live in `compute_driver.proto`. +// Where service forwards connect and which target ports the driver allows. +message SandboxIngressAdmission { + IngressScope scope = 1; + // Allows every target port. Leave ports empty when true. + bool all_ports = 2; + // Unique TCP ports from 1 to 65535. An empty list with all_ports false allows none. + repeated uint32 ports = 3; +} + +// Identifies whose loopback a forwarded connection reaches. +enum IngressScope { + // The gateway has no saved decision for this sandbox. Forwarding is unavailable. + INGRESS_SCOPE_UNSPECIFIED = 0; + // The backend cannot forward service connections. It must allow no ports. + INGRESS_SCOPE_UNSUPPORTED = 1; + // A service inside the sandbox's network. + INGRESS_SCOPE_ISOLATED_LOOPBACK = 2; + // A service on the compute host's loopback that the operator allowed. + INGRESS_SCOPE_SHARED_HOST_LOOPBACK = 3; +} + // Sandbox security policy configuration. message SandboxPolicy { // Policy version. diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index ad75be85e0..c705177d47 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -603,12 +603,14 @@ fn grpc_create_request( command, tty, service_exposures: _, + forward_ports, restart_policy, } = spec; proto::CreateSandboxRequest { name: name.unwrap_or_default(), labels, workspace_scope, + forward_ports: forward_ports.into_iter().map(u32::from).collect(), spec: Some(proto::SandboxSpec { environment, template: (image.is_some() || driver_config.is_some()).then(|| { @@ -1101,13 +1103,14 @@ mod tests { let spec = SandboxSpec { image: Some("python:3".to_string()), providers: vec!["provider".to_string()], + forward_ports: vec![8080, 9090], ..SandboxSpec::default() }; let policy = crate::policy::base(); - let spec = grpc_create_request(spec, Some(policy.clone()), None, None) - .spec - .expect("spec"); + let request = grpc_create_request(spec, Some(policy.clone()), None, None); + assert_eq!(request.forward_ports, [8080, 9090]); + let spec = request.spec.expect("spec"); let template = spec.template.expect("template"); assert_eq!(template.image, "python:3"); From 422550f182cf83facbc7509b1ec7ce4db9df5302 Mon Sep 17 00:00:00 2001 From: Shiju Date: Wed, 18 Nov 2026 11:21:37 +0530 Subject: [PATCH 2/3] test(compute): cover sandbox port checks on replay and live forwards Exercise missing port information on reads, watches, and replayed responses. Check TCP and SSH separately and report denied TUI forwards before starting any listeners. Signed-off-by: Shiju --- crates/openshell-server/src/grpc/sandbox.rs | 192 ++++++++++++++++++++ crates/openshell-tui/src/lib.rs | 29 +++ 2 files changed, 221 insertions(+) diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 67446635cc..7e964515af 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -4884,6 +4884,198 @@ mod tests { } } + #[tokio::test] + async fn old_sandboxes_report_unavailable_ports_on_read_watch_and_replay() { + use futures::StreamExt as _; + use openshell_core::proto::SandboxIngressAdmission; + use openshell_core::proto::open_shell_server::OpenShell as _; + + let (mut state, _) = ingress_test_state(true, None).await; + let directory = tempfile::tempdir().unwrap(); + let key = directory.path().join("private-key"); + std::fs::write(&key, b"test-only stable fingerprint material").unwrap(); + Arc::get_mut(&mut state).unwrap().config.gateway_jwt = + Some(openshell_core::config::GatewayJwtConfig { + signing_key_path: key, + public_key_path: directory.path().join("public"), + kid_path: directory.path().join("kid"), + gateway_id: "test".into(), + ttl_secs: None, + }); + let mut legacy = Sandbox { + metadata: Some(ObjectMeta { + id: "legacy-ingress".into(), + name: "legacy-ingress".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + legacy.set_phase(SandboxPhase::Ready as i32); + state.store.put_message(&legacy).await.unwrap(); + let retained = state + .store + .get_message::("legacy-ingress") + .await + .unwrap() + .unwrap(); + let get = handle_get_sandbox( + &state, + authed_request(GetSandboxRequest { + name: "legacy-ingress".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + }), + ) + .await + .unwrap() + .into_inner() + .sandbox + .unwrap(); + let unavailable = Some(SandboxIngressAdmission::default()); + assert_eq!(get.status.unwrap().ingress_admission, unavailable); + + let service = crate::grpc::OpenShellService::new(state.clone()); + let start = StartSandboxRequest { + name: "legacy-ingress".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + request_id: uuid::Uuid::new_v4().to_string(), + }; + for replay in [false, true] { + let started = service + .start_sandbox(authed_request(start.clone())) + .await + .unwrap(); + assert_eq!( + started.metadata().contains_key("openshell-replayed"), + replay + ); + assert_eq!( + started + .into_inner() + .sandbox + .unwrap() + .status + .unwrap() + .ingress_admission, + unavailable + ); + } + let mut stream = handle_watch_sandbox( + &state, + authed_request(WatchSandboxRequest { + sandbox: "legacy-ingress".into(), + workspace_scope: Some(openshell_core::proto::workspace_selector("default")), + follow_status: true, + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + for updated in [false, true] { + if updated { + state.sandbox_watch_bus.notify("legacy-ingress"); + } + let event = tokio::time::timeout(std::time::Duration::from_secs(1), stream.next()) + .await + .unwrap() + .unwrap() + .unwrap(); + let Some(openshell_core::proto::sandbox_stream_event::Payload::Sandbox(snapshot)) = + event.payload + else { + panic!("expected status snapshot") + }; + assert_eq!(snapshot.status.unwrap().ingress_admission, unavailable); + } + assert!( + openshell_core::ingress::IngressAdmission::from_status(unavailable.as_ref(), false) + .is_err() + ); + assert_eq!( + state + .store + .get_message::("legacy-ingress") + .await + .unwrap() + .unwrap(), + retained + ); + } + + #[tokio::test] + async fn tcp_relay_checks_allowed_ports_and_leaves_ssh_independent() { + use openshell_core::proto::open_shell_client::OpenShellClient; + use openshell_core::proto::open_shell_server::OpenShellServer; + use openshell_core::proto::{IngressScope, SandboxIngressAdmission, tcp_forward_frame}; + use tokio_stream::wrappers::TcpListenerStream; + + let state = test_server_state().await; + let mut sandbox = Sandbox { + metadata: Some(ObjectMeta { + id: "ingress-live".into(), + name: "ingress-live".into(), + workspace: "default".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Stopped as i32); + sandbox.status.as_mut().unwrap().ingress_admission = Some(SandboxIngressAdmission { + scope: IngressScope::SharedHostLoopback as i32, + all_ports: false, + ports: vec![8080], + }); + state.store.put_message(&sandbox).await.unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(OpenShellServer::with_interceptor( + crate::OpenShellService::new(state), + crate::test_support::authenticate_as_dev_user, + )) + .serve_with_incoming(TcpListenerStream::new(listener)), + ); + let mut client = OpenShellClient::connect(format!("http://{address}")) + .await + .unwrap(); + for (target, diagnostic) in [ + ( + tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: "127.0.0.1".into(), + port: 8081, + }), + "the compute driver does not allow this target port", + ), + ( + tcp_forward_init::Target::Tcp(TcpRelayTarget { + host: "127.0.0.1".into(), + port: 8080, + }), + "sandbox is not ready", + ), + ( + tcp_forward_init::Target::Ssh(SshRelayTarget::default()), + "sandbox is not ready", + ), + ] { + let error = client + .forward_tcp(tokio_stream::iter([TcpForwardFrame { + payload: Some(tcp_forward_frame::Payload::Init(TcpForwardInit { + sandbox: "ingress-live".into(), + workspace: "default".into(), + target: Some(target), + ..Default::default() + })), + }])) + .await + .unwrap_err(); + assert!(error.message().contains(diagnostic), "{error}"); + } + server.abort(); + } + #[tokio::test] async fn missing_launch_signer_precedes_driver_validation_and_preserves_staged_archive() { let directory = tempfile::tempdir().unwrap(); diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index b68b1dfd8c..4daf7f95d3 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -3290,6 +3290,35 @@ mod provider_profile_pagination_tests { } } +#[cfg(test)] +mod forward_tests { + use super::*; + use openshell_core::forward::ForwardSpec; + + #[tokio::test] + async fn one_denied_port_skips_all_requested_forwards() { + let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); + let client = OpenShellClient::with_interceptor(channel, EdgeAuthInterceptor::noop()); + let target = SshTarget::new("http://127.0.0.1:1", "local", "app", "default", "app-id"); + let admission = SandboxIngressAdmission { + scope: IngressScope::SharedHostLoopback as i32, + ports: vec![8080], + all_ports: false, + }; + let details = start_port_forwards( + &target, + &client, + &[ForwardSpec::new(8080), ForwardSpec::new(9090)], + Some(&admission), + ) + .await; + assert_eq!(details.len(), 1); + assert!(details[0].starts_with( + "Forwarding skipped for port 9090: the compute driver does not allow this target port" + )); + } +} + #[cfg(test)] mod sandbox_notes_tests { use super::sandbox_notes; From af818ad7779d6f73fd4a246ec2811a88a95218d8 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sat, 5 Dec 2026 14:57:23 +0530 Subject: [PATCH 3/3] chore(drivers): move the Docker, Podman and VM ingress admission changes out of core The Docker, Podman and VM drivers are frozen in this repository while they move to ai-openshell/desktop, so their ingress admission support is prepared there. Here they keep the behavior they have on main: they do not advertise openshell.compute.ingress-admission, and the gateway forwards for them as it did before. This branch adds a field to ValidateSandboxCreateResponse, so the drivers build it from Default. That is the only change left in the frozen paths. The sandbox guide says what `openshell sandbox get` shows for a driver that does not report its ports, and a CLI test pins that text. Signed-off-by: Shiju --- crates/openshell-cli/src/run.rs | 5 +++++ crates/openshell-driver-docker/src/lib.rs | 22 ++++++++------------ crates/openshell-driver-podman/src/driver.rs | 2 +- crates/openshell-driver-podman/src/grpc.rs | 6 +----- crates/openshell-driver-vm/src/driver.rs | 8 ++----- docs/how-it-works/sandboxes/overview.mdx | 4 +++- 6 files changed, 21 insertions(+), 26 deletions(-) diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index 2228a8073c..707bb73565 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -10177,6 +10177,11 @@ mod tests { .clear(); assert_eq!(super::configuration_failure_message(&sandbox), None); assert!(super::sandbox_to_json(&sandbox)["ingress_admission"].is_null()); + // A driver that reports no decision keeps the forwarding it had. + assert_eq!( + super::service_port_summary(None), + "unknown (legacy forwarding)" + ); let mut admission = openshell_core::proto::SandboxIngressAdmission::default(); assert_eq!(super::service_port_summary(Some(&admission)), "unavailable"); admission.scope = openshell_core::proto::IngressScope::SharedHostLoopback as i32; diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 2603b3a622..667bc7006c 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -1098,13 +1098,6 @@ impl DockerComputeDriver { } fn capabilities(&self) -> GetCapabilitiesResponse { - use openshell_core::extension_protocol::{ - COMPUTE_INGRESS_ADMISSION, COMPUTE_UPDATE_SANDBOX_CONFIGURATION, - }; - let mut capabilities = vec![COMPUTE_INGRESS_ADMISSION.to_string()]; - if self.config.workspace_storage == workspace::Storage::Persistent { - capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string()); - } GetCapabilitiesResponse { resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { allow_driver_config: self.config.allow_driver_config, @@ -1135,7 +1128,14 @@ impl DockerComputeDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/docker", openshell_core::VERSION, - capabilities, + if self.config.workspace_storage == workspace::Storage::Persistent { + vec![ + openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION + .to_string(), + ] + } else { + Vec::new() + }, )), } } @@ -3514,11 +3514,7 @@ impl ComputeDriver for DockerComputeDriver { CdiGpuDefaultSelector::peek_device_ids, ) .await?; - Ok(Response::new(ValidateSandboxCreateResponse { - ingress_admission: Some( - openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, - ), - })) + Ok(Response::new(ValidateSandboxCreateResponse::default())) } async fn get_sandbox( diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index c4013ac644..a263bcf7d2 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -751,7 +751,7 @@ impl PodmanComputeDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/podman", openshell_core::VERSION, - [openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string()], + [], )), }) } diff --git a/crates/openshell-driver-podman/src/grpc.rs b/crates/openshell-driver-podman/src/grpc.rs index d13c01ea60..f9ce9f3e8d 100644 --- a/crates/openshell-driver-podman/src/grpc.rs +++ b/crates/openshell-driver-podman/src/grpc.rs @@ -100,11 +100,7 @@ impl ComputeDriver for ComputeDriverService { .validate_sandbox_create(&sandbox) .await .map_err(Status::from)?; - Ok(Response::new(ValidateSandboxCreateResponse { - ingress_admission: Some( - openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, - ), - })) + Ok(Response::new(ValidateSandboxCreateResponse::default())) }) .await } diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 55e2bda6b2..bd4986ff21 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -1552,7 +1552,7 @@ impl VmDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/vm", openshell_core::VERSION, - [openshell_core::extension_protocol::COMPUTE_INGRESS_ADMISSION.to_string()], + [], ); extension .required_capabilities @@ -5351,11 +5351,7 @@ impl ComputeDriver for VmDriver { .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.validate_sandbox(&sandbox)?; - Ok(Response::new(ValidateSandboxCreateResponse { - ingress_admission: Some( - openshell_core::proto::SandboxIngressAdmission::ALL_ISOLATED_LOOPBACK_PORTS, - ), - })) + Ok(Response::new(ValidateSandboxCreateResponse::default())) } async fn create_sandbox( diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index f105caa7cd..628f5ddacf 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -847,7 +847,9 @@ Press `c` in the Sandboxes panel to create a sandbox. In the optional Command fi `openshell sandbox create --forward ` checks the target before creating the sandbox. `openshell sandbox get` shows which ports the driver allows and -whether they reach the sandbox or the compute host's loopback. +whether they reach the sandbox or the compute host's loopback. For a driver +that does not report its ports, it shows `unknown (legacy forwarding)` and +forwarding works as before. Upgrade gateway replicas together. If an existing sandbox reports `Service ports: unavailable` after the upgrade, recreate it.