From 8ed1b3b94d7e94469aa68e548c5c047a71fe72cb Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:35:01 +0530 Subject: [PATCH] feat(docker): support provider workload identity Let the Docker driver start supervisors that a Workload API issuer can bind to one sandbox launch. - The driver labels the supervisor container with the launch SPIFFE ID from its launch bundle, after checking that the bundle's identities belong to the sandbox. The workload container carries the label with an empty value, so an image or template label cannot set it. - The driver advertises provider workload identity when the mode is selected, the Workload API socket is configured, the supervisor can reach the gateway over HTTPS or numeric loopback, and a probe shows that the supervisor image supports the mode. A managed driver needs the gateway's selection. A standalone driver qualifies from its socket setting. - A start whose launch differs from the running supervisor's replaces the supervisor. The driver already recreates the supervisor on a start. A supervisor left over from a stopped workload is now removed unless it carries the requested launch. Create, stop, delete, startup cleanup and monitoring are unchanged. Signed-off-by: Shiju --- crates/openshell-driver-docker/README.md | 2 + .../src/image_update.rs | 3 + .../src/image_update/tests.rs | 100 ++++++ crates/openshell-driver-docker/src/lib.rs | 321 +++++++++++++++--- crates/openshell-driver-docker/src/serve.rs | 4 +- crates/openshell-driver-docker/src/tests.rs | 191 +++++++++++ 6 files changed, 572 insertions(+), 49 deletions(-) diff --git a/crates/openshell-driver-docker/README.md b/crates/openshell-driver-docker/README.md index 871c9f2f01..cfb1add0f9 100644 --- a/crates/openshell-driver-docker/README.md +++ b/crates/openshell-driver-docker/README.md @@ -330,3 +330,5 @@ The gateway passes the `[openshell.drivers.docker]` table on stdin and gateway m `serve` resolves the Docker socket from `socket_path`, then `DOCKER_HOST` and the usual locations, 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 Docker is not reachable and 78 when the table is invalid. Until `Configure` succeeds, both gRPC services (`ComputeDriver` and `ComputeDriverConfigurationUpdates`) return `UNAVAILABLE` and the driver creates no volumes, networks or containers. `preflight` validates the table without contacting Docker. The gateway supplies the CA, the admission policy, its listener address, trusted runtime images from its environment, destination trust, and OTLP settings through `Configure`, so the table rejects `guest_tls_ca`, `allow_driver_config` and `resource_admission`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. + +`Configure` also says whether the gateway selected verified provider workload identity. A launched driver offers that mode only on an explicit `true`, and only when `provider_spiffe_workload_api_socket` is set, the supervisor reaches the gateway over HTTPS or a loopback IP address, and the supervisor image passes the probe. diff --git a/crates/openshell-driver-docker/src/image_update.rs b/crates/openshell-driver-docker/src/image_update.rs index 4c5070f2c9..89546484ff 100644 --- a/crates/openshell-driver-docker/src/image_update.rs +++ b/crates/openshell-driver-docker/src/image_update.rs @@ -645,6 +645,9 @@ impl DockerComputeDriver { .ok_or_else(|| invalid("Docker workload labels are missing"))?; labels.insert(OPERATION_LABEL.into(), p.operation_id.clone()); labels.insert(REVISION_LABEL.into(), p.revision.to_string()); + // The source can predate this label. An empty value keeps the new + // image's label off the workload. + labels.insert(LABEL_PROVIDER_LAUNCH_SPIFFE_ID.into(), String::new()); let container_name = source .name .as_deref() diff --git a/crates/openshell-driver-docker/src/image_update/tests.rs b/crates/openshell-driver-docker/src/image_update/tests.rs index 3ba13f7e21..2d4694b748 100644 --- a/crates/openshell-driver-docker/src/image_update/tests.rs +++ b/crates/openshell-driver-docker/src/image_update/tests.rs @@ -230,6 +230,11 @@ impl Fixture { .as_mut() .unwrap() .insert(REVISION_LABEL.into(), self.p().revision.to_string()); + config + .labels + .as_mut() + .unwrap() + .insert(LABEL_PROVIDER_LAUNCH_SPIFFE_ID.into(), String::new()); target.state.as_mut().unwrap().status = Some(ContainerStateStatusEnum::CREATED); target } @@ -497,6 +502,8 @@ async fn image_replacement_keeps_native_and_volume_identity_and_publishes_new_ev assert_eq!(intent.sandbox_id, fixture.p().sandbox_id); assert_eq!(intent.target_container.as_deref(), Some("container-B")); assert_eq!(requests[8]["Image"], "sha256:corrected"); + // An explicit empty value keeps the new image's label off the workload. + assert_eq!(requests[8]["Labels"][LABEL_PROVIDER_LAUNCH_SPIFFE_ID], ""); assert!( !requests[8]["Env"] .as_array() @@ -917,6 +924,99 @@ async fn stopped_start_repairs_interrupted_launch_rotation_before_staging() { ); } +#[tokio::test] +async fn start_replaces_only_a_supervisor_of_another_launch() { + use crate::tests::test_verified_launch_authentication as launch; + + enum Outcome { + Kept, + Replaced, + Rejected, + } + use Outcome::{Kept, Rejected, Replaced}; + // The launch SPIFFE ID names the runtime generation: a retried start + // carries the same launch and a later start carries another. + let (first, second) = ("generation-1", "generation-2"); + // (generation the supervisor carries, generation started, the bundle + // names this sandbox, outcome) + for (carried, started, bundle_names_this_sandbox, outcome) in [ + (Some(first), first, true, Kept), + (Some(first), second, true, Replaced), + (None, second, true, Replaced), + (Some(first), second, false, Rejected), + ] { + let mut fixture = Fixture::new(); + fixture.config.provider_workload_identity = true; + fixture + .call(fixture.apply_replies(), &fixture.request) + .await + .0 + .unwrap(); + let sandbox_id = fixture.p().sandbox_id.clone(); + let (docker, server) = docker_api(fixture.start_replies(false)).await; + let mut driver = test_driver_with_config(fixture.config.clone()); + driver.docker = Arc::new(docker); + // A supervisor that outlived its stopped workload. + let (shutdown, stopped) = oneshot::channel(); + driver.control_processes.lock().await.insert( + sandbox_id.clone(), + DockerControlProcess { + shutdown: Some(shutdown), + intentional_shutdown: Arc::default(), + task: tokio::spawn(async move { + let _ = stopped.await; + }), + launch_spiffe_id: carried.and_then(|carried| { + launch(&sandbox_id, carried) + .supervisor + .provider_launch_spiffe_id + }), + }, + ); + + let authentication = if bundle_names_this_sandbox { + launch(&sandbox_id, started) + } else { + launch("another-sandbox", started) + }; + let error = Box::pin(driver.start_sandbox( + &sandbox_id, + &fixture.p().name, + started, + &serde_json::to_vec(&authentication).unwrap(), + None, + )) + .await + .unwrap_err(); + server.await.unwrap(); + let kept = driver + .control_processes + .lock() + .await + .contains_key(&sandbox_id); + if matches!(outcome, Rejected) { + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!(kept); + // The bundle was never saved, so no supervisor can carry its launch. + assert!(!fixture.directory.join(SUPERVISOR_AUTH_BUNDLE_FILE).exists()); + continue; + } + // Deliberately omit the workspace-root staging input: reaching this + // gate proves the real Start path decided, without a fake workload. + assert!(error.message().contains("workspace for restart"), "{error}"); + assert_eq!(kept, matches!(outcome, Kept)); + // The supervisor that Start creates next is labeled from the saved bundle. + let mut sandbox = test_sandbox(); + sandbox.id = sandbox_id; + let mut config = fixture.config.clone(); + config.guest_tls = None; + let (_, label) = docker_supervisor_bundle_archive(&sandbox, &config) + .await + .unwrap(); + assert_eq!(label, authentication.supervisor.provider_launch_spiffe_id); + } +} + #[tokio::test] async fn interrupted_launch_pair_requires_stopped_workload_and_fresh_authentication() { for (running, fresh_authentication, inspected_running) in [ diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 75e894bd5e..874ff5563e 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -30,16 +30,22 @@ use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS; use openshell_core::driver_mounts; use openshell_core::driver_utils::{ CONDITION_EXITED, CONDITION_RUNTIME_RESTART, CONDITION_WORKSPACE_VALIDATION_FAILED, - LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, - LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, SANDBOX_RUNTIME_IMAGE_BINARY_PATH, + LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_PROVIDER_LAUNCH_SPIFFE_ID, LABEL_SANDBOX_ID, + LABEL_SANDBOX_NAME, LABEL_SANDBOX_NAMESPACE, LABEL_SANDBOX_WORKSPACE, + PROVIDER_WORKLOAD_IDENTITY_PROBE, PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT, + PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE, SANDBOX_RUNTIME_IMAGE_BINARY_PATH, SUPERVISOR_EXIT_WORKSPACE_VALIDATION_FAILED, WORKSPACE_VALIDATION_FAILED_MESSAGE, extract_first_tar_entry, supervisor_image_should_refresh, temp_extract_container_name, - validate_linux_elf_binary, + validate_linux_elf_binary, validate_provider_launch_identity, }; +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_device_names, validate_cdi_gpu_device_request, }; +use openshell_core::grpc_client::{ + token_grant_gateway_endpoint, validate_attested_token_grant_transport, +}; use openshell_core::progress::{ PROGRESS_STEP_PULLING_IMAGE, PROGRESS_STEP_REQUESTING_SANDBOX, PROGRESS_STEP_STARTING_SANDBOX, format_bytes, mark_progress_active, mark_progress_complete, mark_progress_detail, @@ -105,8 +111,8 @@ const SUPERVISOR_HEALTH_INTERVAL_NS: i64 = 30_000_000_000; const SUPERVISOR_HEALTH_START_INTERVAL_NS: i64 = 250_000_000; const SUPERVISOR_HEALTH_TIMEOUT_NS: i64 = 2_000_000_000; const SUPERVISOR_HEALTH_START_PERIOD_NS: i64 = 60_000_000_000; -const HOST_GATEWAY_RESOLUTION_TIMEOUT: Duration = Duration::from_secs(30); -const HOST_GATEWAY_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10); +const STAGING_SUPERVISOR_TIMEOUT: Duration = Duration::from_secs(30); +const STAGING_SUPERVISOR_CLEANUP_TIMEOUT: Duration = Duration::from_secs(10); const SANDBOX_BINARY_PATH: &str = "/.openshell/runtime/openshell-sandbox"; const SUPERVISOR_IMAGE_CONTROL_BINARY_PATH: &str = "/openshell-supervisor"; @@ -281,6 +287,12 @@ pub struct DockerComputeConfig { /// Host UNIX socket projected into the supervisor for provider identity. pub provider_spiffe_workload_api_socket: Option, + /// Whether the gateway selected verified provider workload identity. The + /// gateway supplies it through `Configure`; driver TOML cannot set it. + /// `None` for a standalone driver, whose socket setting selects the mode. + #[serde(skip)] + pub verified_provider_workload_identity: Option, + /// `AppArmor` confinement requested for the workload container. #[serde(default, skip_serializing_if = "Option::is_none")] pub app_armor_profile: Option, @@ -353,6 +365,7 @@ impl Default for DockerComputeConfig { proxy_ca_bundle: None, ipv6_egress: SupervisorIpv6EgressConfig::default(), provider_spiffe_workload_api_socket: None, + verified_provider_workload_identity: None, app_armor_profile: None, } } @@ -364,6 +377,7 @@ pub(crate) struct DockerGuestTlsPaths { } #[derive(Debug, Clone)] +#[allow(clippy::struct_excessive_bools)] struct DockerDriverRuntimeConfig { allow_driver_config: bool, resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, @@ -391,6 +405,8 @@ struct DockerDriverRuntimeConfig { proxy_ca_bundle: Option, ipv6_egress: SupervisorIpv6EgressConfig, provider_spiffe_workload_api_socket: Option, + /// The mode is selected and this driver's supervisors qualify for it. + provider_workload_identity: bool, app_armor_profile: Option, /// Immutable gateway-normalized additional destination trust. This is /// deliberately separate from `DockerComputeConfig` and sandbox input. @@ -420,6 +436,8 @@ struct DockerControlProcess { shutdown: Option>, intentional_shutdown: Arc, task: JoinHandle<()>, + /// Launch SPIFFE ID on the supervisor container's label, if any. + launch_spiffe_id: Option, } #[derive(Clone)] @@ -1030,7 +1048,7 @@ impl DockerComputeDriver { ) }; let guest_tls = docker_guest_tls_paths(&docker_config)?; - let driver = Self { + let mut driver = Self { docker: Arc::new(docker), config: DockerDriverRuntimeConfig { default_image: docker_config.default_image.clone(), @@ -1065,6 +1083,7 @@ impl DockerComputeDriver { provider_spiffe_workload_api_socket: docker_config .provider_spiffe_workload_api_socket .clone(), + provider_workload_identity: false, app_armor_profile: docker_config.app_armor_profile.clone(), network_trust, }, @@ -1080,6 +1099,13 @@ impl DockerComputeDriver { image_update_gates: Arc::new(image_update::Gates::default()), }; + driver.config.provider_workload_identity = docker_offers_provider_workload_identity( + &driver.docker, + &driver.config, + docker_config.verified_provider_workload_identity, + ) + .await; + Box::pin(driver.reconcile_runtime_resources_at_startup()) .await .map_err(|error| { @@ -1098,6 +1124,14 @@ impl DockerComputeDriver { } fn capabilities(&self) -> GetCapabilitiesResponse { + let mut capabilities = capabilities_if( + openshell_core::extension_protocol::COMPUTE_UPDATE_SANDBOX_CONFIGURATION, + self.config.workspace_storage == workspace::Storage::Persistent, + ); + capabilities.extend(capabilities_if( + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, + self.config.provider_workload_identity, + )); GetCapabilitiesResponse { resource_admission_policy: openshell_core::resource_admission::DriverAdmissionConfig { allow_driver_config: self.config.allow_driver_config, @@ -1128,14 +1162,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, )), } } @@ -1214,7 +1241,9 @@ impl DockerComputeDriver { Ok(()) } - fn validate_sandbox_auth(sandbox: &DriverSandbox) -> Result<(), Status> { + fn validate_sandbox_auth( + sandbox: &DriverSandbox, + ) -> Result { let authentication = sandbox .spec .as_ref() @@ -1224,7 +1253,7 @@ impl DockerComputeDriver { "docker sandboxes require launch-scoped gateway authentication", ) })?; - decode_docker_launch_authentication(&authentication.launch_authentication).map(|_| ()) + decode_docker_launch_authentication(&authentication.launch_authentication) } fn validate_gpu_request( @@ -1627,7 +1656,15 @@ impl DockerComputeDriver { async fn create_sandbox_inner(&self, sandbox: &DriverSandbox) -> Result<(), Status> { self.verify_network_trust()?; let validated = Self::validated_sandbox(sandbox, &self.config)?; - Self::validate_sandbox_auth(sandbox)?; + Self::validate_sandbox_auth(sandbox).and_then(|authentication| { + // Create names its generation only in the launch bundle. + docker_provider_launch_spiffe_id( + &self.config, + &sandbox.id, + authentication.supervisor.runtime_generation.as_str(), + &authentication, + ) + })?; self.validate_user_volume_mounts_available(&validated.driver_config, &sandbox.workspace) .await?; let _ = self @@ -2117,6 +2154,19 @@ impl DockerComputeDriver { } } + /// Stop the sandbox's supervisor unless it carries `launch_spiffe_id`. + async fn stop_control_process_of_other_launch(&self, sandbox_id: &str, launch_spiffe_id: &str) { + let carries_launch = self + .control_processes + .lock() + .await + .get(sandbox_id) + .is_some_and(|process| process.launch_spiffe_id.as_deref() == Some(launch_spiffe_id)); + if !carries_launch { + self.stop_control_process(sandbox_id).await; + } + } + async fn remove_auxiliary_containers_for_sandbox( &self, sandbox_id: &str, @@ -2648,6 +2698,17 @@ impl DockerComputeDriver { .as_ref() .and_then(|labels| labels.get(LABEL_SANDBOX_ID)) .map_or(sandbox_id, String::as_str); + // Check the provider identities before this start changes anything. + // A bundle that does not decode is rejected below, where it is used. + let launch_spiffe_id = match decode_docker_launch_authentication(launch_authentication) { + Ok(authentication) => docker_provider_launch_spiffe_id( + &self.config, + resolved_sandbox_id, + generation.as_str(), + &authentication, + )?, + Err(_) => None, + }; // No destination-trust gating here: the trusted supervisor container // is re-created from the gateway's current configuration on every // start (see `ensure_control_process_for_container`), so stop/start @@ -2698,6 +2759,12 @@ impl DockerComputeDriver { ) .await?; } + // A supervisor that outlived the stopped workload carries an older + // launch. Stop it, so the supervisor created below carries this one. + if let Some(launch_spiffe_id) = &launch_spiffe_id { + self.stop_control_process_of_other_launch(resolved_sandbox_id, launch_spiffe_id) + .await; + } image_update::validate_committed_boundary(&self.config, resolved_sandbox_id)?; let Some(runtime_descriptor) = read_docker_runtime_descriptor(resolved_sandbox_id, &self.config).await? @@ -4852,6 +4919,27 @@ fn decode_docker_launch_authentication( Ok(authentication) } +/// Return the launch SPIFFE ID that the supervisor for this launch bundle +/// carries. A bundle without provider identities names no launch. +fn docker_provider_launch_spiffe_id( + config: &DockerDriverRuntimeConfig, + sandbox_id: &str, + generation_id: &str, + authentication: &openshell_core::jwt::SandboxLaunchAuthentication, +) -> Result, Status> { + let supervisor = &authentication.supervisor; + if supervisor.provider_spiffe_id.is_none() && supervisor.provider_launch_spiffe_id.is_none() { + return Ok(None); + } + if !config.provider_workload_identity { + return Err(Status::failed_precondition( + "Docker does not offer verified provider workload identity", + )); + } + validate_provider_launch_identity(sandbox_id, generation_id, authentication)?; + Ok(supervisor.provider_launch_spiffe_id.clone()) +} + fn gateway_verification_keys( keys: &[openshell_core::jwt::SessionVerificationKey], ) -> Result, Status> { @@ -4999,10 +5087,12 @@ async fn prepare_docker_boundary_files( Ok(()) } +/// Build the supervisor's bundle. Also return the launch SPIFFE ID in its +/// authentication, which is the launch the supervisor container must carry. async fn docker_supervisor_bundle_archive( sandbox: &DriverSandbox, config: &DockerDriverRuntimeConfig, -) -> Result, Status> { +) -> Result<(Vec, Option), Status> { let directory = docker_boundary_state_dir(sandbox, config)?; let runtime_descriptor = tokio::fs::read(directory.join(RUNTIME_DESCRIPTOR_FILE)) .await @@ -5017,6 +5107,11 @@ async fn docker_supervisor_bundle_archive( "Docker supervisor requires launch authentication", )); } + // A bundle that does not parse names no launch. The supervisor rejects it. + let launch_spiffe_id = + serde_json::from_slice::(&auth_bundle) + .ok() + .and_then(|authentication| authentication.provider_launch_spiffe_id); let mut archive = tar::Builder::new(Vec::new()); append_docker_archive_file( &mut archive, @@ -5076,9 +5171,10 @@ async fn docker_supervisor_bundle_archive( )?; } append_docker_proxy_ca_bundle(&mut archive, config.proxy_ca_bundle.as_deref())?; - archive + let archive = archive .into_inner() - .map_err(|error| Status::internal(format!("finish Docker supervisor archive: {error}"))) + .map_err(|error| Status::internal(format!("finish Docker supervisor archive: {error}")))?; + Ok((archive, launch_spiffe_id)) } fn append_docker_proxy_ca_bundle( @@ -5401,6 +5497,24 @@ fn docker_auxiliary_container_labels( ]) } +/// Labels of a sandbox's supervisor container. The driver sets all of them. +/// The launch SPIFFE ID is the one in the supervisor's launch bundle. +fn docker_supervisor_labels( + sandbox: &DriverSandbox, + config: &DockerDriverRuntimeConfig, + launch_spiffe_id: Option<&str>, +) -> HashMap { + let mut labels = + docker_auxiliary_container_labels(sandbox, config, LABEL_ISOLATION_ROLE_SUPERVISOR); + if let Some(launch_spiffe_id) = launch_spiffe_id { + labels.insert( + LABEL_PROVIDER_LAUNCH_SPIFFE_ID.to_string(), + launch_spiffe_id.to_string(), + ); + } + labels +} + fn docker_supervisor_healthcheck() -> HealthConfig { HealthConfig { test: Some(vec![ @@ -5658,21 +5772,10 @@ async fn spawn_docker_control_process( openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET )); } - let supervisor_archive = docker_supervisor_bundle_archive(sandbox, config).await?; + let (supervisor_archive, launch_spiffe_id) = + docker_supervisor_bundle_archive(sandbox, config).await?; stage_docker_supervisor_bundle(docker, sandbox, config, supervisor_archive).await?; - let labels = HashMap::from([ - (LABEL_MANAGED_BY.to_string(), "openshell".to_string()), - (LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()), - (LABEL_SANDBOX_NAME.to_string(), sandbox.name.clone()), - ( - LABEL_SANDBOX_NAMESPACE.to_string(), - config.sandbox_namespace.clone(), - ), - ( - LABEL_ISOLATION_ROLE.to_string(), - LABEL_ISOLATION_ROLE_SUPERVISOR.to_string(), - ), - ]); + let labels = docker_supervisor_labels(sandbox, config, launch_spiffe_id.as_deref()); let mut command = vec![ "--backend-descriptor-file".to_string(), runtime_descriptor_path, @@ -5734,16 +5837,7 @@ async fn spawn_docker_control_process( supervisor_mounts.push(docker_network_trust_supervisor_mount(bundle)?); } if let Some(socket) = config.provider_spiffe_workload_api_socket.as_ref() { - let parent = socket.parent().ok_or_else(|| { - Status::failed_precondition("provider SPIFFE socket has no parent directory") - })?; - supervisor_mounts.push(Mount { - target: Some(PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.to_string()), - source: Some(parent.display().to_string()), - typ: Some(MountTypeEnum::BIND), - read_only: Some(true), - ..Default::default() - }); + supervisor_mounts.push(docker_provider_spiffe_socket_mount(socket)?); } let create = ContainerCreateBody { image: Some(config.supervisor_image_id.clone()), @@ -5864,6 +5958,7 @@ async fn spawn_docker_control_process( shutdown: Some(shutdown), intentional_shutdown, task, + launch_spiffe_id, }; if let Err(error) = Box::pin(wait_for_docker_supervisor_ready( docker, @@ -6449,6 +6544,9 @@ fn build_container_create_body_for_image( }] }); let mut labels = template.labels.clone(); + // Only a supervisor carries a launch. An empty create-time value also + // overrides the same key in a template or image label. + labels.insert(LABEL_PROVIDER_LAUNCH_SPIFFE_ID.to_string(), String::new()); // Persistence is recorded in protected driver state, never inferred from // or published over caller-owned template labels. labels.insert( @@ -7310,11 +7408,24 @@ fn validate_docker_host_gateway_ip( } fn docker_host_gateway_resolver_body(image: &str, namespace: &str) -> ContainerCreateBody { + let mut body = docker_staging_supervisor_body(image, namespace, vec!["--help".to_string()]); + if let Some(host) = body.host_config.as_mut() { + host.extra_hosts = Some(vec![format!("{HOST_OPEN_SHELL_INTERNAL}:host-gateway")]); + } + body +} + +/// A confined supervisor command that mounts no sandbox resources. +fn docker_staging_supervisor_body( + image: &str, + namespace: &str, + command: Vec, +) -> ContainerCreateBody { ContainerCreateBody { image: Some(image.to_string()), user: Some(format!("{SUPERVISOR_UID}:{SUPERVISOR_GID}")), entrypoint: Some(vec![SUPERVISOR_IMAGE_CONTROL_BINARY_PATH.to_string()]), - cmd: Some(vec!["--help".to_string()]), + cmd: Some(command), labels: Some(HashMap::from([ ( LABEL_MANAGED_BY.to_string(), @@ -7328,7 +7439,6 @@ fn docker_host_gateway_resolver_body(image: &str, namespace: &str) -> ContainerC ])), host_config: Some(HostConfig { network_mode: Some("none".to_string()), - extra_hosts: Some(vec![format!("{HOST_OPEN_SHELL_INTERNAL}:host-gateway")]), cap_drop: Some(vec!["ALL".to_string()]), security_opt: Some(vec!["no-new-privileges:true".to_string()]), readonly_rootfs: Some(true), @@ -7381,7 +7491,7 @@ async fn resolve_docker_host_gateway( namespace: &str, ) -> CoreResult { let name = format!("{}-host-gateway", temp_extract_container_name()); - let result = tokio::time::timeout(HOST_GATEWAY_RESOLUTION_TIMEOUT, async { + let result = tokio::time::timeout(STAGING_SUPERVISOR_TIMEOUT, async { docker .create_container( Some( @@ -7424,7 +7534,7 @@ async fn resolve_docker_host_gateway( // Remove by the unique name even after a timed-out create request. let cleanup = tokio::time::timeout( - HOST_GATEWAY_CLEANUP_TIMEOUT, + STAGING_SUPERVISOR_CLEANUP_TIMEOUT, docker.remove_container( &name, Some(RemoveContainerOptionsBuilder::default().force(true).build()), @@ -7453,6 +7563,106 @@ async fn resolve_docker_host_gateway( Ok(ip) } +/// Whether this driver offers verified provider workload identity. The mode +/// must be selected, by the gateway or, for a standalone driver, by the socket +/// setting. The driver's supervisors must then qualify for it. +async fn docker_offers_provider_workload_identity( + docker: &Docker, + config: &DockerDriverRuntimeConfig, + gateway_selected: Option, +) -> bool { + let socket_configured = config.provider_spiffe_workload_api_socket.is_some(); + if !gateway_selected.unwrap_or(socket_configured) { + return false; + } + let qualified = match validate_docker_provider_grant_transport(config) { + Ok(()) => probe_docker_provider_workload_identity(docker, config).await, + Err(reason) => Err(reason), + }; + if let Err(reason) = &qualified { + warn!(%reason, "Docker cannot offer verified provider workload identity"); + } + qualified.is_ok() +} + +/// Run the supervisor image's probe with the Workload API socket mounted as a +/// supervisor gets it. An image that predates the mode exits with another status. +async fn probe_docker_provider_workload_identity( + docker: &Docker, + config: &DockerDriverRuntimeConfig, +) -> Result<(), String> { + let socket = config + .provider_spiffe_workload_api_socket + .as_deref() + .ok_or("provider_spiffe_workload_api_socket is not configured")?; + let projected = openshell_core::driver_utils::projected_provider_spiffe_socket_path(socket)?; + let mount = docker_provider_spiffe_socket_mount(socket) + .map_err(|status| status.message().to_string())?; + let mut body = docker_staging_supervisor_body( + &config.supervisor_image_id, + &config.sandbox_namespace, + vec![PROVIDER_WORKLOAD_IDENTITY_PROBE.to_string(), projected], + ); + if let Some(host) = body.host_config.as_mut() { + host.mounts = Some(vec![mount]); + } + let name = format!("{}-provider-identity", temp_extract_container_name()); + let exit = tokio::time::timeout(STAGING_SUPERVISOR_TIMEOUT, async { + let options = CreateContainerOptionsBuilder::default() + .name(name.as_str()) + .build(); + docker.create_container(Some(options), body).await?; + docker.start_container(&name, None).await?; + let mut wait = docker.wait_container( + &name, + None::, + ); + wait.next().await.transpose() + }) + .await; + // Remove by the unique name even after a timed-out create request. + // Startup reconciliation removes a staging container that stays behind. + let _ = tokio::time::timeout( + STAGING_SUPERVISOR_CLEANUP_TIMEOUT, + docker.remove_container( + &name, + Some(RemoveContainerOptionsBuilder::default().force(true).build()), + ), + ) + .await; + let status = match exit { + Ok(Ok(Some(exit))) => exit.status_code, + // Bollard reports a nonzero exit status as an error. + Ok(Err(BollardError::DockerContainerWaitError { code, .. })) => code, + Ok(Ok(None)) => return Err("the supervisor's probe reported no exit status".to_string()), + Ok(Err(error)) => return Err(format!("run the supervisor's probe: {error}")), + Err(_) => return Err("the supervisor's probe timed out".to_string()), + }; + if status == i64::from(PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT) { + Ok(()) + } else if status == i64::from(PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE) { + Err("the supervisor cannot see the configured Workload API Unix socket".to_string()) + } else { + Err(format!( + "supervisor image '{}' did not report verified Workload API socket support (exit {status}); select a matching supervisor image", + config.supervisor_image_id + )) + } +} + +fn docker_provider_spiffe_socket_mount(socket: &Path) -> Result { + let parent = socket.parent().ok_or_else(|| { + Status::failed_precondition("provider SPIFFE socket has no parent directory") + })?; + Ok(Mount { + target: Some(PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR.to_string()), + source: Some(parent.display().to_string()), + typ: Some(MountTypeEnum::BIND), + read_only: Some(true), + ..Default::default() + }) +} + fn docker_supervisor_networking( config: &DockerDriverRuntimeConfig, ) -> Result<(DockerSupervisorNetworkMode, String), Status> { @@ -7485,6 +7695,21 @@ fn docker_supervisor_networking( Ok((mode, endpoint)) } +/// A supervisor sends its workload assertions to the gateway only over HTTPS +/// or plain HTTP to a literal loopback address. +fn validate_docker_provider_grant_transport( + config: &DockerDriverRuntimeConfig, +) -> Result<(), String> { + let (_, endpoint) = + docker_supervisor_networking(config).map_err(|status| status.message().to_string())?; + token_grant_gateway_endpoint(&endpoint) + .and_then(|endpoint| validate_attested_token_grant_transport(&endpoint)) + .map_err(|_| { + "verified provider grants require a supervisor grpc_endpoint with HTTPS or HTTP to a literal loopback address" + .to_string() + }) +} + pub(crate) fn docker_guest_tls_paths( docker_config: &DockerComputeConfig, ) -> CoreResult> { diff --git a/crates/openshell-driver-docker/src/serve.rs b/crates/openshell-driver-docker/src/serve.rs index b2901a007b..90e6a8ceb3 100644 --- a/crates/openshell-driver-docker/src/serve.rs +++ b/crates/openshell-driver-docker/src/serve.rs @@ -157,13 +157,15 @@ async fn apply_configure( let network_trust = openshell_driver_sdk::load_network_trust(request.network_trust.as_ref())?; let admission = openshell_driver_sdk::admission_from_json(&request.resource_admission_policy_json)?; - let (config, bind_address) = driver_config( + let (mut config, bind_address) = driver_config( settings, &gateway, request.image_overrides.as_ref(), supervisor_otlp, &admission, )?; + config.verified_provider_workload_identity = + Some(request.verified_provider_workload_identity == Some(true)); let driver = DockerComputeDriver::new(bind_address, log_level, &config, network_trust) .await .map_err(|error| Status::internal(error.to_string()))?; diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index 4248145235..64711d02b1 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -83,6 +83,26 @@ pub fn test_launch_authentication() -> Vec { .unwrap() } +/// Launch authentication with the provider identities of `sandbox_id`. Its +/// launch SPIFFE ID names `generation`, as the gateway builds it. +pub fn test_verified_launch_authentication( + sandbox_id: &str, + generation: &str, +) -> SandboxLaunchAuthentication { + let mut authentication: SandboxLaunchAuthentication = + serde_json::from_slice(&test_launch_authentication()).unwrap(); + authentication.supervisor.runtime_generation = + openshell_core::sandbox_generation::SandboxGenerationId::parse(generation).unwrap(); + let stable = format!( + "spiffe://example.test/openshell/gateway/{}/sandbox/{sandbox_id}", + authentication.gateway_id + ); + authentication.supervisor.provider_launch_spiffe_id = + Some(format!("{stable}/launch/{generation}")); + authentication.supervisor.provider_spiffe_id = Some(stable); + authentication +} + #[tokio::test] async fn restart_rotates_bootstrap_descriptor_and_provisioning_evidence_together() { let config = runtime_config(); @@ -368,6 +388,7 @@ pub fn runtime_config() -> DockerDriverRuntimeConfig { proxy_ca_bundle: None, ipv6_egress: SupervisorIpv6EgressConfig::default(), provider_spiffe_workload_api_socket: None, + provider_workload_identity: false, app_armor_profile: Some(AppArmorProfile::Unconfined), network_trust: None, } @@ -612,6 +633,136 @@ fn capabilities_report_static_resource_support() { assert!(gpu.count_selection_supported); } +#[tokio::test] +async fn provider_workload_identity_is_offered_only_when_selected_and_qualified() { + use crate::workspace::tests::docker_api; + use serde_json::{Value, json}; + + let loopback = "http://127.0.0.1:8443"; + let remote = "http://host.openshell.internal:8443"; + let present = Some(PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT); + let hidden = Some(PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE); + // (gateway's selection, socket configured, gateway endpoint, probe exit, + // offered). A standalone driver has no selection from a gateway. + for case in [ + (Some(true), true, loopback, present, true), + (Some(false), true, loopback, None, false), + (None, true, loopback, present, true), + (None, false, loopback, None, false), + (Some(true), false, loopback, None, false), + (Some(true), true, remote, None, false), + // An image that predates the probe prints its help and exits 0. + (Some(true), true, loopback, Some(0), false), + (Some(true), true, loopback, hidden, false), + ] { + let (gateway_selected, socket, endpoint, probe_exit, offered) = case; + let mut config = runtime_config(); + config.provider_spiffe_workload_api_socket = + socket.then(|| PathBuf::from("/run/spire/agent.sock")); + config.supervisor_grpc_endpoint = endpoint.to_string(); + // Only a driver that passes the earlier checks runs the probe. + let replies = probe_exit.map_or_else(Vec::new, |exit| { + let created = json!({"Id": "probe", "Warnings": []}); + vec![ + ("POST", String::new(), 201, created), + ("POST", "/start".into(), 204, Value::Null), + ("POST", String::new(), 200, json!({"StatusCode": exit})), + ("DELETE", String::new(), 204, Value::Null), + ] + }); + let (docker, engine) = docker_api(replies).await; + config.provider_workload_identity = + docker_offers_provider_workload_identity(&docker, &config, gateway_selected).await; + assert_eq!(config.provider_workload_identity, offered, "{case:?}"); + if let Some(probe) = engine.await.unwrap().first() { + let socket = "/spiffe-workload-api/agent.sock"; + assert_eq!( + probe["Cmd"], + json!([PROVIDER_WORKLOAD_IDENTITY_PROBE, socket]) + ); + assert_eq!(probe["User"], format!("{SUPERVISOR_UID}:{SUPERVISOR_GID}")); + assert_eq!(probe["HostConfig"]["NetworkMode"], "none"); + let mount = &probe["HostConfig"]["Mounts"][0]; + assert_eq!(mount["Source"], "/run/spire"); + assert_eq!(mount["Target"], "/spiffe-workload-api"); + assert_eq!(mount["ReadOnly"], true); + } + let capabilities = test_driver_with_config(config) + .capabilities() + .extension + .unwrap() + .supported_capabilities; + assert_eq!( + capabilities + .iter() + .any(|capability| capability == COMPUTE_PROVIDER_WORKLOAD_IDENTITY), + offered, + "{case:?}" + ); + } +} + +#[tokio::test] +async fn launch_bundle_identities_must_belong_to_the_sandbox_launch() { + let mut config = runtime_config(); + let own = test_verified_launch_authentication("sbx-123", "generation-1"); + let launch = |config: &DockerDriverRuntimeConfig, + generation: &str, + bundle: &SandboxLaunchAuthentication| { + docker_provider_launch_spiffe_id(config, "sbx-123", generation, bundle) + }; + + // A driver that does not offer the mode runs only bundles without identities. + let plain = decode_docker_launch_authentication(&test_launch_authentication()).unwrap(); + assert_eq!(launch(&config, "generation-1", &plain).unwrap(), None); + assert_eq!( + launch(&config, "generation-1", &own).unwrap_err().code(), + tonic::Code::FailedPrecondition + ); + + config.provider_workload_identity = true; + assert_eq!( + launch(&config, "generation-1", &own).unwrap(), + own.supervisor.provider_launch_spiffe_id + ); + let other_sandbox = test_verified_launch_authentication("sbx-other", "generation-1"); + let mut other_launch = own.clone(); + other_launch.supervisor.provider_launch_spiffe_id = + test_verified_launch_authentication("sbx-123", "generation-2") + .supervisor + .provider_launch_spiffe_id; + let mut one_identity = own.clone(); + one_identity.supervisor.provider_launch_spiffe_id = None; + for (case, generation, bundle) in [ + ("another sandbox", "generation-1", &other_sandbox), + ("another generation", "generation-2", &own), + ("another launch", "generation-1", &other_launch), + ("one identity", "generation-1", &one_identity), + ] { + assert_eq!( + launch(&config, generation, bundle).unwrap_err().code(), + tonic::Code::InvalidArgument, + "{case}" + ); + } + + // Create rejects the bundle before it reserves or provisions anything. + let mut sandbox = test_sandbox(); + sandbox.spec.as_mut().unwrap().launch_authentication = + serde_json::to_vec(&other_sandbox).unwrap(); + let driver = test_driver_with_config(config); + let error = ComputeDriver::create_sandbox( + &driver, + Request::new(CreateSandboxRequest { + sandbox: Some(sandbox), + }), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert!(driver.pending.lock().await.is_empty()); +} + #[tokio::test] async fn capabilities_reject_missing_gateway_metadata() { let driver = test_driver_with_config(runtime_config()); @@ -3938,6 +4089,46 @@ fn build_container_create_body_uses_runtime_namespace_label() { ); } +#[test] +fn only_the_supervisor_carries_the_launch_label_and_only_from_its_bundle() { + let config = runtime_config(); + let launch = "spiffe://example.test/gateway/gw/sandbox/sbx-123/launch/generation-1"; + let mut spoofing = test_sandbox(); + let template = spoofing.spec.as_mut().unwrap().template.as_mut().unwrap(); + template.labels.insert( + LABEL_PROVIDER_LAUNCH_SPIFFE_ID.into(), + "spiffe://caller/launch".into(), + ); + // The supervisor carries these labels and no template label. + let fixed = [ + (LABEL_MANAGED_BY, "openshell"), + (LABEL_SANDBOX_ID, "sbx-123"), + (LABEL_SANDBOX_NAME, "demo"), + (LABEL_SANDBOX_NAMESPACE, "default"), + (LABEL_ISOLATION_ROLE, LABEL_ISOLATION_ROLE_SUPERVISOR), + ]; + + for sandbox in [test_sandbox(), spoofing] { + for bundle_launch in [Some(launch), None] { + let expected = fixed + .into_iter() + .chain(bundle_launch.map(|launch| (LABEL_PROVIDER_LAUNCH_SPIFFE_ID, launch))) + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect::>(); + assert_eq!( + docker_supervisor_labels(&sandbox, &config, bundle_launch), + expected + ); + } + // An empty value keeps a template or image label off the workload. + let workload = build_container_create_body(&sandbox, &config).unwrap(); + assert_eq!( + workload.labels.unwrap()[LABEL_PROVIDER_LAUNCH_SPIFFE_ID], + "" + ); + } +} + #[test] fn driver_status_keeps_running_sandboxes_provisioning_with_stable_message() { let running = ContainerSummary {