diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 8157c9b219..6468fdb17b 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -50,6 +50,9 @@ nix = { workspace = true } rustix = { workspace = true } libc = "0.2" +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { workspace = true, features = ["event"] } + [features] default = ["telemetry"] ## Compile in anonymous telemetry emission support. On by default; disable with diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..66192142cb 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -47,6 +47,9 @@ pub const COMPUTE_SUSPEND_RESUME: &str = "openshell.compute.suspend-resume"; pub const COMPUTE_UPDATE_SANDBOX_CONFIGURATION: &str = "openshell.compute.update-sandbox-configuration"; +/// Driver resolves a running workload from the gateway's sandbox and generation. +pub const COMPUTE_WORKLOAD_REFERENCE: &str = "openshell.compute.workload-reference"; + /// Capability for supervisor middleware that implements HTTP hooks. /// /// A service selects HTTP hooks for all of its HTTP bindings by diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 4bc48e01d1..60e0254312 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -75,6 +75,7 @@ pub mod token_endpoint; pub mod token_grant_failure; pub mod transport_errors; pub mod upload; +pub mod workload_reference; pub use config::{ AppArmorProfile, Config, ExtensionBindingPolicy, GatewayAuditConfig, GatewayAuthConfig, diff --git a/crates/openshell-core/src/workload_reference.rs b/crates/openshell-core/src/workload_reference.rs new file mode 100644 index 0000000000..0e390ff4b8 --- /dev/null +++ b/crates/openshell-core/src/workload_reference.rs @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Process evidence for compute drivers and gateways using a node-local identity broker. + +use std::io; + +use crate::proto::compute::v1::LocalWorkloadProcess; + +/// A specific process lifetime held across a broker request. +/// +/// The caller supplies the immutable workload object obtained through the engine. +/// The handle checks OS evidence independently of the engine's generation binding. +#[derive(Debug)] +pub struct LocalProcessHandle { + reference: LocalWorkloadProcess, + #[cfg(target_os = "linux")] + pidfd: std::os::fd::OwnedFd, +} + +impl LocalProcessHandle { + /// Capture evidence for a live process in the caller's Linux PID namespace. + /// + /// Returns an error if procfs uses a different PID view or the process has exited. + #[cfg(target_os = "linux")] + pub fn capture(runtime_identity: String, pid: u32) -> io::Result { + use std::fs; + use std::os::unix::fs::MetadataExt as _; + + use rustix::process::{Pid, PidfdFlags, pidfd_open}; + + let os_pid = i32::try_from(pid).ok().and_then(Pid::from_raw); + let os_pid = os_pid + .filter(|_| !runtime_identity.is_empty()) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidInput, + "missing workload identity or invalid PID", + ) + })?; + + // A host procfs mount inside another PID namespace could describe a + // different process from the one that pidfd_open sees at the same PID. + let own_status = fs::read("/proc/self/status")?; + let same_view = own_status + .split(|&c| c == b'\n') + .find_map(|line| line.strip_prefix(b"NSpid:")) + .and_then(|pids| std::str::from_utf8(pids).ok()) + .and_then(|pids| pids.trim().parse::().ok()) + == Some(std::process::id()); + if !same_view { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "procfs PID namespace mismatch", + )); + } + + let pidfd = pidfd_open(os_pid, PidfdFlags::empty())?; + let stat = fs::read(format!("/proc/{pid}/stat"))?; + // The parenthesized command may contain arbitrary bytes, spaces and ')'. + // State is field 3, the first token after the final closing parenthesis. + let start_time_ticks = stat + .iter() + .rposition(|&b| b == b')') + .and_then(|end| std::str::from_utf8(&stat[end + 1..]).ok()) + .and_then(|fields| fields.split_ascii_whitespace().nth(19)) + .and_then(|ticks| ticks.parse().ok()) + .ok_or_else(|| { + io::Error::new(io::ErrorKind::InvalidData, "invalid process start time") + })?; + let reference = LocalWorkloadProcess { + runtime_identity, + pid, + start_time_ticks, + boot_id: fs::read_to_string("/proc/sys/kernel/random/boot_id")? + .trim() + .to_owned(), + pid_namespace_inode: fs::metadata("/proc/self/ns/pid")?.ino(), + }; + let handle = Self { reference, pidfd }; + // If the original process vanished during the procfs reads, discard + // the snapshot even when a replacement is already using its PID. + handle.ensure_live()?; + Ok(handle) + } + + /// Return an unsupported error on systems without Linux process evidence. + #[cfg(not(target_os = "linux"))] + pub fn capture(_runtime_identity: String, _pid: u32) -> io::Result { + Err(io::ErrorKind::Unsupported.into()) + } + + /// Return the wire evidence associated with the pinned process lifetime. + #[must_use] + pub fn reference(&self) -> &LocalWorkloadProcess { + &self.reference + } + + /// Fail if the captured process has exited, including before it is reaped. + pub fn ensure_live(&self) -> io::Result<()> { + #[cfg(target_os = "linux")] + { + use rustix::event::{PollFd, PollFlags, Timespec, poll}; + + let mut fds = [PollFd::new(&self.pidfd, PollFlags::IN)]; + if poll(&mut fds, Some(&Timespec::default()))? == 0 { + return Ok(()); + } + Err(io::Error::new( + io::ErrorKind::NotFound, + "workload process exited", + )) + } + #[cfg(not(target_os = "linux"))] + Err(io::ErrorKind::Unsupported.into()) + } +} + +#[cfg(all(test, target_os = "linux"))] +mod tests { + use super::*; + + #[test] + fn captured_process_cannot_be_used_after_exit() { + use std::process::{Command, Stdio}; + + // Keep the child alive until its stdin closes so the test has no timing dependency. + let mut child = Command::new("cat").stdin(Stdio::piped()).spawn().unwrap(); + let handle = LocalProcessHandle::capture("engine-object".to_owned(), child.id()).unwrap(); + let again = LocalProcessHandle::capture("engine-object".to_owned(), child.id()).unwrap(); + assert_eq!(handle.reference(), again.reference()); + assert_eq!(handle.reference().pid, child.id()); + assert!(!handle.reference().boot_id.is_empty()); + assert_ne!(handle.reference().pid_namespace_inode, 0); + assert!(child.wait().unwrap().success()); + assert_eq!( + handle.ensure_live().unwrap_err().kind(), + io::ErrorKind::NotFound + ); + } +} diff --git a/crates/openshell-core/tests/compute_driver_compat.rs b/crates/openshell-core/tests/compute_driver_compat.rs index 22e5089fbf..1f9f2ec3ed 100644 --- a/crates/openshell-core/tests/compute_driver_compat.rs +++ b/crates/openshell-core/tests/compute_driver_compat.rs @@ -11,17 +11,18 @@ use openshell_core::proto::compute::v1::{ CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, EnsureWorkspaceRequest, EnsureWorkspaceResponse, GetCapabilitiesRequest, GetCapabilitiesResponse, GetSandboxRequest, GetSandboxResponse, - ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, - StopSandboxRequest, StopSandboxResponse, SuspendSandboxRequest, SuspendSandboxResponse, - UpdateSandboxConfigurationRequest, UpdateSandboxConfigurationResponse, - ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, - WatchSandboxesRequest, + ListSandboxesRequest, ListSandboxesResponse, ResolveWorkloadReferenceRequest, + StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, + SuspendSandboxRequest, SuspendSandboxResponse, UpdateSandboxConfigurationRequest, + UpdateSandboxConfigurationResponse, ValidateSandboxCreateRequest, + ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, compute_driver_client::ComputeDriverClient, compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient, compute_driver_configuration_updates_server::{ ComputeDriverConfigurationUpdates, ComputeDriverConfigurationUpdatesServer, }, compute_driver_server::{ComputeDriver, ComputeDriverServer}, + compute_driver_workload_references_client::ComputeDriverWorkloadReferencesClient, }; use prost::Message; use std::pin::Pin; @@ -197,6 +198,15 @@ async fn roundtrip(serve_image_updates: bool) { tonic::Code::Unimplemented, ); let mut baseline = ComputeDriverClient::new(channel.clone()); + let mut workload_refs = ComputeDriverWorkloadReferencesClient::new(channel.clone()); + assert_eq!( + workload_refs + .resolve_workload_reference(ResolveWorkloadReferenceRequest::default()) + .await + .unwrap_err() + .code(), + tonic::Code::Unimplemented, + ); assert_eq!( baseline .get_capabilities(GetCapabilitiesRequest::default()) diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 79a63a3f8d..b3643e40f7 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -641,6 +641,7 @@ mod tests { let mut sandbox_protocol_methods = BTreeSet::new(); let mut supervisor_host_methods = BTreeSet::new(); let mut driver_launch_methods = BTreeSet::new(); + let mut workload_reference_methods = BTreeSet::new(); for file in &public.file { let package = file.package.as_deref().unwrap_or_default(); for service in &file.service { @@ -672,6 +673,18 @@ mod tests { method.name.as_deref().expect("supervisor host method name") })); } + // The trusted compute channel resolves a workload process for the gateway. + // Its evidence stays outside the public SDK and durable message inventory. + if (package, service_name) + == ("openshell.compute.v1", "ComputeDriverWorkloadReferences") + { + workload_reference_methods.extend(service.method.iter().map(|method| { + method + .name + .as_deref() + .expect("workload reference method name") + })); + } // Private gateway-to-driver launch protocol: served by launched // compute drivers, never part of the public SDK surface. if package == "openshell.driver.launch.v1" { @@ -729,6 +742,10 @@ mod tests { driver_launch_methods, BTreeSet::from(["Configure", "GetLaunchInfo", "Shutdown"]) ); + assert_eq!( + workload_reference_methods, + BTreeSet::from(["ResolveWorkloadReference"]) + ); for signature in PROVIDER_READINESS_RPC_SIGNATURES { assert!( methods.iter().any(|method| method == signature), @@ -754,7 +771,8 @@ mod tests { + PEER_CONFIG_RPC_SIGNATURES.len() + isolation_methods.len() + sandbox_protocol_methods.len() - + supervisor_host_methods.len(), + + supervisor_host_methods.len() + + workload_reference_methods.len(), "classify every compiled RPC" ); assert_eq!( diff --git a/proto/README.md b/proto/README.md index 23306835bd..c6b02863bb 100644 --- a/proto/README.md +++ b/proto/README.md @@ -101,6 +101,12 @@ safe endpoint is currently available. Neither result authorizes publication. The gateway owns installation validation and the public discovery API. The baseline `ComputeDriver` service and generated server trait stay unchanged. +## Compute-driver workload references + +A configured compute driver can advertise `openshell.compute.workload-reference` and serve `ComputeDriverWorkloadReferences.ResolveWorkloadReference` on its private channel. The gateway supplies its own sandbox ID and runtime generation. The driver resolves the live workload through the engine, checks ownership and generation, and returns the immutable engine object ID and a Linux process reference. A missing workload or a stale binding must withhold evidence. Drivers without this service return `UNIMPLEMENTED`. + +The reference is valid only for the named Linux boot and PID numbering namespace. The gateway must establish that it and the broker use this same local process view, check the process lifetime around issuance, and recheck the driver binding before returning a grant. A PID from another engine host is insufficient for remote attestation. Advertising the service does not enable provider grants or select a supervisor topology. + ## Supervisor host protocol [`supervisor_host.proto`](supervisor_host.proto) is the private stream between diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index fa51425729..b0c9faa325 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -93,6 +93,47 @@ service ComputeDriverConfigurationUpdates { returns (UpdateSandboxConfigurationResponse); } +// Optional private service, advertised with openshell.compute.workload-reference. +// Only the gateway may ask its configured driver to identify a live workload. +service ComputeDriverWorkloadReferences { + // Resolve from trusted engine state. Absent or stale generations fail closed. + rpc ResolveWorkloadReference(ResolveWorkloadReferenceRequest) + returns (ResolveWorkloadReferenceResponse); +} + +message ResolveWorkloadReferenceRequest { + // Gateway-assigned immutable sandbox ID. + string sandbox_id = 1; + // Engine lookup hint. A name alone never establishes ownership. + string name = 2; + // Gateway generation that the driver must independently match against the runtime. + string generation_id = 3; +} + +message ResolveWorkloadReferenceResponse { + // Binding observed by the driver, checked against the request by the gateway. + string sandbox_id = 1; + string generation_id = 2; + // Present only for a live workload identified on this driver host. + LocalWorkloadProcess process = 3; +} + +// Local Linux process evidence for the workload, scoped to the engine host. +// Resolve again across attestation and on cache reuse. Never forward a PID to +// a broker on another host or in a different PID numbering namespace. +message LocalWorkloadProcess { + // Immutable engine object that owns this process, such as a full container ID. + string runtime_identity = 1; + // Workload process ID as seen by the driver and its node-local broker. + uint32 pid = 2; + // Field 22 of /proc//stat in kernel clock ticks since boot. + uint64 start_time_ticks = 3; + // Linux kernel boot ID for the host on which the evidence was collected. + string boot_id = 4; + // Inode of the PID namespace in which the PID above was resolved. + uint64 pid_namespace_inode = 5; +} + message UpdateSandboxConfigurationRequest { // Shared lifecycle, image, revision and runtime identity preconditions. SandboxUpdatePreconditions preconditions = 1;