diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index b60b472b03..e76b780bf0 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -100,6 +100,58 @@ binary extraction path. `supervisor_image` supplies the dynamically linked glibc `/openshell-supervisor` binary outside the workload. Image and request environment belong to agent children, never the supervisor process. +## Verified provider workload identity + +The driver advertises `openshell.compute.provider-workload-identity` when all +of these hold at startup: + +- The mode is selected. A launched driver needs + `verified_provider_workload_identity = true` in `Configure`. A standalone + driver receives no `Configure`, so its socket setting selects the mode. +- `provider_spiffe_workload_api_socket` is an absolute Unix socket path. +- Supervisors reach the gateway over HTTPS or numeric loopback HTTP. +- The supervisor image answers the probe. The driver runs + `/openshell-supervisor provider-workload-identity-probe ` in a + one-shot container with the socket's directory mounted as a supervisor + mounts it. Exit 70 (socket visible) and 71 (not visible) both show that the + image supports the mode. Any other exit withholds the capability. + +Whether a supervisor sees the socket depends on its workload's UID, GID, and +groups. Create and supervisor replacement therefore run the same probe as that +user and require exit 70. + +When a launch bundle carries provider identities, the driver checks that they +belong to the sandbox and generation, then labels the supervisor container +`openshell.ai/provider-launch-spiffe-id=`. The workload +container carries the label with an empty value, so an image label cannot +claim a launch. A template cannot set the label on either container. + +The launch SPIFFE ID ends in the runtime generation, so it changes when the +gateway starts a new generation and stays the same across a gateway restart +and a retry. Podman fixes labels at creation, so a start whose bundle names a +launch acts on the supervisor it finds: + +| Supervisor | Start | +|---|---| +| Running, labeled for this launch | Restarts the pair in place, as a start without provider identity does. | +| Stopped, labeled for this launch | The same. If that fails, creates a new supervisor. | +| Missing, never started, or labeled for another launch or for none | Creates a new supervisor. | +| Stopped pair whose supervisor holds stale destination trust | Creates a new supervisor. | + +To create one, the driver first does everything that can fail without +changing the pair. It resolves the kept workload's pinned image and identity, +pulls and pins the supervisor image, and runs the probe as the workload's +user. It then stops and removes the supervisor under the canonical name, so a +sandbox never has two. With no supervisor left to mount them, it rewrites the +proxy-credential and gateway-CA secrets from the operator's current files, +then creates and starts the new supervisor. The workload container keeps its +volumes, devices, and runtime binary: the driver pulls no runtime image, +extracts no binary, and selects no GPU. + +A failure after the removal leaves no supervisor, or one that the next start +removes, so a retry with the same bundle finishes the job. The driver keeps no +launch state outside Podman. + ## OCI working directory OpenShell reads `WORKDIR` from the workload image. If it is unset, `/`, or @@ -129,7 +181,10 @@ driver-owned volumes and secrets. Stop retains both containers, workspace, channel, and secrets. Start restores the consumed sandbox bootstrap from a copy in the supervisor's private filesystem, verifies the fence, and starts the same pair. A failed supervisor -start stops the workload. Delete removes the companion first, then the workload, +start stops the workload. A start for a new provider launch replaces the +supervisor instead; see +[Verified provider workload identity](#verified-provider-workload-identity). +Delete removes the companion first, then the workload, channel, workspace, and driver-owned secrets. User-owned volumes are retained. Delete keeps a channel, control, or workspace volume whose `openshell.ai/sandbox-id` label is missing or names another sandbox, and logs a @@ -176,4 +231,4 @@ The gateway passes the `[openshell.drivers.podman]` table on stdin and gateway m `serve` resolves the Podman socket from `OPENSHELL_PODMAN_SOCKET`, `socket_path`, or discovery, and pings it before it binds. The ping gets 20 seconds, so the gateway, which waits 30 seconds for a driver to start, receives the report instead of killing the driver. It exits 69 when Podman is not reachable and 78 when the table is invalid. Until `Configure` succeeds, `ComputeDriver` calls return `UNAVAILABLE` and the driver creates no networks, volumes, or secrets. `preflight` validates the table without contacting Podman. -The gateway port and name, trusted runtime images, and OTLP settings come from `Configure`. Trusted runtime images from the gateway's environment take precedence over the table, as they did when the driver ran in process. The gateway supplies `gateway_port` and the CA, so the table rejects `gateway_port`, `guest_tls_ca` and the admission keys (`allow_driver_config`, `resource_admission`), which the gateway delivers in `Configure`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. +The gateway port and name, trusted runtime images, OTLP settings, and the selection of verified provider workload identity come from `Configure`. Trusted runtime images from the gateway's environment take precedence over the table, as they did when the driver ran in process. The gateway supplies `gateway_port` and the CA, so the table rejects `gateway_port`, `guest_tls_ca` and the admission keys (`allow_driver_config`, `resource_admission`), which the gateway delivers in `Configure`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. diff --git a/crates/openshell-driver-podman/src/client.rs b/crates/openshell-driver-podman/src/client.rs index 793b92271c..39b7b7bccc 100644 --- a/crates/openshell-driver-podman/src/client.rs +++ b/crates/openshell-driver-podman/src/client.rs @@ -612,6 +612,17 @@ impl PodmanClient { .await } + /// Wait for a started container to exit and return its exit status. + pub(crate) async fn wait_for_container_exit(&self, name: &str) -> Result { + validate_name(name)?; + self.request_json( + hyper::Method::POST, + &format!("/libpod/containers/{name}/wait?condition=exited"), + None, + ) + .await + } + /// Stop a container with a grace period in seconds. pub async fn stop_container( &self, diff --git a/crates/openshell-driver-podman/src/container.rs b/crates/openshell-driver-podman/src/container.rs index 38135d2eb4..304ee75d47 100644 --- a/crates/openshell-driver-podman/src/container.rs +++ b/crates/openshell-driver-podman/src/container.rs @@ -41,7 +41,8 @@ fn is_selinux_enabled() -> bool { } pub use openshell_core::driver_utils::{ - LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, + LABEL_PROVIDER_LAUNCH_SPIFFE_ID, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, LABEL_SANDBOX_NAMESPACE, + LABEL_SANDBOX_WORKSPACE, }; /// Label applied to all managed containers. @@ -1513,16 +1514,8 @@ fn build_base_spec( options: opts, }); } - if let Some(path) = provider_spiffe_workload_api_socket_mount_source(config) { - // No SELinux relabel - the SPIRE agent socket is shared host - // infrastructure and must keep its existing SELinux context. - let ro = vec!["ro".into(), "rbind".into()]; - m.push(Mount { - kind: "bind".into(), - source: path.display().to_string(), - destination: PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.into(), - options: ro, - }); + if let Some(mount) = provider_spiffe_workload_api_socket_mount(config) { + m.push(mount); } m.extend(user_mounts.mounts); m @@ -1592,6 +1585,14 @@ pub struct IsolationSpecs { } impl IsolationSpecs { + /// Mark the supervisor with the launch SPIFFE ID from its launch bundle. + pub(crate) fn record_provider_launch(&mut self, launch_spiffe_id: &str) { + self.supervisor.labels.insert( + LABEL_PROVIDER_LAUNCH_SPIFFE_ID.into(), + launch_spiffe_id.into(), + ); + } + pub(crate) fn record_resource_identities( &mut self, identities: &BTreeMap, @@ -1627,6 +1628,13 @@ pub fn build_isolation_specs( workload .labels .insert(crate::isolation::LABEL_ROLE.into(), "sandbox".into()); + // Only a supervisor carries a launch SPIFFE ID, and only the one in its + // launch bundle. The empty value keeps an image or template label from + // passing the workload off as one; a template cannot set the supervisor's. + workload + .labels + .insert(LABEL_PROVIDER_LAUNCH_SPIFFE_ID.into(), String::new()); + supervisor.labels.remove(LABEL_PROVIDER_LAUNCH_SPIFFE_ID); workload.env = BTreeMap::new(); workload.unsetenv = input .image @@ -1858,6 +1866,61 @@ fn provider_spiffe_workload_api_socket_mount_source(config: &PodmanComputeConfig host_path.parent() } +fn provider_spiffe_workload_api_socket_mount(config: &PodmanComputeConfig) -> Option { + let source = provider_spiffe_workload_api_socket_mount_source(config)?; + // No SELinux relabel - the SPIRE agent socket is shared host + // infrastructure and must keep its existing SELinux context. + Some(Mount { + kind: "bind".into(), + source: source.display().to_string(), + destination: PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.into(), + options: vec!["ro".into(), "rbind".into()], + }) +} + +/// A one-shot container that runs the supervisor image's probe subcommand +/// against the Workload API socket, mounted as a supervisor's is. It runs as +/// `identity` when given, as that workload's supervisor would, and otherwise +/// as the engine's root user. +pub fn provider_workload_identity_probe_spec( + config: &PodmanComputeConfig, + supervisor_image: &str, + identity: Option<&openshell_isolation_interface::contract::ResolvedWorkloadIdentity>, +) -> Result { + let (Some(socket), Some(mount)) = ( + provider_spiffe_workload_api_socket_env_value(config), + provider_spiffe_workload_api_socket_mount(config), + ) else { + return Err(ComputeDriverError::Precondition( + "verified provider workload identity needs a Workload API Unix socket path".into(), + )); + }; + let mut spec = serde_json::json!({ + "name": format!("openshell-provider-probe-{}", uuid::Uuid::new_v4()), + "image": supervisor_image, + "entrypoint": ["/openshell-supervisor"], + "command": [openshell_core::driver_utils::PROVIDER_WORKLOAD_IDENTITY_PROBE, socket], + "mounts": [mount], + "user": "0:0", + "userns": {"nsmode": "host"}, + "netns": {"nsmode": "none"}, + "cap_drop": ["ALL"], + "no_new_privileges": true, + "read_only_filesystem": true, + "healthconfig": {"test": ["NONE"]}, + "work_dir": "/", + }); + if let Some(identity) = identity { + spec["user"] = format!("{}:{}", identity.uid, identity.gid).into(); + spec["groups"] = identity + .supplementary_gids + .iter() + .map(ToString::to_string) + .collect(); + } + Ok(spec) +} + fn hostadd_entries(config: &PodmanComputeConfig) -> Vec { let host_gateway_ip = config.host_gateway_ip.trim(); if host_gateway_ip.is_empty() { @@ -4212,6 +4275,89 @@ mod tests { })); } + #[test] + fn only_the_supervisor_carries_its_bundles_launch_spiffe_id() { + use openshell_core::proto::compute::v1::DriverSandboxSpec; + let mut sandbox = test_sandbox("launch-id", "launch-name"); + sandbox.spec = Some(DriverSandboxSpec { + template: Some(DriverSandboxTemplate { + labels: std::iter::once(( + LABEL_PROVIDER_LAUNCH_SPIFFE_ID.to_string(), + "spiffe://example.test/spoofed".to_string(), + )) + .collect(), + ..Default::default() + }), + ..Default::default() + }); + let mut config = test_config(); + config.provider_spiffe_workload_api_socket = Some("/host/spire-agent.sock".into()); + let identity = openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( + 1000, + 1001, + vec![2000], + "image".into(), + "sha256:image".into(), + ) + .unwrap(); + let mut specs = build_isolation_specs(IsolationSpecInput { + sandbox: &sandbox, + config: &config, + token_secret: None, + resolver_secret: "resolver", + gpu_devices: None, + image: &ResolvedPodmanImage::new("sha256:image"), + supervisor_bin: None, + tls_secrets: None, + network_trust: None, + identity: &identity, + }) + .unwrap(); + let launch = + |spec: &ContainerSpec| spec.labels.get(LABEL_PROVIDER_LAUNCH_SPIFFE_ID).cloned(); + assert_eq!(launch(&specs.workload).as_deref(), Some("")); + assert_eq!(launch(&specs.supervisor), None); + specs.record_provider_launch("spiffe://example.test/launch"); + assert_eq!(launch(&specs.workload).as_deref(), Some("")); + assert_eq!( + launch(&specs.supervisor).as_deref(), + Some("spiffe://example.test/launch") + ); + + // The probe sees the socket through the supervisor's own mount, as + // the supervisor's user. + let supervisor = serde_json::to_value(&specs.supervisor).unwrap(); + let probe = + provider_workload_identity_probe_spec(&config, "sha256:supervisor", Some(&identity)) + .unwrap(); + let socket_mount = |spec: &Value| { + spec["mounts"] + .as_array() + .unwrap() + .iter() + .find(|mount| { + mount["destination"].as_str() + == Some(PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR) + }) + .cloned() + }; + assert!(socket_mount(&probe).is_some()); + assert_eq!(socket_mount(&probe), socket_mount(&supervisor)); + for field in ["user", "groups", "userns"] { + assert_eq!(probe[field], supervisor[field], "{field}"); + } + assert_eq!( + probe["command"], + serde_json::json!([ + openshell_core::driver_utils::PROVIDER_WORKLOAD_IDENTITY_PROBE, + "/spiffe-workload-api/spire-agent.sock" + ]) + ); + + config.provider_spiffe_workload_api_socket = Some("tcp:127.0.0.1:8081".into()); + assert!(provider_workload_identity_probe_spec(&config, "sha256:supervisor", None).is_err()); + } + #[test] fn container_spec_omits_tls_without_config() { let sandbox = test_sandbox("notls-id", "notls-name"); diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index d4000c15c2..badc14dbc8 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -5,16 +5,22 @@ use crate::client::{ContainerListEntry, PodmanApiError, PodmanClient, VolumeInspect}; use crate::config::{PodmanComputeConfig, podman_image_pull_policy}; -use crate::container::{self, LABEL_MANAGED_FILTER, LABEL_SANDBOX_ID, PodmanSandboxDriverConfig}; +use crate::container::{ + self, LABEL_MANAGED_FILTER, LABEL_PROVIDER_LAUNCH_SPIFFE_ID, LABEL_SANDBOX_ID, + PodmanSandboxDriverConfig, +}; use crate::watcher::{ self, LifecycleEventFences, WatchStream, driver_sandbox_from_inspect, driver_sandbox_from_list_entry, }; use openshell_core::config::CDI_GPU_DEVICE_ALL; use openshell_core::driver_utils::{ + PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT, PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE, SANDBOX_RUNTIME_IMAGE_BINARY_PATH, extract_first_tar_entry, supervisor_image_should_refresh, - temp_extract_container_name, validate_linux_elf_binary, write_cache_binary_atomic, + temp_extract_container_name, validate_linux_elf_binary, validate_provider_launch_identity, + write_cache_binary_atomic, }; +use openshell_core::extension_protocol::{COMPUTE_PROVIDER_WORKLOAD_IDENTITY, capabilities_if}; use openshell_core::gpu::{ CdiGpuDefaultSelector, CdiGpuInventory, CdiGpuSelectionError, driver_gpu_requirements, effective_driver_gpu_count, validate_cdi_gpu_device_request, @@ -151,6 +157,9 @@ pub struct PodmanComputeDriver { gpu_selector: Arc, gpu_inventory_refresh: Arc (CdiGpuInventory, bool) + Send + Sync>, lifecycle_event_fences: LifecycleEventFences, + /// Whether verified provider workload identity is selected and this + /// driver's Workload API socket and supervisor image qualified for it. + provider_workload_identity: bool, /// Gateway-normalized destination trust held outside untrusted sandbox /// specs. Gateway-managed drivers receive the staged bundle from the /// gateway; standalone drivers self-source one from the @@ -183,6 +192,21 @@ struct ValidatedPodmanSandbox<'a> { gpu_requirements: Option<&'a GpuResourceRequirements>, } +/// How a sandbox's supervisor stands to the launch that a start names. +#[derive(Debug, PartialEq, Eq)] +enum LaunchSupervisor { + /// Running under this launch's label. The start proceeds as it does + /// without provider identity. + Running, + /// Stopped under this launch's label. The start restarts it, and creates + /// it again if that fails. + Stopped, + /// Missing, never started, labeled for another launch or for none, or + /// holding destination trust that a stopped pair must refresh. The start + /// creates it. + Create, +} + /// Construct and validate a container name from a sandbox. /// /// Combines the prefix with workspace, name, and ID, then validates the @@ -560,9 +584,15 @@ fn stage_operator_network_trust_artifact( impl PodmanComputeDriver { /// Create a new driver, verifying the Podman socket is reachable. + /// + /// `provider_workload_identity_selected` is the gateway's `Configure` + /// flag for verified provider workload identity. A standalone driver + /// receives no `Configure` and passes `true`, so its configured Workload + /// API socket selects the mode. pub async fn new( mut config: PodmanComputeConfig, network_trust: Option, + provider_workload_identity_selected: bool, ) -> Result { const MAX_PING_RETRIES: u32 = 5; const PING_RETRY_DELAY: Duration = Duration::from_secs(2); @@ -697,7 +727,7 @@ impl PodmanComputeDriver { ); } - let driver = Self { + let mut driver = Self { client, config, gpu_selector: Arc::new(CdiGpuDefaultSelector::new( @@ -706,9 +736,25 @@ impl PodmanComputeDriver { )), gpu_inventory_refresh: Arc::new(local_podman_gpu_selector_state), lifecycle_event_fences: LifecycleEventFences::default(), + provider_workload_identity: false, network_trust, network_trust_staging, }; + if provider_workload_identity_selected + && driver + .config + .provider_spiffe_workload_api_socket + .as_deref() + .is_some_and(Path::is_absolute) + { + match driver.qualify_provider_workload_identity().await { + Ok(()) => driver.provider_workload_identity = true, + Err(error) => warn!( + %error, + "Podman driver cannot supply verified provider workload identity" + ), + } + } let reconciler = driver.clone(); tokio::spawn(async move { loop { @@ -751,7 +797,10 @@ impl PodmanComputeDriver { openshell_core::extension_protocol::ExtensionFamily::Compute, "openshell/podman", openshell_core::VERSION, - [], + capabilities_if( + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, + self.provider_workload_identity, + ), )), }) } @@ -1062,6 +1111,94 @@ impl PodmanComputeDriver { ) } + /// Check what verified provider workload identity needs from this driver: + /// a gateway endpoint a supervisor may send workload assertions to, and a + /// supervisor image that answers the probe with the Workload API socket + /// mounted. Whether a supervisor sees the socket depends on its workload's + /// user and groups, so each launch runs the probe again as that user. + async fn qualify_provider_workload_identity(&self) -> Result<(), ComputeDriverError> { + use openshell_core::grpc_client::{ + token_grant_gateway_endpoint, validate_attested_token_grant_transport, + }; + token_grant_gateway_endpoint(&self.config.grpc_endpoint) + .and_then(|endpoint| validate_attested_token_grant_transport(&endpoint)) + .map_err(|_| { + ComputeDriverError::Precondition( + "verified provider workload identity needs a Podman supervisor gateway \ + endpoint using HTTPS or a numeric loopback HTTP address" + .into(), + ) + })?; + let image = &self.config.supervisor_image; + self.client + .pull_image(image, runtime_image_pull_policy(image)) + .await?; + self.probe_provider_supervisor(image, None).await + } + + /// Run the supervisor image's probe subcommand in a one-shot container. + /// An image that supports verified provider workload identity reports + /// whether it sees the Workload API socket; any other exit status means + /// the image does not support the mode. Run as a workload's `identity`, + /// the probe must also see the socket, as that workload's supervisor will. + async fn probe_provider_supervisor( + &self, + supervisor_image: &str, + identity: Option<&openshell_isolation_interface::contract::ResolvedWorkloadIdentity>, + ) -> Result<(), ComputeDriverError> { + let spec = container::provider_workload_identity_probe_spec( + &self.config, + supervisor_image, + identity, + )?; + let probe = self.client.create_typed_container(&spec).await?; + let status = async { + self.client.start_container(&probe).await?; + self.client.wait_for_container_exit(&probe).await + } + .await; + if let Err(error) = self.client.remove_container(&probe, 0).await { + warn!(container = %probe, %error, "Failed to remove provider identity probe container"); + } + match (status?, identity) { + (PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT, _) + | (PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE, None) => Ok(()), + (PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE, Some(_)) => { + Err(ComputeDriverError::Precondition( + "Podman supervisor cannot see the configured Workload API Unix socket".into(), + )) + } + (status, _) => Err(ComputeDriverError::Precondition(format!( + "Podman supervisor image {supervisor_image} does not support verified provider \ + workload identity (probe exit {status}). Select a matching supervisor image." + ))), + } + } + + /// The launch SPIFFE ID a supervisor started from this bundle is labeled + /// with, or `None` when the bundle carries no provider identity. The + /// identities must belong to this sandbox and generation. + fn provider_launch_spiffe_id<'a>( + &self, + sandbox_id: &str, + generation_id: &str, + authentication: &'a openshell_core::jwt::SandboxLaunchAuthentication, + ) -> Result, ComputeDriverError> { + let supervisor = &authentication.supervisor; + if supervisor.provider_spiffe_id.is_none() && supervisor.provider_launch_spiffe_id.is_none() + { + return Ok(None); + } + if !self.provider_workload_identity { + return Err(ComputeDriverError::Precondition( + "Podman driver cannot supply verified provider workload identity".into(), + )); + } + validate_provider_launch_identity(sandbox_id, generation_id, authentication) + .map_err(|status| ComputeDriverError::InvalidArgument(status.message().into()))?; + Ok(supervisor.provider_launch_spiffe_id.as_deref()) + } + /// Create a sandbox container. #[tracing::instrument( name = "podman.provision", @@ -1538,6 +1675,23 @@ impl PodmanComputeDriver { .and_then(|spec| { decode_launch_authentication(&spec.launch_authentication) })?; + // Label the supervisor for its launch only once the + // bundle's identities are known to be this sandbox's and + // the supervisor's own user can see the Workload API + // socket. A create request carries no generation of its + // own, so the bundle is checked against the one it names. + if let Some(launch_spiffe_id) = self.provider_launch_spiffe_id( + &sandbox.id, + launch_authentication.supervisor.runtime_generation.as_str(), + &launch_authentication, + )? { + self.probe_provider_supervisor( + &runtime_config.supervisor_image, + Some(&identity), + ) + .await?; + specs.record_provider_launch(launch_spiffe_id); + } let archives = crate::isolation::bootstrap_archives( crate::isolation::BootstrapArchivesInput { runtime_initiated: true, @@ -2013,6 +2167,187 @@ impl PodmanComputeDriver { Ok(()) } + /// How the sandbox's supervisor stands to the launch that a start names. + async fn launch_supervisor( + &self, + sandbox_id: &str, + launch_spiffe_id: &str, + refresh_trust: bool, + ) -> Result { + let supervisor = crate::isolation::supervisor_name(sandbox_id); + let inspect = match self.client.inspect_container(&supervisor).await { + Ok(inspect) => inspect, + Err(PodmanApiError::NotFound(_)) => return Ok(LaunchSupervisor::Create), + Err(error) => return Err(error.into()), + }; + let label = |key: &str| inspect.config.labels.get(key).map(String::as_str); + // Podman fixes labels at creation, so only a new supervisor can carry + // another launch or the current destination trust. + if label(LABEL_PROVIDER_LAUNCH_SPIFFE_ID) != Some(launch_spiffe_id) + || (refresh_trust + && label(NETWORK_SUPERVISOR_TRUST_GENERATION_KEY) + != Some(self.expected_network_trust_generation())) + { + return Ok(LaunchSupervisor::Create); + } + Ok(match inspect.state.status.as_str() { + _ if inspect.state.running => LaunchSupervisor::Running, + "exited" | "stopped" => LaunchSupervisor::Stopped, + // Created but never started: its bootstrap may be missing. + _ => LaunchSupervisor::Create, + }) + } + + /// Give a kept, stopped workload a new supervisor that carries the launch + /// in this start. + /// + /// Everything that can fail without changing the pair runs first. Then the + /// supervisor under the canonical name is stopped and removed, so a + /// sandbox never has two, and the new one is created and started. A + /// failure after the removal leaves no supervisor, or one that the next + /// start removes here. + async fn create_supervisor_for_launch( + &self, + sandbox_id: &str, + workload_id: &str, + durable_sandbox: Option<&DriverSandbox>, + generation: &str, + launch_authentication: &openshell_core::jwt::SandboxLaunchAuthentication, + launch_spiffe_id: &str, + ) -> Result<(), ComputeDriverError> { + let sandbox = durable_sandbox + .filter(|sandbox| { + sandbox.id == sandbox_id && !sandbox.name.is_empty() && sandbox.spec.is_some() + }) + .ok_or_else(|| { + ComputeDriverError::Precondition( + "a durable provisioning snapshot of this sandbox is required to create its \ + Podman supervisor" + .into(), + ) + })?; + // The kept workload pins its image. Its devices and runtime binary are + // already in the container, so neither is selected or extracted again. + let image = self + .resolve_retained_workload_image( + workload_id, + container::resolve_image(sandbox, &self.config), + ) + .await?; + validate_sandbox_proxy_ca_bundle(&self.config).await?; + let host_gateway_ip = self + .config + .resolved_host_gateway_ip() + .map_err(ComputeDriverError::from)?; + let identity = self + .resolve_workload_identity(sandbox, &image.id, &image.oci_user) + .await?; + let mut config = self.config.clone(); + self.client + .pull_image( + &config.supervisor_image, + runtime_image_pull_policy(&config.supervisor_image), + ) + .await?; + config.supervisor_image = self + .client + .inspect_image(&self.config.supervisor_image) + .await? + .id; + self.probe_provider_supervisor(&config.supervisor_image, Some(&identity)) + .await?; + let token_secret = container::token_secret_name(sandbox_id); + let token_secret = self + .client + .secret_exists(&token_secret) + .await? + .then_some(token_secret); + let tls_secrets = self + .config + .tls_enabled() + .then(|| container::tls_secret_names(sandbox_id)); + let mut specs = container::build_isolation_specs(container::IsolationSpecInput { + sandbox, + config: &config, + token_secret: token_secret.as_deref(), + resolver_secret: &container::resolver_secret_name(sandbox_id), + gpu_devices: None, + image: &image, + supervisor_bin: None, + tls_secrets: tls_secrets.as_ref(), + network_trust: self.network_trust.as_ref(), + identity: &identity, + })?; + specs.record_provider_launch(launch_spiffe_id); + let archives = + crate::isolation::bootstrap_archives(crate::isolation::BootstrapArchivesInput { + runtime_initiated: true, + sandbox_id, + container_id: workload_id, + generation, + host_gateway_ip, + identity: &identity, + allow_extra_supplementary_groups: crate::isolation::userns_preserves_host_groups( + self.config.userns.as_deref(), + ), + child_env: podman_child_environment(sandbox, &image.environment), + launch_authentication, + })?; + // Fence delayed stop/die events from the previous workload run, as + // the in-place start does. + let previous = self.client.inspect_container(workload_id).await?; + self.lifecycle_event_fences + .record_previous_exit(sandbox_id, previous.state.finished_at.as_deref()); + self.client.verify_isolation_fence(workload_id).await?; + + let supervisor = crate::isolation::supervisor_name(sandbox_id); + let gone = |result: Result<(), PodmanApiError>| match result { + Ok(()) | Err(PodmanApiError::NotFound(_)) => Ok(()), + Err(error) => Err(ComputeDriverError::from(error)), + }; + gone( + self.client + .stop_container(&supervisor, self.config.stop_timeout_secs) + .await, + )?; + gone( + self.client + .remove_container_preserving_volumes(&supervisor) + .await, + )?; + // Only a supervisor mounts these secrets and none exists now, so the + // new one gets the operator's current proxy credential and gateway CA. + create_sandbox_proxy_auth_secret(&self.client, &self.config, sandbox).await?; + if let Some(names) = &tls_secrets { + create_tls_secrets(&self.client, &self.config, names).await?; + } + self.client + .copy_to_container( + workload_id, + crate::isolation::CHANNEL_ROOT, + archives.channel, + ) + .await?; + if let Some(control) = archives.control { + self.client + .copy_to_container(workload_id, crate::isolation::CONTROL_ROOT, control) + .await?; + } + let supervisor = self + .client + .create_typed_container(&specs.supervisor) + .await?; + self.client + .copy_to_container(&supervisor, "/", archives.supervisor) + .await?; + self.client.start_container(workload_id).await?; + if let Err(error) = self.client.start_container(&supervisor).await { + let _ = self.client.stop_container(workload_id, 0).await; + return Err(error.into()); + } + Ok(()) + } + /// Start a previously stopped sandbox container. #[tracing::instrument( name = "podman.start_sandbox", @@ -2042,6 +2377,12 @@ impl PodmanComputeDriver { let launch_authentication = (!encoded_authentication.is_empty()) .then(|| decode_launch_authentication(encoded_authentication)) .transpose()?; + let provider_launch = match &launch_authentication { + Some(authentication) => self + .provider_launch_spiffe_id(sandbox_id, generation.as_str(), authentication)? + .map(|launch_spiffe_id| (authentication, launch_spiffe_id)), + None => None, + }; let container = self .find_container(sandbox_id) .await? @@ -2084,6 +2425,33 @@ impl PodmanComputeDriver { self.wait_for_container_stopped(sandbox_id, &container.id) .await?; } + // A bundle that names a provider launch needs a supervisor labeled for + // it. The launch SPIFFE ID changes with the runtime generation, and a + // retry repeats it, so this converges on whatever an earlier attempt + // left behind. + let mut recreate_if_start_fails = None; + if let Some((authentication, launch_spiffe_id)) = provider_launch { + match self + .launch_supervisor(sandbox_id, launch_spiffe_id, !workload_running) + .await? + { + LaunchSupervisor::Running => {} + LaunchSupervisor::Stopped => recreate_if_start_fails = provider_launch, + LaunchSupervisor::Create => { + let result = self + .create_supervisor_for_launch( + sandbox_id, + &container.id, + durable_sandbox, + generation.as_str(), + authentication, + launch_spiffe_id, + ) + .await; + return span_status.finish(result); + } + } + } // A user-driven start of a stopped sandbox mints fresh launch // credentials. When the trusted supervisor predates the gateway's // current destination-trust bundle (including supervisors created @@ -2197,6 +2565,21 @@ impl PodmanComputeDriver { Ok(()) } .await; + let result = match (result, recreate_if_start_fails) { + (Err(error), Some((authentication, launch_spiffe_id))) => { + warn!(%sandbox_id, %error, "Could not restart the stopped Podman supervisor; creating it again"); + self.create_supervisor_for_launch( + sandbox_id, + &container_id, + durable_sandbox, + generation.as_str(), + authentication, + launch_spiffe_id, + ) + .await + } + (result, _) => result, + }; span_status.finish(result) } @@ -2455,6 +2838,7 @@ impl PodmanComputeDriver { (refresh_inventory.clone(), allow_all_default_gpu) }), lifecycle_event_fences: LifecycleEventFences::default(), + provider_workload_identity: false, network_trust: None, network_trust_staging: None, } @@ -2986,6 +3370,340 @@ mod tests { ); } + /// A driver that qualified for verified provider workload identity. + fn provider_identity_driver(socket_path: PathBuf) -> PodmanComputeDriver { + let mut driver = test_driver(socket_path); + driver.config.default_image = "app:test".into(); + driver.config.provider_spiffe_workload_api_socket = Some("/run/spire/agent.sock".into()); + driver.provider_workload_identity = true; + driver + } + + const STABLE_SPIFFE_ID: &str = "spiffe://example.test/gateway/gateway-test/sandbox/sandbox-1"; + + /// The launch SPIFFE ID of `sandbox-1` for a runtime generation. + fn launch_spiffe_id(generation: &str) -> String { + format!("{STABLE_SPIFFE_ID}/launch/{generation}") + } + + /// The `generation-1` launch bundle of `sandbox-1`, naming a launch. + fn provider_launch_authentication(launch_spiffe_id: &str) -> Vec { + let mut authentication = launch_authentication(); + authentication.supervisor.provider_spiffe_id = Some(STABLE_SPIFFE_ID.into()); + authentication.supervisor.provider_launch_spiffe_id = Some(launch_spiffe_id.into()); + serde_json::to_vec(&authentication).unwrap() + } + + /// An inspected supervisor with current destination trust. + fn supervisor(status: &str, launch_spiffe_id: Option<&str>) -> StubResponse { + let mut labels = serde_json::json!({ + NETWORK_SUPERVISOR_TRUST_GENERATION_KEY: NETWORK_SUPERVISOR_TRUST_GENERATION_NONE, + }); + if let Some(launch_spiffe_id) = launch_spiffe_id { + labels[LABEL_PROVIDER_LAUNCH_SPIFFE_ID] = launch_spiffe_id.into(); + } + StubResponse::new( + StatusCode::OK, + serde_json::json!({ + "Id": "sup-1", + "Name": "supervisor", + "State": {"Status": status, "Running": status == "running"}, + "Config": {"Labels": labels}, + }) + .to_string(), + ) + } + + const STOPPED_WORKLOAD_LIST: &str = + r#"[{"Id":"ctr-1","State":"exited","Labels":{"openshell.ai/sandbox-id":"sandbox-1"}}]"#; + const STOPPED_WORKLOAD: &str = r#"{"Id":"ctr-1","Name":"sandbox","State":{"Status":"exited","Running":false,"FinishedAt":"2026-08-12T16:39:13Z"},"Config":{"Image":"sha256:sandbox"}}"#; + + /// The requests of `create_supervisor_for_launch`. `secrets` is the + /// number of supervisor secrets the driver's settings make it write. + fn supervisor_creation_responses(launch_spiffe_id: &str, secrets: usize) -> Vec { + let no_content = || StubResponse::new(StatusCode::NO_CONTENT, ""); + let not_found = || StubResponse::new(StatusCode::NOT_FOUND, ""); + let mut responses = vec![ + // Everything that can fail without changing the pair. + StubResponse::new(StatusCode::OK, STOPPED_WORKLOAD), // the kept workload's image + image_response("sha256:sandbox"), + created_response("identity-reader"), + not_found(), // reserved hierarchy absent + not_found(), // optional passwd + not_found(), // optional group + no_content(), // remove stopped reader + StubResponse::new(StatusCode::OK, "{}"), // supervisor pull + image_response("sha256:supervisor"), + created_response("probe") + .with_json_field("/image", "sha256:supervisor") + .with_json_field("/user", "1234:1235") + .with_json_field("/command/1", "/spiffe-workload-api/agent.sock"), + no_content(), // probe start + StubResponse::new(StatusCode::OK, "70"), // probe sees the socket + no_content(), // remove probe + not_found(), // no token secret + StubResponse::new(StatusCode::OK, STOPPED_WORKLOAD), // event fence + fence_response(), + // The pair changes from here. + no_content(), // stop the supervisor under the canonical name + no_content(), // remove it + ]; + responses.extend((0..secrets).map(|_| StubResponse::new(StatusCode::CREATED, "{}"))); + responses.extend([ + StubResponse::new(StatusCode::OK, "").with_archive_members(channel_archive_members()), + StubResponse::new(StatusCode::OK, "").with_archive_members(&["."]), // control volume + created_response("supervisor").with_json_field( + "/labels/openshell.ai~1provider-launch-spiffe-id", + launch_spiffe_id, + ), + StubResponse::new(StatusCode::OK, ""), // supervisor archive + no_content(), // workload start + no_content(), // supervisor start + ]); + responses + } + + #[tokio::test] + async fn start_converges_on_a_supervisor_that_carries_the_launch() { + let launch = launch_spiffe_id("generation-1"); + let authentication = provider_launch_authentication(&launch); + let previous = launch_spiffe_id("generation-0"); + let ok = |body: &'static str| StubResponse::new(StatusCode::OK, body); + let not_found = || StubResponse::new(StatusCode::NOT_FOUND, ""); + // The supervisor is inspected for the launch and again for `main`'s + // trust check before `main` restarts the pair in place. + let restart = |status: &'static str| { + vec![ + supervisor(status, Some(&launch)), + supervisor(status, Some(&launch)), + ok(STOPPED_WORKLOAD), + ] + }; + let cases: [(&str, Vec, bool); 7] = [ + ("no supervisor", vec![not_found()], true), + ("this launch, running", restart("running"), false), + ("this launch, stopped", restart("exited"), false), + ( + "this launch, stopped, cannot start", + restart("exited") + .into_iter() + .chain([ + StubResponse::new(StatusCode::NO_CONTENT, ""), // supervisor stop + supervisor("exited", Some(&launch)), + not_found(), // no restart metadata + ]) + .collect(), + true, + ), + ( + "this launch, never started", + vec![supervisor("created", Some(&launch))], + true, + ), + ( + "another launch", + vec![supervisor("running", Some(&previous))], + true, + ), + ("no launch", vec![supervisor("exited", None)], true), + ]; + for (case, found, created) in cases { + let then = if created { + supervisor_creation_responses(&launch, 0) + } else { + restart_responses() + }; + let (socket, requests, handle) = spawn_podman_stub( + "launch-converges", + std::iter::once(ok(STOPPED_WORKLOAD_LIST)) + .chain(found) + .chain(then) + .collect(), + ); + provider_identity_driver(socket) + .start_sandbox( + "sandbox-1", + "generation-1", + &authentication, + Some(&plain_sandbox("sandbox-1", "demo")), + ) + .await + .unwrap_or_else(|error| panic!("{case}: {error}")); + handle.await.unwrap_or_else(|_| panic!("{case}: stub")); + let requests = requests.lock().unwrap(); + let count = |needle: &str| { + requests + .iter() + .filter(|request| request.contains(needle)) + .count() + }; + // The stub checks the probe and the new supervisor's label. A kept + // workload costs one pull, of the supervisor image, and three + // containers: the identity reader, the probe, and the supervisor. + assert_eq!( + (count("/containers/create"), count("/images/pull")), + if created { (3, 1) } else { (0, 0) }, + "{case}: {requests:?}" + ); + assert_eq!( + count("/rename") + count("/volumes/create") + count("/secrets/create"), + 0, + "{case}: only the supervisor changes: {requests:?}" + ); + } + } + + #[tokio::test] + async fn the_next_start_repairs_a_replacement_that_failed_after_removing_the_supervisor() { + let launch = launch_spiffe_id("generation-1"); + let authentication = provider_launch_authentication(&launch); + let durable = plain_sandbox("sandbox-1", "demo"); + // Proxy credentials and a gateway CA: both reach a supervisor as secrets. + let auth_file = write_proxy_auth_file("launch-repair"); + let ca_file = auth_file.with_extension("ca"); + fs::write(&ca_file, "gateway CA").unwrap(); + let driver = |socket| { + let mut driver = provider_identity_driver(socket); + driver.config.proxy_auth_file = Some(auth_file.to_string_lossy().into_owned()); + driver.config.proxy_auth_allow_insecure = Some(true); + driver.config.guest_tls_ca = Some(ca_file.clone()); + driver + }; + let ok = |body: &'static str| StubResponse::new(StatusCode::OK, body); + + // The supervisor of the previous launch is removed, then the create fails. + let mut failing = supervisor_creation_responses(&launch, 2); + failing.truncate(failing.len() - 4); + failing.push(StubResponse::new( + StatusCode::INTERNAL_SERVER_ERROR, + "create failed", + )); + let (socket, requests, handle) = spawn_podman_stub( + "launch-repair-fails", + [ + ok(STOPPED_WORKLOAD_LIST), + supervisor("running", Some(&launch_spiffe_id("generation-0"))), + ] + .into_iter() + .chain(failing) + .collect(), + ); + driver(socket) + .start_sandbox("sandbox-1", "generation-1", &authentication, Some(&durable)) + .await + .expect_err("supervisor create should fail"); + handle.await.expect("stub should finish"); + let requests = requests.lock().unwrap().clone(); + let position = |needle: &str| { + requests + .iter() + .position(|request| request.contains(needle)) + .unwrap_or_else(|| panic!("no {needle} in {requests:?}")) + }; + // The probe passes before the old supervisor goes, and the secrets + // only supervisors mount are rewritten once none exists. + let removed = position(&format!( + "DELETE {}", + api_path("/libpod/containers/openshell-supervisor-sandbox-1") + )); + assert!(position("/wait?condition=exited") < removed, "{requests:?}"); + assert!(removed < position("/secrets/create"), "{requests:?}"); + assert!( + !requests + .iter() + .any(|request| request.starts_with("DELETE") && request.contains("/secrets/")), + "no secret may be deleted: {requests:?}" + ); + + // No supervisor is left, so the retry creates one for the same launch. + let (socket, _requests, handle) = spawn_podman_stub( + "launch-repair-retries", + [ + ok(STOPPED_WORKLOAD_LIST), + StubResponse::new(StatusCode::NOT_FOUND, ""), + ] + .into_iter() + .chain(supervisor_creation_responses(&launch, 2)) + .collect(), + ); + driver(socket) + .start_sandbox("sandbox-1", "generation-1", &authentication, Some(&durable)) + .await + .expect("the retry should create the supervisor"); + handle.await.expect("stub should finish"); + let _ = fs::remove_file(auth_file); + let _ = fs::remove_file(ca_file); + } + + #[tokio::test] + async fn start_rejects_a_launch_bundle_that_is_not_this_sandbox_launch() { + let authentication = provider_launch_authentication(&launch_spiffe_id("generation-1")); + let offline = || provider_identity_driver(PathBuf::from("/nonexistent/podman.sock")); + for (sandbox_id, generation_id, launch) in [ + ("sandbox-2", "generation-1", "generation-1"), + ("sandbox-1", "generation-2", "generation-1"), + ("sandbox-1", "generation-1", "generation-0"), + ] { + let authentication = provider_launch_authentication(&launch_spiffe_id(launch)); + let error = offline() + .start_sandbox(sandbox_id, generation_id, &authentication, None) + .await + .unwrap_err(); + assert!( + matches!(error, ComputeDriverError::InvalidArgument(_)), + "{sandbox_id} {generation_id} {launch}: {error}" + ); + } + // A driver that did not qualify never labels a supervisor. + let mut unqualified = offline(); + unqualified.provider_workload_identity = false; + let error = unqualified + .start_sandbox("sandbox-1", "generation-1", &authentication, None) + .await + .unwrap_err(); + assert!( + matches!(error, ComputeDriverError::Precondition(_)), + "{error}" + ); + } + + #[tokio::test] + async fn provider_probe_qualifies_the_image_and_a_launch_needs_the_socket() { + let identity = openshell_isolation_interface::contract::ResolvedWorkloadIdentity::new( + 1000, + 1001, + vec![], + "image".into(), + "sha256:image".into(), + ) + .unwrap(); + // Driver startup probes as the engine's root; a launch probes as the + // workload's user and must see the socket. + for (exit, launch, passes) in [ + ("70", false, true), + ("71", false, true), + ("2", false, false), + ("70", true, true), + ("71", true, false), + ] { + let user = if launch { "1000:1001" } else { "0:0" }; + let (socket, _requests, handle) = spawn_podman_stub( + "provider-probe", + vec![ + created_response("probe").with_json_field("/user", user), + StubResponse::new(StatusCode::NO_CONTENT, ""), + StubResponse::new(StatusCode::OK, exit), + StubResponse::new(StatusCode::NO_CONTENT, ""), + ], + ); + let result = provider_identity_driver(socket) + .probe_provider_supervisor("supervisor:test", launch.then_some(&identity)) + .await; + handle.await.expect("stub should finish"); + assert_eq!(result.is_ok(), passes, "exit {exit}, launch {launch}"); + } + } + #[test] fn podman_driver_error_from_not_found() { let err = ComputeDriverError::from(PodmanApiError::NotFound("gone".into())); diff --git a/crates/openshell-driver-podman/src/main.rs b/crates/openshell-driver-podman/src/main.rs index 84079c856f..b762815f07 100644 --- a/crates/openshell-driver-podman/src/main.rs +++ b/crates/openshell-driver-podman/src/main.rs @@ -283,6 +283,9 @@ async fn main() -> Result<()> { enable_bind_mounts: args.enable_bind_mounts, }, None, + // No gateway configures a standalone driver, so its Workload API + // socket setting selects verified provider workload identity. + true, ) .await .into_diagnostic()?; diff --git a/crates/openshell-driver-podman/src/serve.rs b/crates/openshell-driver-podman/src/serve.rs index 4350badcdc..a12ab7ceba 100644 --- a/crates/openshell-driver-podman/src/serve.rs +++ b/crates/openshell-driver-podman/src/serve.rs @@ -160,9 +160,13 @@ async fn apply_configure( )?; config.allow_driver_config = admission.allow_driver_config; config.resource_admission = admission.resource_admission; - let driver = PodmanComputeDriver::new(config, network_trust) - .await - .map_err(|error| Status::internal(error.to_string()))?; + let driver = PodmanComputeDriver::new( + config, + network_trust, + request.verified_provider_workload_identity == Some(true), + ) + .await + .map_err(|error| Status::internal(error.to_string()))?; Ok(ComputeDriverService::new(driver)) } diff --git a/crates/openshell-driver-podman/src/test_utils.rs b/crates/openshell-driver-podman/src/test_utils.rs index 25cbcb4ac2..925b566e3e 100644 --- a/crates/openshell-driver-podman/src/test_utils.rs +++ b/crates/openshell-driver-podman/src/test_utils.rs @@ -23,6 +23,7 @@ pub struct StubResponse { pub body: Bytes, pub delay: Duration, pub archive_members: Option>, + pub json_fields: Vec<(&'static str, serde_json::Value)>, } impl StubResponse { @@ -32,9 +33,20 @@ impl StubResponse { body: body.into(), delay: Duration::ZERO, archive_members: None, + json_fields: Vec::new(), } } + /// Expect the JSON request body to hold `value` at a JSON pointer. + pub fn with_json_field( + mut self, + pointer: &'static str, + value: impl Into, + ) -> Self { + self.json_fields.push((pointer, value.into())); + self + } + pub fn with_delay(mut self, delay: Duration) -> Self { self.delay = delay; self @@ -121,6 +133,13 @@ pub fn spawn_podman_stub( .map(|entry| entry.unwrap().path().unwrap().into_owned()) .collect(); assert_eq!(&members, expected_members); + } else if !response.json_fields.is_empty() { + let body = req.into_body().collect().await.unwrap().to_bytes(); + let json: serde_json::Value = + serde_json::from_slice(&body).unwrap(); + for (pointer, value) in &response.json_fields { + assert_eq!(json.pointer(pointer), Some(value), "{pointer}"); + } } tokio::time::sleep(response.delay).await; Ok::<_, Infallible>( diff --git a/crates/openshell-driver-podman/tests/serve_configure.rs b/crates/openshell-driver-podman/tests/serve_configure.rs index 896f790739..e2df82cc8c 100644 --- a/crates/openshell-driver-podman/tests/serve_configure.rs +++ b/crates/openshell-driver-podman/tests/serve_configure.rs @@ -10,9 +10,13 @@ use std::io::{Read as _, Write as _}; use std::os::unix::net::UnixListener; use std::path::Path; use std::process::{Child, Command, Output, Stdio}; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use hyper_util::rt::TokioIo; +use openshell_core::extension_protocol::{ + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, ExtensionFamily, gateway_metadata, has_capability, +}; use openshell_core::proto::compute::v1::GetCapabilitiesRequest; use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; @@ -88,8 +92,12 @@ async fn serve() -> Serving { let dir = tempfile::tempdir().unwrap(); let podman = dir.path().join("podman.sock"); fake_podman(&podman); - let socket = dir.path().join("driver.sock"); let table = format!("socket_path = \"{}\"\n", podman.display()); + serve_with_table(dir, &table).await +} + +async fn serve_with_table(dir: tempfile::TempDir, table: &str) -> Serving { + let socket = dir.path().join("driver.sock"); let mut child = command( &[ "serve", @@ -98,7 +106,7 @@ async fn serve() -> Serving { "--expected-peer-pid", &std::process::id().to_string(), ], - &table, + table, dir.path(), ) .spawn() @@ -130,6 +138,107 @@ fn configure(version: u32) -> ConfigureRequest { } } +/// A Podman API that lets `Configure` build the driver and answers the +/// provider identity probe with `probe_exit`. Returns its request lines. +fn configurable_podman(path: &Path, probe_exit: &'static str) -> Arc>> { + let listener = UnixListener::bind(path).unwrap(); + let requests = Arc::new(Mutex::new(Vec::new())); + let log = Arc::clone(&requests); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buffer = [0_u8; 4096]; + let read = stream.read(&mut buffer).unwrap_or_default(); + let request = String::from_utf8_lossy(&buffer[..read]) + .lines() + .next() + .unwrap_or_default() + .to_string(); + let (status, body) = if request.contains("/_ping") { + ("200 OK", "OK") + } else if request.contains("/libpod/info") { + ("200 OK", r#"{"host":{"cgroupVersion":"v2"}}"#) + } else if request.contains("/libpod/networks/create") { + ("201 Created", "{}") + } else if request.contains("/libpod/containers/json") { + ("200 OK", "[]") + } else if request.contains("/libpod/images/pull") { + ("200 OK", "{}") + } else if request.contains("/libpod/containers/create") { + ("201 Created", r#"{"Id":"probe"}"#) + } else if request.contains("/wait") { + ("200 OK", probe_exit) + } else { + // The probe container's start and removal. + ("204 No Content", "") + }; + log.lock().unwrap().push(request); + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len(), + ); + } + }); + requests +} + +#[tokio::test] +async fn provider_workload_identity_is_advertised_only_when_selected_and_qualified() { + const LOOPBACK: &str = "http://127.0.0.1:8080"; + for (selected, grpc_endpoint, probe_exit, probed, advertised) in [ + // A managed driver needs the gateway's explicit selection. + (None, LOOPBACK, "70", false, false), + (Some(false), LOOPBACK, "70", false, false), + (Some(true), LOOPBACK, "70", true, true), + // The supervisor image does not know the probe. + (Some(true), LOOPBACK, "2", true, false), + // Workload assertions must not cross plaintext to another host. + (Some(true), "http://gateway.test:8080", "70", false, false), + ] { + let case = format!("{selected:?} {grpc_endpoint} exit {probe_exit}"); + let dir = tempfile::tempdir().unwrap(); + let podman = dir.path().join("podman.sock"); + let requests = configurable_podman(&podman, probe_exit); + let table = format!( + "socket_path = \"{}\"\n\ + grpc_endpoint = \"{grpc_endpoint}\"\n\ + provider_spiffe_workload_api_socket = \"/run/spire/agent.sock\"\n", + podman.display(), + ); + let serving = serve_with_table(dir, &table).await; + let mut request = configure(PROTOCOL_VERSION); + request.verified_provider_workload_identity = selected; + DriverLaunchClient::new(serving.channel.clone()) + .configure(request) + .await + .unwrap_or_else(|error| panic!("{case}: Configure failed: {error}")); + let capabilities = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest { + gateway: Some(gateway_metadata(ExtensionFamily::Compute)), + }) + .await + .unwrap() + .into_inner() + .extension + .unwrap() + .supported_capabilities; + assert_eq!( + has_capability(&capabilities, COMPUTE_PROVIDER_WORKLOAD_IDENTITY), + advertised, + "{case}" + ); + let requests = requests.lock().unwrap(); + assert_eq!( + requests + .iter() + .any(|request| request.contains("/libpod/containers/create")), + probed, + "{case}: {requests:?}" + ); + } +} + #[tokio::test] async fn launch_info_answers_and_compute_calls_wait_for_configure() { let serving = serve().await;