From 38db4c922d3f28c352a1ac42cbe8ca5c5769db65 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:42:59 +0530 Subject: [PATCH] feat(gateway): configure provider workload identity Add the gateway setting that turns on per-sandbox SPIFFE provider grants for dedicated supervisors, and document the mode. - [openshell.gateway.spiffe_workload_identity] sets the SPIFFE ID prefix and the gateway's Workload API socket. It needs a positive gateway_jwt.ttl_secs and excludes spiffe_broker. - Preflight and startup require an explicit compute driver, reject the Kubernetes driver, and check the selected Docker, Podman, or VM table for a Workload API Unix socket and a supervisor endpoint that uses HTTPS or numeric loopback. A socket value that is set but invalid is reported with the rule it broke. Diagnostics carry no configuration values. - The gateway tells managed Docker, Podman, and VM drivers that the mode is selected through one Configure field. - The docs cover issuer registration for both identities, the evidence each runtime gives an attestor, turning the mode on and off, what an extension driver must implement, and a two-sandbox verification procedure. Signed-off-by: Shiju --- crates/openshell-gateway/src/launcher.rs | 15 +- .../openshell-gateway/src/launcher/tests.rs | 5 + crates/openshell-gateway/src/lib.rs | 9 +- crates/openshell-server/src/cli.rs | 340 +++++++++++++++++- crates/openshell-server/src/config_file.rs | 23 +- crates/openshell-server/src/lib.rs | 38 ++ docs/how-it-works/gateways/configuration.mdx | 196 +++++++++- docs/how-it-works/providers/profiles.mdx | 18 +- .../podman/README.md | 5 +- 9 files changed, 625 insertions(+), 24 deletions(-) diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs index 1b5d09edd1..74e5625024 100644 --- a/crates/openshell-gateway/src/launcher.rs +++ b/crates/openshell-gateway/src/launcher.rs @@ -765,6 +765,7 @@ pub struct ConfigureInputs<'a> { pub admission: Option<&'a openshell_core::resource_admission::DriverAdmissionConfig>, pub sandbox_runtime_image: Option, pub supervisor_image: Option, + verified_provider_workload_identity: Option, /// How long the driver has to answer `Configure`. pub configure_timeout: Duration, } @@ -790,6 +791,7 @@ impl<'a> ConfigureInputs<'a> { sandbox_runtime_image: std::env::var(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV) .ok(), supervisor_image: std::env::var(openshell_core::config::SUPERVISOR_IMAGE_ENV).ok(), + verified_provider_workload_identity: None, configure_timeout: DEFAULT_CONFIGURE_TIMEOUT, } } @@ -802,6 +804,17 @@ impl<'a> ConfigureInputs<'a> { self } + #[cfg(any( + feature = "compute-driver-docker", + feature = "compute-driver-podman", + feature = "compute-driver-vm" + ))] + #[must_use] + pub fn with_verified_provider_workload_identity(mut self, enabled: bool) -> Self { + self.verified_provider_workload_identity = Some(enabled); + self + } + /// The `Configure` call for these inputs: the request and its deadline. #[must_use] pub fn configure_call(&self) -> ConfigureCall { @@ -872,7 +885,7 @@ impl<'a> ConfigureInputs<'a> { .admission .and_then(|policy| serde_json::to_string(policy).ok()) .unwrap_or_default(), - verified_provider_workload_identity: None, + verified_provider_workload_identity: self.verified_provider_workload_identity, } } } diff --git a/crates/openshell-gateway/src/launcher/tests.rs b/crates/openshell-gateway/src/launcher/tests.rs index c29a6ac1f8..424ca107e6 100644 --- a/crates/openshell-gateway/src/launcher/tests.rs +++ b/crates/openshell-gateway/src/launcher/tests.rs @@ -598,12 +598,15 @@ fn configure_carries_the_gateway_metadata_the_argv_used_to() { admission: Some(&admission), sandbox_runtime_image: Some("runtime:1".to_string()), supervisor_image: None, + verified_provider_workload_identity: Some(true), configure_timeout: DEFAULT_CONFIGURE_TIMEOUT, }; let request = inputs.request(); assert_eq!(request.protocol_version, PROTOCOL_VERSION); + assert_eq!(request.verified_provider_workload_identity, Some(true)); + assert!(request.required_features.is_empty()); let gateway = request.gateway.unwrap(); assert_eq!(gateway.gateway_port, 8080); assert_eq!(gateway.bind_address, "127.0.0.1:8080"); @@ -645,6 +648,7 @@ fn configure_omits_what_the_gateway_does_not_have() { admission: None, sandbox_runtime_image: None, supervisor_image: None, + verified_provider_workload_identity: None, configure_timeout: DEFAULT_CONFIGURE_TIMEOUT, }; @@ -654,6 +658,7 @@ fn configure_omits_what_the_gateway_does_not_have() { assert!(request.network_trust.is_none()); assert!(request.telemetry.is_none()); assert!(request.resource_admission_policy_json.is_empty()); + assert_eq!(request.verified_provider_workload_identity, None); } #[tokio::test] diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index de45db23ad..389362dc7b 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -423,7 +423,8 @@ impl openshell_server::ComputeDriverFactory for DockerFactory { context.otlp_config(), Some(&admission), ) - .with_configure_timeout(context.image_preparation_timeout()); + .with_configure_timeout(context.image_preparation_timeout()) + .with_verified_provider_workload_identity(context.requires_provider_workload_identity()); // Auto-detection already started the driver; configure that process. let detected = context.take_detected_driver::(); let endpoint = docker::DOCKER @@ -488,7 +489,8 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory { context.otlp_config(), Some(&admission), ) - .with_configure_timeout(context.image_preparation_timeout()); + .with_configure_timeout(context.image_preparation_timeout()) + .with_verified_provider_workload_identity(context.requires_provider_workload_identity()); let endpoint = podman::PODMAN .spawn( &plan, @@ -559,7 +561,8 @@ impl openshell_server::ComputeDriverFactory for VmFactory { context.otlp_config(), Some(&admission), ) - .with_configure_timeout(context.image_preparation_timeout()); + .with_configure_timeout(context.image_preparation_timeout()) + .with_verified_provider_workload_identity(context.requires_provider_workload_identity()); let endpoint = vm::spawn(&plan, context.gateway_log_level(), &inputs).await?; Ok(openshell_server::ComputeDriverInstance::ManagedRemote( endpoint, diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 3e5a736cf7..e58c7bba13 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -472,6 +472,9 @@ fn prepare_server_config_with_drivers( } let legacy_compute_driver_env_seen = resolve_legacy_driver_selector_env(args)?; normalize_compute_driver_socket_args(args)?; + if let Some(file) = file.as_ref() { + validate_provider_workload_identity_selection(file, args)?; + } let compute_driver = compute_drivers .select_with_file( args.compute_driver.as_deref(), @@ -480,6 +483,12 @@ fn prepare_server_config_with_drivers( ) .map_err(|error| miette::miette!("{error}"))?; if let Some(file) = file.as_mut() { + validate_provider_workload_identity_driver( + file, + compute_drivers, + compute_driver.name(), + args, + )?; config_file::normalize_legacy_podman_ca_bundle(file, compute_driver.name()) .map_err(|error| miette::miette!("{error}"))?; } @@ -836,6 +845,9 @@ fn prepare_server_config_with_drivers( config.spiffe_broker = file .as_ref() .and_then(|file| file.openshell.gateway.spiffe_broker.clone()); + config.spiffe_workload_identity = file + .as_ref() + .and_then(|file| file.openshell.gateway.spiffe_workload_identity.clone()); if let Some(kubernetes) = file .as_ref() @@ -1287,6 +1299,12 @@ fn run_effective_config_preflight( let mut selected_driver = None; if let Some(selection) = selection.as_ref() { validate_preflight_isolation_backend(semantic_file, selection.name())?; + validate_provider_workload_identity_driver( + semantic_file, + compute_drivers, + selection.name(), + &run, + )?; let driver = crate::validate_compute_driver_config( compute_drivers, selection.name(), @@ -1358,10 +1376,20 @@ fn run_effective_config_preflight( } Ok(driver) } - (Err(_), Some(path)) => Err(miette::miette!( - "{}", - config_file::ConfigPreflightError::invalid_current(path) - )), + (Err(error), Some(path)) => { + let error = error + .downcast_ref::() + .map_or_else( + || config_file::ConfigPreflightError::invalid_current(path), + |error| { + config_file::ConfigPreflightError::invalid_provider_workload_identity( + path, + error.0.clone(), + ) + }, + ); + Err(miette::miette!("{error}")) + } (Err(error), None) => Err(error), } } @@ -1432,12 +1460,129 @@ fn validate_preflight_isolation_backend(file: &ConfigFile, driver_name: &str) -> Ok(()) } +// These diagnostics may reach package logs. Build them from fixed text and +// first-party driver names only, with no configuration values attached. +#[derive(Debug, thiserror::Error, miette::Diagnostic)] +#[error("{0}")] +struct ProviderWorkloadIdentityConfigError(String); + +fn validate_provider_workload_identity_selection(file: &ConfigFile, args: &RunArgs) -> Result<()> { + if file.openshell.gateway.spiffe_workload_identity.is_some() && args.compute_driver.is_none() { + return Err(ProviderWorkloadIdentityConfigError( + "spiffe_workload_identity requires an explicit compute driver; set openshell.gateway.compute_driver, OPENSHELL_COMPUTE_DRIVER, or --compute-driver".into(), + ) + .into()); + } + Ok(()) +} + +fn validate_provider_workload_identity_driver( + file: &ConfigFile, + registry: &ComputeDriverRegistry, + name: &str, + args: &RunArgs, +) -> Result<()> { + if file.openshell.gateway.spiffe_workload_identity.is_none() + || args.compute_driver_socket.is_some() + || registry.get(name).is_none() + { + return Ok(()); + } + + if name == "kubernetes" { + return Err(ProviderWorkloadIdentityConfigError( + "the Kubernetes compute driver does not support spiffe_workload_identity".into(), + ) + .into()); + } + if !matches!(name, "docker" | "podman" | "vm") { + return Ok(()); + } + + let table = file.openshell.drivers.get(name); + let get = |key: &str| { + table + .and_then(|table| table.get(key)) + .and_then(toml::Value::as_str) + }; + let socket = match get("provider_spiffe_workload_api_socket") { + Some(socket) => Some(PathBuf::from(socket)), + None if name == "vm" => std::env::var("OPENSHELL_VM_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET") + .ok() + .map(PathBuf::from), + None => None, + }; + // The validator's reasons are fixed text with no configuration values. + let reason = match socket + .as_deref() + .map(openshell_core::driver_utils::validate_provider_spiffe_unix_socket) + { + Some(Ok(())) => None, + Some(Err(reason)) => Some(format!(": {reason}")), + None => Some(String::new()), + }; + if let Some(reason) = reason { + return Err(ProviderWorkloadIdentityConfigError(format!( + "spiffe_workload_identity requires a Workload API Unix socket in [openshell.drivers.{name}].provider_spiffe_workload_api_socket{reason}" + )) + .into()); + } + + let endpoint = get("grpc_endpoint").filter(|endpoint| !endpoint.trim().is_empty()); + let docker_bridge = name == "docker" && get("supervisor_network_mode") == Some("bridge"); + let podman_machine = name == "podman" && cfg!(not(target_os = "linux")); + if endpoint.is_none() && args.disable_tls && (docker_bridge || podman_machine) { + return Err(ProviderWorkloadIdentityConfigError(format!( + "spiffe_workload_identity requires HTTPS for the default {name} supervisor gateway endpoint; enable gateway TLS" + )) + .into()); + } + let Some(endpoint) = endpoint else { + return Ok(()); + }; + let endpoint = openshell_core::grpc_client::token_grant_gateway_endpoint(endpoint); + if docker_bridge + && endpoint.as_ref().is_ok_and(|url| match url.host() { + Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"), + Some(url::Host::Ipv4(host)) => host.is_loopback() || host.is_unspecified(), + Some(url::Host::Ipv6(host)) => host.is_loopback() || host.is_unspecified(), + None => false, + }) + { + return Err(ProviderWorkloadIdentityConfigError( + "Docker bridge supervisor grpc_endpoint must be reachable outside the gateway's loopback namespace".into(), + ) + .into()); + } + if !endpoint.is_ok_and(|url| { + openshell_core::grpc_client::validate_attested_token_grant_transport(&url).is_ok() + || (name == "vm" + && url.host_str().is_some_and(|host| { + openshell_core::driver_utils::VM_HOST_LOOPBACK_ALIASES.contains(&host) + })) + }) { + return Err(ProviderWorkloadIdentityConfigError(format!( + "spiffe_workload_identity requires HTTPS or direct HTTP to a loopback IP for [openshell.drivers.{name}].grpc_endpoint" + )) + .into()); + } + + Ok(()) +} + fn validate_preflight_semantics( args: &RunArgs, matches: &ArgMatches, file: &ConfigFile, ) -> Result<()> { let gateway = &file.openshell.gateway; + crate::spiffe_broker::SupervisorWorkloadIdentity::from_settings( + gateway.spiffe_workload_identity.as_ref(), + gateway.gateway_jwt.as_ref(), + gateway.spiffe_broker.is_some(), + ) + .map_err(ProviderWorkloadIdentityConfigError)?; + validate_provider_workload_identity_selection(file, args)?; validate_grpc_rate_limit_args( args.grpc_rate_limit_requests, args.grpc_rate_limit_window_seconds, @@ -2925,6 +3070,172 @@ mod tests { }); } + #[test] + fn config_preflight_checks_provider_workload_identity_for_the_selected_driver() { + let config_home = tempfile::tempdir().unwrap(); + let config = config_home.path().join("gateway.toml"); + let workload_identity = r#" +[openshell] +version = 2 +[openshell.gateway.gateway_jwt] +signing_key_path = "/configured/signing.pem" +public_key_path = "/configured/public.pem" +kid_path = "/configured/kid" +ttl_secs = 3600 +[openshell.gateway.spiffe_workload_identity] +spiffe_id_prefix = "spiffe://example.org/openshell" +workload_api_socket_path = "/run/spire/agent.sock" +"#; + // Columns: driver, its table, behind --compute-driver-socket, expected rejection. + let cases = [ + ("", "", false, Some("requires an explicit compute driver")), + ("kubernetes", "", false, Some("Kubernetes compute driver")), + ( + "docker", + "", + false, + Some("provider_spiffe_workload_api_socket"), + ), + ("docker", "", true, None), + ( + "docker", + "provider_spiffe_workload_api_socket = '/spire.sock'", + false, + Some("must be an absolute UNIX socket path below a dedicated parent directory"), + ), + ( + "docker", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'", + false, + None, + ), + ( + "docker", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'\nsupervisor_network_mode = 'bridge'", + false, + Some("requires HTTPS for the default docker supervisor gateway endpoint"), + ), + ( + "docker", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'\nsupervisor_network_mode = 'bridge'\ngrpc_endpoint = 'https://127.0.0.1:8080'", + false, + Some("Docker bridge supervisor grpc_endpoint must be reachable"), + ), + ( + "podman", + "provider_spiffe_workload_api_socket = 'tcp:127.0.0.1:8081'", + false, + Some("must be an absolute host UNIX socket path, not a URI"), + ), + ( + "podman", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'", + false, + cfg!(not(target_os = "linux")) + .then_some("requires HTTPS for the default podman supervisor gateway endpoint"), + ), + ( + "podman", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'\ngrpc_endpoint = 'http://127.0.0.1:8080'", + false, + None, + ), + ( + "podman", + "provider_spiffe_workload_api_socket = '/run/spire/agent.sock'\ngrpc_endpoint = 'http://secret-callback-marker.test:8080'", + false, + Some("grpc_endpoint"), + ), + ( + "vm", + "grpc_endpoint = 'http://host.openshell.internal:8080'", + false, + None, + ), + ( + "external", + "socket_path = '/run/external.sock'", + false, + None, + ), + ]; + Environment::new() + .remove("OPENSHELL_GATEWAY_CONFIG") + .remove("OPENSHELL_COMPUTE_DRIVER") + .remove("OPENSHELL_COMPUTE_DRIVER_SOCKET") + .remove("OPENSHELL_DRIVERS") + .set( + "OPENSHELL_VM_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET", + "/run/spire/agent.sock", + ) + .run(|| { + for (driver, settings, remote, expected_error) in cases { + let mut content = workload_identity.to_owned(); + let mut args = vec!["openshell-gateway", "--disable-tls"]; + if !driver.is_empty() { + use std::fmt::Write as _; + writeln!(content, "\n[openshell.drivers.{driver}]\n{settings}").unwrap(); + args.extend(["--compute-driver", driver]); + } + if remote { + args.extend(["--compute-driver-socket", "/run/remote-driver.sock"]); + } + std::fs::write(&config, content).unwrap(); + let registered_name = if matches!(driver, "" | "external") { + "local" + } else { + driver + }; + let mut registry = crate::ComputeDriverRegistry::new(); + registry + .install( + crate::ComputeDriverRegistration::new( + registered_name, + 100, + Some(|| panic!("preflight must not auto-detect a driver")), + TestFactory, + ) + .unwrap(), + ) + .unwrap(); + let (mut run, matches) = parse_with_args(&args); + let result = super::run_config_preflight_with_drivers( + super::ConfigPreflightArgs { + path: Some(config.clone()), + ..Default::default() + }, + run.clone(), + &matches, + ®istry, + ); + if let Some(expected_error) = expected_error { + let error = + result.expect_err("preflight should reject the driver settings"); + let message = error.to_string(); + assert!( + message.contains("category=invalid_provider_workload_identity"), + "{message}" + ); + assert!(message.contains(expected_error), "{message}"); + assert!(!format!("{error:?}").contains("secret-callback-marker")); + assert!(!message.contains("secret-callback-marker")); + + run.config = Some(config.clone()); + let Err(error) = super::prepare_server_config_with_drivers( + &mut run, &matches, ®istry, + ) else { + panic!("daemon startup should reject the driver settings"); + }; + let message = error.to_string(); + assert!(message.contains(expected_error), "{message}"); + assert!(!message.contains("secret-callback-marker")); + } else { + assert!(result.is_ok(), "{driver} with {settings}: {result:?}"); + } + } + }); + } + #[test] fn config_preflight_rejects_factory_without_side_effect_free_validation() { let config_home = tempfile::tempdir().unwrap(); @@ -3309,6 +3620,14 @@ mod tests { "middleware", "[openshell]\nversion = 2\n[[openshell.supervisor.middleware]]\nname = 'guard'\ngrpc_endpoint = 'http://127.0.0.1:50051'\nallow_insecure_transport = true\nmax_payload_bytes = 1024\ntimeout = 'invalid'\n", ), + ( + "provider-workload-identity-without-expiring-session", + "[openshell]\nversion = 2\n[openshell.gateway.spiffe_workload_identity]\nspiffe_id_prefix = 'spiffe://example.org/openshell'\nworkload_api_socket_path = '/run/spire/agent.sock'\n", + ), + ( + "provider-workload-identity-with-invalid-prefix", + "[openshell]\nversion = 2\n[openshell.gateway.gateway_jwt]\nsigning_key_path = '/jwt/signing.pem'\npublic_key_path = '/jwt/public.pem'\nkid_path = '/jwt/kid'\nttl_secs = 3600\n[openshell.gateway.spiffe_workload_identity]\nspiffe_id_prefix = 'secret-prefix-marker'\nworkload_api_socket_path = '/run/spire/agent.sock'\n", + ), ]; for (name, contents) in cases { @@ -3327,7 +3646,18 @@ mod tests { let Err(error) = result else { panic!("{name}: invalid effective configuration passed preflight"); }; - assert!(error.to_string().contains("category=malformed"), "{name}"); + if name.starts_with("provider-workload-identity") { + let message = error.to_string(); + assert!(message.contains("category=invalid_provider_workload_identity"), "{name}"); + let expected_field = if name.ends_with("expiring-session") { + "gateway_jwt.ttl_secs" + } else { + "spiffe_workload_identity.spiffe_id_prefix" + }; + assert!(message.contains(expected_field), "{message}"); + } else { + assert!(error.to_string().contains("category=malformed"), "{name}"); + } assert!(error.to_string().contains("detected_version=2"), "{name}"); assert!(!error.to_string().contains("secret-")); assert!(!format!("{error:?}").contains("secret-")); diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index abcad0cfc9..8c1c3003a8 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -249,6 +249,8 @@ pub struct GatewayFileSection { #[serde(default)] pub spiffe_broker: Option, #[serde(default)] + pub spiffe_workload_identity: Option, + #[serde(default)] pub otlp: Option, #[serde(default)] pub ocsf_log: Option, @@ -1474,20 +1476,23 @@ pub enum ConfigFileError { }, } -const CONFIG_MIGRATION_URL: &str = "https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration#migrate-to-schema-version-2"; +const CONFIG_MIGRATION_ADVICE: &str = "migrate it before restarting the gateway: https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration#migrate-to-schema-version-2"; /// Stable package-preflight failure with no configuration contents attached. #[derive(Debug, thiserror::Error)] #[error( - "gateway config preflight failed: path='{}' category={} detected_version={}; the file was preserved unchanged; migrate it before restarting the gateway: {CONFIG_MIGRATION_URL}", + "gateway config preflight failed: path='{}' category={} detected_version={}; the file was preserved unchanged; {}", path.display(), category, - detected_version + detected_version, + reason.as_deref().unwrap_or(CONFIG_MIGRATION_ADVICE) )] pub struct ConfigPreflightError { path: PathBuf, category: &'static str, detected_version: String, + /// Replaces the migration advice. Fixed text only. + reason: Option, } impl ConfigPreflightError { @@ -1496,6 +1501,15 @@ impl ConfigPreflightError { path: path.to_path_buf(), category: "malformed", detected_version: SCHEMA_VERSION.to_string(), + reason: None, + } + } + + pub(crate) fn invalid_provider_workload_identity(path: &Path, reason: String) -> Self { + Self { + category: "invalid_provider_workload_identity", + reason: Some(reason), + ..Self::invalid_current(path) } } @@ -1824,6 +1838,7 @@ fn preflight_error( path: path.to_path_buf(), category, detected_version, + reason: None, } } @@ -3764,7 +3779,7 @@ ssh_gateway_port = 8080 assert!(diagnostic.contains(&format!("category={category}"))); assert!(diagnostic.contains(&format!("detected_version={version}"))); assert!(diagnostic.contains("the file was preserved unchanged")); - assert!(diagnostic.contains(CONFIG_MIGRATION_URL)); + assert!(diagnostic.contains(CONFIG_MIGRATION_ADVICE)); assert!(!diagnostic.contains("secret-value")); assert!(!format!("{error:?}").contains("secret-value")); assert!(std::error::Error::source(&error).is_none()); diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index aa834113b2..8f8db64183 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -2409,6 +2409,15 @@ pub struct ComputeDriverBuildContext<'a> { } impl ComputeDriverBuildContext<'_> { + /// Whether the gateway requires launch-attested provider identities. + #[must_use] + pub fn requires_provider_workload_identity(&self) -> bool { + self.config + .driver_startup + .file + .is_some_and(|file| file.openshell.gateway.spiffe_workload_identity.is_some()) + } + /// The gateway's budget for preparing images, which includes the images /// a driver pulls while it is constructed. #[must_use] @@ -3338,6 +3347,35 @@ mod tests { } } + #[test] + fn provider_workload_identity_is_required_only_when_its_table_is_set() { + let config = Config::new(None); + let (_shutdown, shutdown_rx) = watch::channel(false); + let enabled: super::config_file::ConfigFile = toml::from_str( + "[openshell]\nversion = 2\n[openshell.gateway.spiffe_workload_identity]\nspiffe_id_prefix = 'spiffe://example.org/openshell'\nworkload_api_socket_path = '/run/spire/agent.sock'\n", + ) + .unwrap(); + for (file, required) in [(None, false), (Some(&enabled), true)] { + let context = super::ComputeDriverBuildContext { + config: super::ComputeDriverConfigContext { + driver_name: "docker", + gateway_name: "test", + gateway_bind_address: "127.0.0.1:8080".parse().unwrap(), + gateway_log_level: "info", + driver_startup: test_driver_startup(&config, file), + }, + shutdown_rx: shutdown_rx.clone(), + shared_supervision: &std::sync::OnceLock::new(), + detected: crate::DetectedSlot::default(), + image_preparation_timeout: Duration::from_mins(30), + app_endpoint_resolver: &std::sync::OnceLock::new(), + supervisor_recovery_timeout_secs: None, + supervisor_pool_limits: openshell_supervisor_control::PoolLimits::default(), + }; + assert_eq!(context.requires_provider_workload_identity(), required); + } + } + #[test] fn factory_admission_defaults_remain_enabled() { use super::ComputeDriverFactory as _; diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index f7aa1b4996..5cd7acbdd2 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1752,6 +1752,178 @@ The gateway verifies supervisor JWT-SVIDs with JWT bundles fetched from the SPIFFE Workload API, so this validation path does not require gateway access to the SPIRE OIDC discovery endpoint or its TLS CA. +### Sandbox identity through the Workload API + +Configure `[openshell.gateway.spiffe_workload_identity]` to give each sandbox +its own SPIFFE identity for provider token grants on Docker, Podman, and +MicroVM. The sandbox's dedicated supervisor fetches JWT-SVIDs from a Workload +API Unix socket. The gateway verifies them and makes the OAuth requests. The +agent never holds the socket, the JWT-SVIDs, or the access token. +[Dynamic Token Grants](/how-it-works/providers/profiles#dynamic-token-grants) +describes the grant flow. Kubernetes uses the +[Broker API mode](#sandbox-identity-through-the-spiffe-broker-api) instead. + +#### Enable sandbox identity + +Add the table, give the selected driver a Workload API socket, and restart the +gateway. + +```toml +[openshell.gateway] +compute_driver = "docker" + +[openshell.gateway.gateway_jwt] +signing_key_path = "/etc/openshell/jwt/signing.pem" +public_key_path = "/etc/openshell/jwt/public.pem" +kid_path = "/etc/openshell/jwt/kid" +ttl_secs = 3600 + +[openshell.gateway.spiffe_workload_identity] +spiffe_id_prefix = "spiffe://example.org/openshell" +workload_api_socket_path = "/run/spire/agent.sock" + +[openshell.drivers.docker] +provider_spiffe_workload_api_socket = "/run/spire/agent.sock" +``` + +The mode has these requirements: + +- `spiffe_id_prefix` is `spiffe://`, optionally followed by path + segments, with no trailing slash. +- `workload_api_socket_path` is a Workload API socket in the gateway's + filesystem. The gateway reads the JWT trust bundle from it and, for + `token_exchange` grants, fetches its own JWT-SVID there. +- `[openshell.gateway.gateway_jwt]` sets a positive `ttl_secs`. An installation + that relies on discovered signing keys has no such table. Add it and point + `signing_key_path`, `public_key_path`, and `kid_path` at the discovered + `jwt/signing.pem`, `jwt/public.pem`, and `jwt/kid` files. The + [full example](#full-example) shows the table. +- The compute driver is selected explicitly with `compute_driver`, + `OPENSHELL_COMPUTE_DRIVER`, or `--compute-driver`. The gateway rejects the + table with the Kubernetes driver and with `spiffe_broker`. +- The Docker, Podman, or MicroVM driver table sets + `provider_spiffe_workload_api_socket`. Docker and Podman mount the socket's + directory read-only into the supervisor container. MicroVM gives the path to + the supervisor on the driver host. A Podman `tcp:` endpoint serves direct + supervisor exchanges only. +- Both sockets are plain absolute paths below a dedicated parent directory. + OpenShell rejects a `unix:` or `tcp:` URI and a socket directly under `/`, + such as `/agent.sock`. +- The supervisor reaches the gateway over HTTPS, or over HTTP to a loopback IP + address. Without an explicit `grpc_endpoint`, Docker bridge networking and + Podman on a host other than Linux need gateway TLS. + +[`openshell-gateway config preflight`](#gateway-config-preflight) checks these +settings without opening either socket. A failure reports +`category=invalid_provider_workload_identity` and the reason. + +At startup the selected driver checks that its supervisor supports the mode. +Docker and MicroVM also need the driver's socket to exist at that point. Podman +checks that a supervisor can see the socket each time it creates one. If a +startup check fails, the driver logs the reason and the gateway stops with +`did not advertise openshell.compute.provider-workload-identity`. Once the +gateway runs, `openshell gateway info` lists that capability for the driver. + +Creating or starting a sandbox needs only the socket file. It needs no +registration and does not contact the issuer, which the supervisor first uses +when the sandbox makes a provider request. A supervisor keeps the grant mode it +was launched with, so stop and start existing sandboxes after you enable the +mode. + +The mode adds no state on the driver host and nothing to back up. Sandbox +starts and stops stay idempotent, and gateway shutdown is unchanged. + +#### Register identities + +Each sandbox has two SPIFFE IDs. Register both with the Workload API issuer for +that sandbox's supervisor only. + +| Identity | SPIFFE ID | +|---|---| +| Stable ID | `/gateway//sandbox/` | +| Launch ID | `/launch/` | + +`` is `gateway_jwt.gateway_id`, which defaults to `openshell`. It +is not `[openshell.gateway].name`. `` is the sandbox's runtime +generation. The gateway assigns a new generation on create, start, resume, and +automatic restart, and keeps it across a gateway restart. The gateway logs both +IDs for each launch in the message +`Configured sandbox SPIFFE identity for provider grants`. + +The supervisor requests the stable ID for the provider audience, which is the +grant's `jwt_svid_audience` or its default. It requests the launch ID for the +launch audience, `urn:openshell:provider-grants:launch:`. The +gateway verifies both on every provider request and sends the stable JWT-SVID +as the OAuth client assertion. + +A new generation means a new launch ID. Register the new launch each time the +generation changes, and retire the previous one. Until you do, provider +requests from that sandbox fail, so automate registration when sandboxes can +restart automatically. A start that names a new launch ID replaces the +sandbox's supervisor, and the gateway refuses a supervisor from an earlier +launch. + +Each runtime gives the issuer different evidence to attest: + +- Docker and Podman set the label `openshell.ai/provider-launch-spiffe-id` to + the launch ID on the supervisor container. The workload container carries + the label with an empty value, so an image or a sandbox template cannot + claim a launch. Bind both registrations to the container whose label equals + the launch ID. Use an attestor that reads engine labels, such as SPIRE's + [Docker workload attestor](https://github.com/spiffe/spire/blob/main/doc/plugin_agent_workloadattestor_docker.md). + Whoever controls the engine controls its labels. On rootless Podman that is + the account that owns the engine, so use an engine owned by a trusted host + account and limit issuance to that account's containers. +- MicroVM starts every host supervisor as the same user from the same + executable, so SPIRE's + [Unix selectors](https://github.com/spiffe/spire/blob/main/doc/plugin_agent_workloadattestor_unix.md) + match every sandbox's supervisor. Per-sandbox identity on MicroVM needs an + external attestor that maps a supervisor process to its sandbox launch. The + driver does not provide one. + +Configure the OAuth server to trust the SPIFFE issuer and to accept each +sandbox's stable ID as the client. For `token_exchange`, also authorize the +gateway's own SPIFFE ID for the intermediate exchange. The gateway makes the +OAuth requests, so each provider's `token_endpoint` must be reachable from the +gateway. + +#### Verify sandbox identity + +Check the deployment before you rely on it. Use a disposable trust domain, the +attestor you deploy, an OAuth test server that verifies JWT-SVID signatures and +audiences, and a protected HTTP target. + +1. Attach the same provider to two sandboxes and call the target from each. + Confirm that the OAuth server sees a different stable ID for each sandbox. + At the issuer, confirm that each supervisor receives its stable ID for the + provider audience and its launch ID for the launch audience, and that the + issuer refuses it the other sandbox's IDs. +2. Stop and start one sandbox. Confirm that its launch ID changed and that a + request fails until you register the new launch. Register it, retire the + previous launch, and confirm that the OAuth server sees the same stable ID. + Restart the gateway and confirm that the launch ID did not change. +3. Give the access token a short lifetime so that a later request needs a new + one. Then make the gateway, the Workload API, and the OAuth endpoint + unreachable, one at a time. Confirm each time that the request fails and + that nothing reaches the target. A token in the gateway's cache can cover + an OAuth outage. The supervisor and the gateway reuse Workload API results + for up to five seconds, so wait that long after you stop the Workload API. +4. Confirm that the workload's environment, arguments, and mounts contain no + Workload API socket, JWT-SVID, or access token. + +A missing registration, a JWT-SVID that does not match the sandbox's current +launch, or an unavailable issuer fails the provider request. The workload +receives a generic HTTP 502, and OpenShell forwards nothing to the target. The +sandbox's latest token grant failure gives the code and stage, such as +`workload_identity_rejected`. See +[Read Token Grant Failures](/how-it-works/sandboxes/overview#read-token-grant-failures). + +#### Turn off sandbox identity + +Remove the `[openshell.gateway.spiffe_workload_identity]` table and restart the +gateway. A supervisor keeps the grant mode it was launched with, so stop and +start each sandbox. Then retire its registrations. + ### Sandbox identity through the SPIFFE Broker API For shared-supervisor Kubernetes sandboxes, the gateway can obtain sandbox @@ -2258,10 +2430,12 @@ gateway's staging directory and rootfs tar sources fail with a Set `provider_spiffe_workload_api_socket`, or `OPENSHELL_VM_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET`, to the absolute path of a Workload API Unix socket on the VM driver host. The driver passes the path to -each host supervisor for provider token grants. The legacy -`provider_spiffe_workload_api_tcp_endpoint` and -`provider_spiffe_allow_guest_tcp` settings have no effect. The driver logs a -warning when an endpoint is set. +each host supervisor for provider token grants. Read the MicroVM attestation +limit in +[Sandbox identity through the Workload API](#sandbox-identity-through-the-workload-api) +before you rely on it. The legacy `provider_spiffe_workload_api_tcp_endpoint` +and `provider_spiffe_allow_guest_tcp` settings have no effect. The driver logs +a warning when an endpoint is set. ### Extension Driver @@ -2284,6 +2458,20 @@ compute_driver = "kyma" socket_path = "/run/openshell/kyma-compute-driver.sock" ``` +An extension driver can offer +[sandbox identity through the Workload API](#sandbox-identity-through-the-workload-api). +To offer it, the driver does the following: + +- Advertises the capability `openshell.compute.provider-workload-identity`. +- Gives each dedicated supervisor, and not the workload, a Workload API Unix + socket. The supervisor reads the path from + `OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_SOCKET`. +- Marks the supervisor with the launch ID from its launch bundle, in a form + that an issuer can attest. The bundle is the `launch_authentication` JSON, + and the launch ID is its `supervisor.provider_launch_spiffe_id` field. +- Replaces the supervisor when `StartSandbox` carries a bundle that names a + different launch ID. + ## Preflight package configuration {#gateway-config-preflight} Before starting a package-managed gateway, validate the selected file without diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..8da0ea1565 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -766,7 +766,7 @@ The refresh attaches to the primary credential (`access_key_id`). Each reference ### Dynamic Token Grants -`token_grant` belongs to one credential declaration. When a sandbox with the provider attached sends HTTP traffic to a matching profile endpoint, the supervisor resolves the dynamic credentials, caches each returned access token separately, and injects them before forwarding the request upstream. Use `auth_style: bearer` to inject `Authorization: Bearer `, or `auth_style: header` with `header_name` to inject the raw access token into a custom header. +`token_grant` belongs to one credential declaration. When a sandbox with the provider attached sends HTTP traffic to a matching profile endpoint, OpenShell resolves the dynamic credentials and caches each returned access token separately. The supervisor injects them before forwarding the request upstream. Use `auth_style: bearer` to inject `Authorization: Bearer `, or `auth_style: header` with `header_name` to inject the raw access token into a custom header. Declare multiple credentials with different destination headers when one request needs independently issued tokens. Each credential keeps its own token endpoint, audience, scopes, and cache lifetime. For example, this profile sends a service bearer token and a separate workload token on the same inspected request: @@ -814,7 +814,7 @@ Upgrade the gateway before the supervisor: inspected requests with a matching to Later requests use the latest installed provider credentials. If provider state or policy changes while a grant is being obtained, the supervisor rejects the request before sending it upstream. Reconnect and retry after the new configuration is ready. A token-service failure also closes the request without forwarding it; a later connection can retry the grant. -OpenShell supports two dynamic grant types: +OpenShell supports two dynamic grant types. The table describes direct exchange by a dedicated supervisor. In the gateway-mediated modes described after the field table, the gateway makes the same OAuth requests. | Grant type | Behavior | |---|---| @@ -851,20 +851,26 @@ Token grant fields: | `grant_type` | No | `client_credentials` or `token_exchange`. Defaults to `client_credentials` for backward compatibility. | | `token_endpoint` | Yes | OAuth2 token endpoint that accepts a SPIFFE JWT-SVID client assertion. Use `https://` unless the endpoint is loopback or a Kubernetes service DNS name such as `token-issuer.default.svc.cluster.local`. | | `audience` | No | Resource audience requested from the token service. For `token_exchange`, this is the final exchange audience; the gateway intermediate exchange always uses the verified supervisor SVID subject as its audience. | -| `jwt_svid_audience` | No | Audience used when requesting the JWT-SVID. When omitted, OpenShell derives an issuer-style audience from Keycloak token endpoint paths or falls back to the full token endpoint URL. | +| `jwt_svid_audience` | No | Audience used when requesting the JWT-SVID. When omitted, OpenShell derives an issuer-style audience from Keycloak token endpoint paths or falls back to the full token endpoint URL. For RFC 7523 client authentication, set it to the authorization server's exact issuer identifier, as required by [RFC 10070 Section 4](https://www.rfc-editor.org/rfc/rfc10070.html#section-4). | | `client_assertion_type` | No | OAuth2 `client_assertion_type` form value. Defaults to RFC 7523 `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. Set `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` when the token issuer expects the SPIFFE assertion type. | | `scopes` | No | OAuth2 scopes sent as a space-separated `scope` parameter. | -| `cache_ttl` | No | Protobuf-duration cache override, such as `300s`. Omission uses the token response expiry; `0s` disables caching. Shared supervisor grants require a positive override to be at least `1s` and cap it at the issuer and identity expiries. The legacy `cache_ttl_seconds` input remains accepted. | +| `cache_ttl` | No | Protobuf-duration cache override, such as `300s`. Omission uses the token response expiry; `0s` disables caching. Gateway-mediated grants cap the override at the issuer and identity expiries. Shared supervisor grants require a positive override to be at least `1s`. With `spiffe_workload_identity`, a positive override below `1s` disables caching. The legacy `cache_ttl_seconds` input remains accepted. | | `requested_token_type` | No | RFC 8693 `requested_token_type` sent during token exchange. Defaults to `urn:ietf:params:oauth:token-type:access_token`. | | `subject_token` | Required for `token_exchange` | Subject-token source used for the gateway-brokered intermediate exchange. Phase one supports `source: provider_credential`, where `credential` names another credential declared in the same profile. That referenced credential is broker-only and cannot declare workload injection metadata such as env vars, static placement, refresh, or token grant metadata. | | `subject_token.subject_token_type` | No | RFC 8693 `subject_token_type` for the stored subject token. Defaults to `urn:ietf:params:oauth:token-type:access_token`. | | `audience_overrides` | No | Endpoint-specific final-exchange `audience` and `scopes` overrides selected by host, port, and path. These overrides do not affect the gateway intermediate exchange. | -Dedicated supervisors use a local SPIFFE Workload API socket for the exchanges above. Shared supervisors use the gateway's [SPIFFE Broker API integration](/how-it-works/gateways/configuration#sandbox-identity-through-the-spiffe-broker-api): the gateway obtains the stable sandbox JWT-SVID and performs both exchanges, then returns only the final access token. The intermediate audience is the stable sandbox SPIFFE ID. Only the gateway mounts the Workload API socket, including for its own JWT-SVID in `token_exchange`. +Dedicated supervisors use a local SPIFFE Workload API socket for the exchanges above. + +With [`spiffe_workload_identity`](/how-it-works/gateways/configuration#sandbox-identity-through-the-workload-api), the gateway makes the OAuth requests for dedicated supervisors on Docker, Podman, and MicroVM. The supervisor fetches two JWT-SVIDs from its Workload API socket, one for the sandbox's stable SPIFFE ID and one for the SPIFFE ID of its current launch, and sends both with each request. The gateway verifies both, performs the exchanges with the stable JWT-SVID, and returns only the final access token. The supervisor reuses a pair for up to five seconds, unless the issuer adds a JWT ID (`jti`) to either JWT-SVID. + +Shared supervisors use the gateway's [SPIFFE Broker API integration](/how-it-works/gateways/configuration#sandbox-identity-through-the-spiffe-broker-api): the gateway obtains the stable sandbox JWT-SVID and performs both exchanges, then returns only the final access token. Only the gateway mounts the Workload API socket, including for its own JWT-SVID in `token_exchange`. + +In both gateway-mediated modes, the intermediate audience is the stable sandbox SPIFFE ID. Token grants apply to HTTP traffic that the proxy can inspect. Token-grant profiles reject endpoints with `protocol: sql` or `tls: skip`, including when `allow_uninspected_credentials` is enabled, because those modes cannot inject the required HTTP credential. The token service must return a token value that is safe for HTTP header placement; malformed values are rejected before caching or header injection. -The gateway authorizes the sandbox session and provider attachment on every request. In the dedicated path it also verifies the supervisor JWT-SVID issuer, audience, signature, and SPIFFE trust domain. In the shared path it resolves the configured credential itself and rechecks authorization before returning even a cached token. +The gateway authorizes the sandbox session and provider attachment on every request. In the direct path it also verifies the supervisor JWT-SVID issuer, audience, signature, and SPIFFE trust domain. In the gateway-mediated modes it resolves the configured credential itself and rechecks authorization before returning even a cached token. With `spiffe_workload_identity` it also verifies both JWT-SVIDs on every request, including one that a cached token answers. ### Token Grant Failures diff --git a/examples/spiffe-token-exchange-demo/podman/README.md b/examples/spiffe-token-exchange-demo/podman/README.md index cbc470410c..f30f235be0 100644 --- a/examples/spiffe-token-exchange-demo/podman/README.md +++ b/examples/spiffe-token-exchange-demo/podman/README.md @@ -1,7 +1,10 @@ # Podman SPIFFE Token Exchange Demo This variant runs the SPIFFE token exchange demo with local Podman containers -instead of Kubernetes workloads. +instead of Kubernetes workloads. The dedicated supervisor exchanges tokens +directly. For grants that the gateway performs with +`spiffe_workload_identity`, see +[Sandbox identity through the Workload API](../../../docs/how-it-works/gateways/configuration.mdx#sandbox-identity-through-the-workload-api). The first version is intentionally single-sandbox. The script creates one concrete SPIRE registration entry for the sandbox after OpenShell creates it.