@@ -29,7 +29,8 @@ use futures::{Stream, StreamExt};
2929#[cfg(unix)]
3030use hyper_util::rt::TokioIo;
3131use openshell_core::extension_protocol::{
32- ExtensionFamily, NegotiatedExtension, gateway_metadata, negotiate,
32+ COMPUTE_PROVIDER_WORKLOAD_IDENTITY, ExtensionFamily, NegotiatedExtension, gateway_metadata,
33+ has_capability, negotiate,
3334};
3435#[cfg(test)]
3536use openshell_core::proto::ServiceAuthorizationMode;
@@ -1325,6 +1326,7 @@ pub struct ComputeRuntime {
13251326 image_preparation_timeout_seconds: u32,
13261327 provisioning_repair_window_ms: i64,
13271328 sandbox_updates_enabled: bool,
1329+ provider_workload_identity: Option<crate::spiffe_broker::SupervisorWorkloadIdentity>,
13281330 update_recovery_sweep: Arc<tokio::sync::Semaphore>,
13291331 update_recovery_backoff: Arc<Mutex<HashMap<String, image_update::UpdateRecoveryBackoff>>>,
13301332 store: Arc<Store>,
@@ -1448,6 +1450,7 @@ impl ComputeRuntime {
14481450 image_preparation_timeout_seconds: 1800,
14491451 provisioning_repair_window_ms: 300_000,
14501452 sandbox_updates_enabled: false,
1453+ provider_workload_identity: None,
14511454 update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)),
14521455 update_recovery_backoff: Arc::default(),
14531456 store,
@@ -1487,6 +1490,40 @@ impl ComputeRuntime {
14871490 self.supervisor_host.as_ref()
14881491 }
14891492
1493+ /// Give every launch bundle the sandbox's stable and launch SPIFFE IDs.
1494+ ///
1495+ /// # Errors
1496+ ///
1497+ /// The mode needs dedicated supervisors and a driver that advertises
1498+ /// [`COMPUTE_PROVIDER_WORKLOAD_IDENTITY`].
1499+ pub(crate) fn with_provider_workload_identity(
1500+ mut self,
1501+ identity: Option<crate::spiffe_broker::SupervisorWorkloadIdentity>,
1502+ ) -> Result<Self, String> {
1503+ if identity.is_some() {
1504+ if self.supervisor_host.is_some() {
1505+ return Err("spiffe_workload_identity requires dedicated supervisors".into());
1506+ }
1507+ if !has_capability(
1508+ &self.driver_info.negotiated_extension.supported_capabilities,
1509+ COMPUTE_PROVIDER_WORKLOAD_IDENTITY,
1510+ ) {
1511+ return Err(format!(
1512+ "compute driver '{}' did not advertise {COMPUTE_PROVIDER_WORKLOAD_IDENTITY}, required by spiffe_workload_identity; check the running driver's version and Workload API configuration",
1513+ self.driver_info.name,
1514+ ));
1515+ }
1516+ }
1517+ self.provider_workload_identity = identity;
1518+ Ok(self)
1519+ }
1520+
1521+ pub(crate) fn provider_workload_identity(
1522+ &self,
1523+ ) -> Option<&crate::spiffe_broker::SupervisorWorkloadIdentity> {
1524+ self.provider_workload_identity.as_ref()
1525+ }
1526+
14901527 pub(crate) fn configure_ssh_identities(
14911528 &self,
14921529 credentials: crate::credentials::CredentialRuntime,
@@ -1522,11 +1559,32 @@ impl ComputeRuntime {
15221559 let _ = self.supervisor_otlp_tls.set(tls);
15231560 }
15241561
1525- pub(crate) async fn prepare_ssh_identity(
1562+ /// Add the identities a launch bundle carries besides its session tokens.
1563+ pub(crate) async fn prepare_launch_identity(
15261564 &self,
15271565 sandbox: &mut Sandbox,
15281566 authentication: &mut openshell_core::jwt::SandboxLaunchAuthentication,
15291567 ) -> Result<(), Status> {
1568+ if let Some(identity) = self.provider_workload_identity() {
1569+ // A launch is the runtime generation the bundle was minted for.
1570+ let spiffe_id = identity
1571+ .sandbox_spiffe_id(sandbox.object_id())
1572+ .map_err(Status::failed_precondition)?;
1573+ let launch_spiffe_id = identity
1574+ .launch_spiffe_id(
1575+ sandbox.object_id(),
1576+ &authentication.supervisor.runtime_generation,
1577+ )
1578+ .map_err(Status::failed_precondition)?;
1579+ info!(
1580+ sandbox_id = sandbox.object_id(),
1581+ %spiffe_id,
1582+ %launch_spiffe_id,
1583+ "Configured sandbox SPIFFE identity for provider grants"
1584+ );
1585+ authentication.supervisor.provider_spiffe_id = Some(spiffe_id);
1586+ authentication.supervisor.provider_launch_spiffe_id = Some(launch_spiffe_id);
1587+ }
15301588 if let Some(identities) = self.ssh_identities.get() {
15311589 identities.prepare(sandbox, authentication).await?;
15321590 }
@@ -1546,7 +1604,7 @@ impl ComputeRuntime {
15461604 mut authentication: openshell_core::jwt::SandboxLaunchAuthentication,
15471605 ) -> Result<Vec<u8>, Status> {
15481606 let mut with_identity = sandbox.clone();
1549- self.prepare_ssh_identity (&mut with_identity, &mut authentication)
1607+ self.prepare_launch_identity (&mut with_identity, &mut authentication)
15501608 .await?;
15511609 if let Some(headers) = self.supervisor_otlp_headers.get() {
15521610 headers.apply(&mut authentication.supervisor);
@@ -9238,6 +9296,7 @@ pub fn new_test_runtime_with_driver(
92389296 image_preparation_timeout_seconds: 1800,
92399297 provisioning_repair_window_ms: 300_000,
92409298 sandbox_updates_enabled: false,
9299+ provider_workload_identity: None,
92419300 update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)),
92429301 update_recovery_backoff: Arc::default(),
92439302 store,
@@ -10582,6 +10641,7 @@ mod tests {
1058210641 image_preparation_timeout_seconds: 1800,
1058310642 provisioning_repair_window_ms: 300_000,
1058410643 sandbox_updates_enabled: false,
10644+ provider_workload_identity: None,
1058510645 update_recovery_sweep: Arc::new(Semaphore::new(1)),
1058610646 update_recovery_backoff: Arc::default(),
1058710647 store,
@@ -14384,6 +14444,126 @@ mod tests {
1438414444 }
1438514445 }
1438614446
14447+ fn test_provider_workload_identity() -> crate::spiffe_broker::SupervisorWorkloadIdentity {
14448+ crate::spiffe_broker::SupervisorWorkloadIdentity::from_settings(
14449+ Some(&openshell_core::config::SpiffeWorkloadIdentityConfig {
14450+ spiffe_id_prefix: "spiffe://test.example/openshell".into(),
14451+ workload_api_socket_path: "/run/spire/agent.sock".into(),
14452+ }),
14453+ Some(&openshell_core::config::GatewayJwtConfig {
14454+ // The gateway ID of `test_session_authority`.
14455+ gateway_id: "test-gateway".into(),
14456+ ttl_secs: std::num::NonZeroU64::new(300),
14457+ signing_key_path: PathBuf::default(),
14458+ public_key_path: PathBuf::default(),
14459+ kid_path: PathBuf::default(),
14460+ }),
14461+ false,
14462+ )
14463+ .unwrap()
14464+ .unwrap()
14465+ }
14466+
14467+ #[tokio::test]
14468+ async fn provider_workload_identity_requires_the_driver_capability() {
14469+ let identity = test_provider_workload_identity();
14470+ let runtime = test_runtime(ControlledDriver::new()).await;
14471+
14472+ let error = runtime
14473+ .clone()
14474+ .with_provider_workload_identity(Some(identity.clone()))
14475+ .unwrap_err();
14476+ assert!(
14477+ error.contains(&format!(
14478+ "did not advertise {COMPUTE_PROVIDER_WORKLOAD_IDENTITY}"
14479+ )),
14480+ "{error}"
14481+ );
14482+ // The capability is required only when the mode is configured.
14483+ let unselected = runtime
14484+ .clone()
14485+ .with_provider_workload_identity(None)
14486+ .unwrap();
14487+ assert!(unselected.provider_workload_identity().is_none());
14488+
14489+ let mut capable = runtime;
14490+ capable
14491+ .driver_info
14492+ .negotiated_extension
14493+ .supported_capabilities
14494+ .push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.to_string());
14495+ let selected = capable
14496+ .with_provider_workload_identity(Some(identity))
14497+ .unwrap();
14498+ assert!(selected.provider_workload_identity().is_some());
14499+ }
14500+
14501+ /// A bundle's launch ID is the stable ID plus the persisted generation, so
14502+ /// a retried start names the same launch and a new start a new one.
14503+ #[tokio::test]
14504+ async fn start_bundles_name_the_launch_of_the_persisted_generation() {
14505+ let driver = ControlledDriver::new();
14506+ let mut runtime = test_runtime(driver.clone()).await;
14507+ let identity = test_provider_workload_identity();
14508+ runtime.provider_workload_identity = Some(identity.clone());
14509+ let sandbox = sandbox_record("sb-launch", "sandbox-launch", SandboxPhase::Stopped);
14510+ runtime.store.put_message(&sandbox).await.unwrap();
14511+ let authority = test_session_authority();
14512+ let stable = identity.sandbox_spiffe_id(sandbox.object_id()).unwrap();
14513+
14514+ let mut launches = Vec::new();
14515+ // A start, its retry while `Starting`, and a start after a stop.
14516+ for stop_first in [false, false, true] {
14517+ if stop_first {
14518+ runtime
14519+ .store
14520+ .update_message_cas::<Sandbox, _>(sandbox.object_id(), 0, |sandbox| {
14521+ sandbox.set_phase(SandboxPhase::Stopped as i32);
14522+ })
14523+ .await
14524+ .unwrap();
14525+ }
14526+ runtime
14527+ .start_sandbox_authenticated(
14528+ sandbox.object_workspace(),
14529+ sandbox.object_name(),
14530+ Some(&authority),
14531+ )
14532+ .await
14533+ .unwrap();
14534+ let stored = runtime
14535+ .store
14536+ .get_message::<Sandbox>(sandbox.object_id())
14537+ .await
14538+ .unwrap()
14539+ .unwrap();
14540+ let generation = sandbox_runtime_generation(&stored).unwrap();
14541+ let encoded = driver.start_authentications().pop().unwrap();
14542+ let authentication: openshell_core::jwt::SandboxLaunchAuthentication =
14543+ serde_json::from_slice(&encoded).unwrap();
14544+ let supervisor = &authentication.supervisor;
14545+ assert_eq!(supervisor.provider_spiffe_id.as_ref(), Some(&stable));
14546+ assert_eq!(
14547+ supervisor.provider_launch_spiffe_id,
14548+ Some(format!("{stable}/launch/{}", generation.as_str()))
14549+ );
14550+ // A driver accepts the bundle for this sandbox and generation only.
14551+ let validate = |sandbox_id, generation_id| {
14552+ openshell_core::driver_utils::validate_provider_launch_identity(
14553+ sandbox_id,
14554+ generation_id,
14555+ &authentication,
14556+ )
14557+ };
14558+ validate(sandbox.object_id(), generation.as_str()).unwrap();
14559+ validate("another-sandbox", generation.as_str()).unwrap_err();
14560+ validate(sandbox.object_id(), "another-generation").unwrap_err();
14561+ launches.push(supervisor.provider_launch_spiffe_id.clone());
14562+ }
14563+ assert_eq!(launches[0], launches[1]);
14564+ assert_ne!(launches[1], launches[2]);
14565+ }
14566+
1438714567 #[tokio::test]
1438814568 async fn concurrent_authenticated_start_keeps_the_claimed_launch_identity() {
1438914569 let driver = ControlledDriver::new();
0 commit comments