diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 2d3f37c7eb..466c683f44 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -335,6 +335,14 @@ impl SpiffeBrokerConfig { } } +/// Validate provider assertions from dedicated, platform-attested supervisors. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SpiffeWorkloadIdentityConfig { + pub spiffe_id_prefix: String, + pub workload_api_socket_path: PathBuf, +} + /// Server configuration. /// /// Built programmatically in [`crate::Config::new`] and the gateway CLI from @@ -419,6 +427,7 @@ pub struct Config { pub gateway_jwt: Option, /// Gateway-only access to SPIRE; shared supervisors receive access tokens. pub spiffe_broker: Option, + pub spiffe_workload_identity: Option, /// Database URL for persistence. pub database_url: String, @@ -1340,6 +1349,7 @@ impl Config { audit: GatewayAuditConfig::default(), gateway_jwt: None, spiffe_broker: None, + spiffe_workload_identity: None, database_url: String::new(), database_auth: DatabaseAuthMode::default(), database_max_connections: None, diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index fb835b43a3..a09ca1cef9 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -29,7 +29,8 @@ use futures::{Stream, StreamExt}; #[cfg(unix)] use hyper_util::rt::TokioIo; use openshell_core::extension_protocol::{ - ExtensionFamily, NegotiatedExtension, gateway_metadata, negotiate, + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, ExtensionFamily, NegotiatedExtension, gateway_metadata, + has_capability, negotiate, }; #[cfg(test)] use openshell_core::proto::ServiceAuthorizationMode; @@ -1325,6 +1326,7 @@ pub struct ComputeRuntime { image_preparation_timeout_seconds: u32, provisioning_repair_window_ms: i64, sandbox_updates_enabled: bool, + provider_workload_identity: Option, update_recovery_sweep: Arc, update_recovery_backoff: Arc>>, store: Arc, @@ -1448,6 +1450,7 @@ impl ComputeRuntime { image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + provider_workload_identity: None, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, @@ -1487,6 +1490,40 @@ impl ComputeRuntime { self.supervisor_host.as_ref() } + /// Give every launch bundle the sandbox's stable and launch SPIFFE IDs. + /// + /// # Errors + /// + /// The mode needs dedicated supervisors and a driver that advertises + /// [`COMPUTE_PROVIDER_WORKLOAD_IDENTITY`]. + pub(crate) fn with_provider_workload_identity( + mut self, + identity: Option, + ) -> Result { + if identity.is_some() { + if self.supervisor_host.is_some() { + return Err("spiffe_workload_identity requires dedicated supervisors".into()); + } + if !has_capability( + &self.driver_info.negotiated_extension.supported_capabilities, + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, + ) { + return Err(format!( + "compute driver '{}' did not advertise {COMPUTE_PROVIDER_WORKLOAD_IDENTITY}, required by spiffe_workload_identity; check the running driver's version and Workload API configuration", + self.driver_info.name, + )); + } + } + self.provider_workload_identity = identity; + Ok(self) + } + + pub(crate) fn provider_workload_identity( + &self, + ) -> Option<&crate::spiffe_broker::SupervisorWorkloadIdentity> { + self.provider_workload_identity.as_ref() + } + pub(crate) fn configure_ssh_identities( &self, credentials: crate::credentials::CredentialRuntime, @@ -1522,11 +1559,32 @@ impl ComputeRuntime { let _ = self.supervisor_otlp_tls.set(tls); } - pub(crate) async fn prepare_ssh_identity( + /// Add the identities a launch bundle carries besides its session tokens. + pub(crate) async fn prepare_launch_identity( &self, sandbox: &mut Sandbox, authentication: &mut openshell_core::jwt::SandboxLaunchAuthentication, ) -> Result<(), Status> { + if let Some(identity) = self.provider_workload_identity() { + // A launch is the runtime generation the bundle was minted for. + let spiffe_id = identity + .sandbox_spiffe_id(sandbox.object_id()) + .map_err(Status::failed_precondition)?; + let launch_spiffe_id = identity + .launch_spiffe_id( + sandbox.object_id(), + &authentication.supervisor.runtime_generation, + ) + .map_err(Status::failed_precondition)?; + info!( + sandbox_id = sandbox.object_id(), + %spiffe_id, + %launch_spiffe_id, + "Configured sandbox SPIFFE identity for provider grants" + ); + authentication.supervisor.provider_spiffe_id = Some(spiffe_id); + authentication.supervisor.provider_launch_spiffe_id = Some(launch_spiffe_id); + } if let Some(identities) = self.ssh_identities.get() { identities.prepare(sandbox, authentication).await?; } @@ -1546,7 +1604,7 @@ impl ComputeRuntime { mut authentication: openshell_core::jwt::SandboxLaunchAuthentication, ) -> Result, Status> { let mut with_identity = sandbox.clone(); - self.prepare_ssh_identity(&mut with_identity, &mut authentication) + self.prepare_launch_identity(&mut with_identity, &mut authentication) .await?; if let Some(headers) = self.supervisor_otlp_headers.get() { headers.apply(&mut authentication.supervisor); @@ -9238,6 +9296,7 @@ pub fn new_test_runtime_with_driver( image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + provider_workload_identity: None, update_recovery_sweep: Arc::new(tokio::sync::Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, @@ -10582,6 +10641,7 @@ mod tests { image_preparation_timeout_seconds: 1800, provisioning_repair_window_ms: 300_000, sandbox_updates_enabled: false, + provider_workload_identity: None, update_recovery_sweep: Arc::new(Semaphore::new(1)), update_recovery_backoff: Arc::default(), store, @@ -14384,6 +14444,126 @@ mod tests { } } + fn test_provider_workload_identity() -> crate::spiffe_broker::SupervisorWorkloadIdentity { + crate::spiffe_broker::SupervisorWorkloadIdentity::from_settings( + Some(&openshell_core::config::SpiffeWorkloadIdentityConfig { + spiffe_id_prefix: "spiffe://test.example/openshell".into(), + workload_api_socket_path: "/run/spire/agent.sock".into(), + }), + Some(&openshell_core::config::GatewayJwtConfig { + // The gateway ID of `test_session_authority`. + gateway_id: "test-gateway".into(), + ttl_secs: std::num::NonZeroU64::new(300), + signing_key_path: PathBuf::default(), + public_key_path: PathBuf::default(), + kid_path: PathBuf::default(), + }), + false, + ) + .unwrap() + .unwrap() + } + + #[tokio::test] + async fn provider_workload_identity_requires_the_driver_capability() { + let identity = test_provider_workload_identity(); + let runtime = test_runtime(ControlledDriver::new()).await; + + let error = runtime + .clone() + .with_provider_workload_identity(Some(identity.clone())) + .unwrap_err(); + assert!( + error.contains(&format!( + "did not advertise {COMPUTE_PROVIDER_WORKLOAD_IDENTITY}" + )), + "{error}" + ); + // The capability is required only when the mode is configured. + let unselected = runtime + .clone() + .with_provider_workload_identity(None) + .unwrap(); + assert!(unselected.provider_workload_identity().is_none()); + + let mut capable = runtime; + capable + .driver_info + .negotiated_extension + .supported_capabilities + .push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.to_string()); + let selected = capable + .with_provider_workload_identity(Some(identity)) + .unwrap(); + assert!(selected.provider_workload_identity().is_some()); + } + + /// A bundle's launch ID is the stable ID plus the persisted generation, so + /// a retried start names the same launch and a new start a new one. + #[tokio::test] + async fn start_bundles_name_the_launch_of_the_persisted_generation() { + let driver = ControlledDriver::new(); + let mut runtime = test_runtime(driver.clone()).await; + let identity = test_provider_workload_identity(); + runtime.provider_workload_identity = Some(identity.clone()); + let sandbox = sandbox_record("sb-launch", "sandbox-launch", SandboxPhase::Stopped); + runtime.store.put_message(&sandbox).await.unwrap(); + let authority = test_session_authority(); + let stable = identity.sandbox_spiffe_id(sandbox.object_id()).unwrap(); + + let mut launches = Vec::new(); + // A start, its retry while `Starting`, and a start after a stop. + for stop_first in [false, false, true] { + if stop_first { + runtime + .store + .update_message_cas::(sandbox.object_id(), 0, |sandbox| { + sandbox.set_phase(SandboxPhase::Stopped as i32); + }) + .await + .unwrap(); + } + runtime + .start_sandbox_authenticated( + sandbox.object_workspace(), + sandbox.object_name(), + Some(&authority), + ) + .await + .unwrap(); + let stored = runtime + .store + .get_message::(sandbox.object_id()) + .await + .unwrap() + .unwrap(); + let generation = sandbox_runtime_generation(&stored).unwrap(); + let encoded = driver.start_authentications().pop().unwrap(); + let authentication: openshell_core::jwt::SandboxLaunchAuthentication = + serde_json::from_slice(&encoded).unwrap(); + let supervisor = &authentication.supervisor; + assert_eq!(supervisor.provider_spiffe_id.as_ref(), Some(&stable)); + assert_eq!( + supervisor.provider_launch_spiffe_id, + Some(format!("{stable}/launch/{}", generation.as_str())) + ); + // A driver accepts the bundle for this sandbox and generation only. + let validate = |sandbox_id, generation_id| { + openshell_core::driver_utils::validate_provider_launch_identity( + sandbox_id, + generation_id, + &authentication, + ) + }; + validate(sandbox.object_id(), generation.as_str()).unwrap(); + validate("another-sandbox", generation.as_str()).unwrap_err(); + validate(sandbox.object_id(), "another-generation").unwrap_err(); + launches.push(supervisor.provider_launch_spiffe_id.clone()); + } + assert_eq!(launches[0], launches[1]); + assert_ne!(launches[1], launches[2]); + } + #[tokio::test] async fn concurrent_authenticated_start_keeps_the_claimed_launch_identity() { let driver = ControlledDriver::new(); diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..faf3f136ef 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -2123,7 +2123,7 @@ pub async fn mint_persisted_authentication( let mut with_identity = sandbox.clone(); state .compute - .prepare_ssh_identity(&mut with_identity, &mut authentication) + .prepare_launch_identity(&mut with_identity, &mut authentication) .await?; Ok(authentication) } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index fe12441f89..aa834113b2 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -663,7 +663,12 @@ impl ServerState { let sandbox_identity = spiffe_broker::sandbox_identity_provider(&config).map_err(Error::config)?; let replica_id = compute::lease::replica_id(); - let compute = compute.with_sandbox_updates(config.enable_sandbox_updates); + let workload_identity = spiffe_broker::SupervisorWorkloadIdentity::from_config(&config) + .map_err(Error::config)?; + let compute = compute + .with_sandbox_updates(config.enable_sandbox_updates) + .with_provider_workload_identity(workload_identity) + .map_err(Error::config)?; compute.configure_ssh_identities(credentials.clone()); let service_route_index = Arc::new(service_routing::ServiceRouteIndex::new( config.service_routing_discriminator().map(str::to_string), diff --git a/crates/openshell-server/src/spiffe_broker.rs b/crates/openshell-server/src/spiffe_broker.rs index 886b2b4902..5498b6f2c1 100644 --- a/crates/openshell-server/src/spiffe_broker.rs +++ b/crates/openshell-server/src/spiffe_broker.rs @@ -8,9 +8,12 @@ //! `[openshell.gateway.spiffe_broker]` is configured. use std::sync::Arc; -use openshell_core::config::{Config, SpiffeBrokerConfig}; +use openshell_core::config::{ + Config, GatewayJwtConfig, SpiffeBrokerConfig, SpiffeWorkloadIdentityConfig, +}; +use openshell_core::sandbox_generation::SandboxGenerationId; use openshell_core::token_grant_failure::TokenGrantFailure; -use openshell_spiffe::SandboxIdentityProvider; +use openshell_spiffe::{SandboxIdentityProvider, SandboxSpiffeIdPrefix}; /// Check the broker settings `config` enables without building them. /// @@ -19,9 +22,76 @@ use openshell_spiffe::SandboxIdentityProvider; /// Rejects broker without gateway session JWTs and a positive session /// TTL, and settings [`SpiffeBrokerConfig::validate`] rejects. pub fn validate_config(config: &Config) -> Result<(), String> { + SupervisorWorkloadIdentity::from_config(config)?; enabled(config).map(drop) } +/// Trusted identity settings shared by launch provisioning and the provider broker. +#[derive(Clone)] +pub struct SupervisorWorkloadIdentity { + prefix: SandboxSpiffeIdPrefix, + gateway_id: String, +} + +impl SupervisorWorkloadIdentity { + pub(crate) fn from_config(config: &Config) -> Result, String> { + Self::from_settings( + config.spiffe_workload_identity.as_ref(), + config.gateway_jwt.as_ref(), + config.spiffe_broker.is_some(), + ) + } + + pub(crate) fn from_settings( + workload: Option<&SpiffeWorkloadIdentityConfig>, + jwt: Option<&GatewayJwtConfig>, + broker_enabled: bool, + ) -> Result, String> { + let Some(workload) = workload else { + return Ok(None); + }; + if broker_enabled { + return Err("configure either spiffe_workload_identity or spiffe_broker".into()); + } + let jwt = jwt + .filter(|jwt| jwt.ttl_secs.is_some()) + .ok_or("spiffe_workload_identity requires a positive gateway_jwt.ttl_secs")?; + let prefix = SandboxSpiffeIdPrefix::parse(&workload.spiffe_id_prefix).map_err(|_| { + "spiffe_workload_identity.spiffe_id_prefix must be a SPIFFE ID prefix with a lowercase trust domain and optional path segments" + })?; + // The longest launch SPIFFE ID must fit: a UUID sandbox ID and a + // runtime generation of the maximum length. + let sandbox_id = uuid::Uuid::nil().to_string(); + let generation = "0".repeat(SandboxGenerationId::MAX_LEN); + prefix + .supervisor_launch_spiffe_id(&jwt.gateway_id, &sandbox_id, &generation) + .map_err(|reason| format!("spiffe_workload_identity launch SPIFFE ID: {reason}"))?; + openshell_core::driver_utils::validate_provider_spiffe_unix_socket( + &workload.workload_api_socket_path, + ) + .map_err(|reason| format!("spiffe_workload_identity.workload_api_socket_path: {reason}"))?; + Ok(Some(Self { + prefix, + gateway_id: jwt.gateway_id.clone(), + })) + } + + pub(crate) fn sandbox_spiffe_id(&self, sandbox_id: &str) -> Result { + self.prefix.sandbox_spiffe_id(&self.gateway_id, sandbox_id) + } + + /// The SPIFFE ID of the supervisor launched for `generation`: the stable + /// ID followed by `/launch/`. + pub(crate) fn launch_spiffe_id( + &self, + sandbox_id: &str, + generation: &SandboxGenerationId, + ) -> Result { + self.prefix + .supervisor_launch_spiffe_id(&self.gateway_id, sandbox_id, generation.as_str()) + } +} + /// The sandbox identity provider `config` enables, if any. /// /// # Errors