From 1358794c2d217143660e01665ed416a2a2291bb9 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:24:27 +0530 Subject: [PATCH 1/5] feat(compute): add provider workload identity contract Add the contract that the gateway and a compute driver share to give each dedicated supervisor a SPIFFE identity for provider grants. - A capability, openshell.compute.provider-workload-identity, for a driver that gives each dedicated supervisor a Workload API socket and marks it with its launch SPIFFE ID. - The launch bundle can carry the stable sandbox SPIFFE ID and the launch SPIFFE ID. The launch ID is the stable ID followed by /launch/, so it changes when the gateway issues a new generation. - validate_provider_launch_identity lets a driver check that both IDs belong to the sandbox and generation it is starting. - ConfigureRequest gains a flag that tells a managed driver the mode is selected. - Label and probe constants shared by the supervisor and the drivers. Nothing uses the contract yet. Existing call sites only initialize the new fields. Signed-off-by: Shiju --- crates/openshell-core/src/driver_utils.rs | 165 ++++++++++++++++++ .../openshell-core/src/extension_protocol.rs | 27 +-- crates/openshell-core/src/jwt.rs | 12 ++ crates/openshell-driver-docker/src/tests.rs | 2 + crates/openshell-driver-podman/src/driver.rs | 2 + .../openshell-driver-podman/src/isolation.rs | 2 + crates/openshell-driver-vm/src/driver.rs | 2 + crates/openshell-gateway/src/launcher.rs | 1 + .../openshell-server/src/auth/sandbox_jwt.rs | 5 + .../src/persistence/mutation_lock_pg_tests.rs | 4 + crates/openshell-server/src/ssh_identity.rs | 2 + crates/openshell-spiffe/src/lib.rs | 29 ++- .../src/backend_setup/tests.rs | 2 + .../src/legacy_startup_regression_tests.rs | 2 + crates/openshell-supervisor/src/lib.rs | 2 + crates/openshell-supervisor/src/main.rs | 2 + proto/driver_launch.proto | 3 + 17 files changed, 248 insertions(+), 16 deletions(-) diff --git a/crates/openshell-core/src/driver_utils.rs b/crates/openshell-core/src/driver_utils.rs index 12ac8019be..e19abff651 100644 --- a/crates/openshell-core/src/driver_utils.rs +++ b/crates/openshell-core/src/driver_utils.rs @@ -8,6 +8,61 @@ use std::path::{Path, PathBuf}; use crate::proto::compute::v1::DriverSandbox; +/// Check that a launch bundle's provider identities belong to this sandbox launch. +/// +/// The stable ID must end in this gateway and sandbox. The launch ID must be +/// that stable ID followed by `/launch/`, so it changes exactly +/// when the gateway issues a new runtime generation. A driver calls this +/// before it marks a supervisor with the launch ID. +#[cfg(feature = "jwt")] +#[allow(clippy::result_large_err)] +pub fn validate_provider_launch_identity( + sandbox_id: &str, + generation_id: &str, + authentication: &crate::jwt::SandboxLaunchAuthentication, +) -> Result<(), tonic::Status> { + let invalid = + || tonic::Status::invalid_argument("provider identity does not match the sandbox launch"); + let supervisor = &authentication.supervisor; + if supervisor.runtime_generation.as_str() != generation_id { + return Err(invalid()); + } + let sandbox_path = format!( + "/gateway/{}/sandbox/{sandbox_id}", + authentication.gateway_id + ); + let prefix = supervisor + .provider_spiffe_id + .as_deref() + .and_then(|id| id.strip_suffix(&sandbox_path)) + .ok_or_else(invalid)?; + let prefix = openshell_spiffe::SandboxSpiffeIdPrefix::parse(prefix).map_err(|_| invalid())?; + let expected = prefix + .supervisor_launch_spiffe_id(&authentication.gateway_id, sandbox_id, generation_id) + .map_err(|_| invalid())?; + if supervisor.provider_launch_spiffe_id.as_deref() != Some(expected.as_str()) { + return Err(invalid()); + } + Ok(()) +} + +/// Gateway alias available inside a sandbox VM. +pub const VM_HOST_GATEWAY_ALIAS: &str = "host.openshell.internal"; + +/// Gateway hostnames that VM host supervisors rewrite to numeric loopback. +pub const VM_HOST_LOOPBACK_ALIASES: &[&str] = &[ + VM_HOST_GATEWAY_ALIAS, + "host.containers.internal", + "host.docker.internal", +]; + +/// Supervisor command that reports whether it can see a Workload API socket. +pub const PROVIDER_WORKLOAD_IDENTITY_PROBE: &str = "provider-workload-identity-probe"; + +/// Exit statuses for the provider probe with a socket path argument. +pub const PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT: i32 = 70; +pub const PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE: i32 = 71; + // --------------------------------------------------------------------------- // Sandbox container/pod label keys (openshell.ai/ namespace) // --------------------------------------------------------------------------- @@ -34,6 +89,9 @@ pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace"; /// Label carrying the gateway identity on managed namespaces. pub const LABEL_GATEWAY_ID: &str = "openshell.ai/gateway-id"; +/// SPIFFE ID registered for one driver-owned supervisor launch. +pub const LABEL_PROVIDER_LAUNCH_SPIFFE_ID: &str = "openshell.ai/provider-launch-spiffe-id"; + /// Label selector that matches all OpenShell-managed resources which carry a /// sandbox ID label. Used by list and watch operations to exclude foreign /// resources from the same namespace. @@ -743,6 +801,24 @@ pub fn validate_provider_spiffe_unix_socket(path: &Path) -> Result<(), String> { Ok(()) } +/// Check that an absolute path resolves to a Unix socket in the current filesystem. +pub fn provider_spiffe_socket_visible(path: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::FileTypeExt as _; + + path.is_absolute() + && path + .metadata() + .is_ok_and(|meta| meta.file_type().is_socket()) + } + #[cfg(not(unix))] + { + let _ = path; + false + } +} + /// Return the guest/container path for a projected provider SPIFFE socket. pub fn projected_provider_spiffe_socket_path(path: &Path) -> Result { validate_provider_spiffe_unix_socket(path)?; @@ -1550,4 +1626,93 @@ mod tests { }) .expect("an intercepting proxy's CA is meaningful without an https:// proxy URL"); } + + #[cfg(feature = "jwt")] + #[test] + fn provider_launch_identity_binds_generation_sandbox_and_launch() { + use crate::jwt::{ + CredentialEpoch, SandboxLaunchAuthentication, SecretJwt, SessionRotation, + SupervisorAuthBundle, + }; + use crate::sandbox_generation::SandboxGenerationId; + use crate::sandbox_session::SandboxSessionId; + + let sandbox = "spiffe://example.test/gateway/gateway/sandbox/sandbox-a"; + let authentication = SandboxLaunchAuthentication { + supervisor: SupervisorAuthBundle { + session_id: SandboxSessionId::new(), + runtime_generation: SandboxGenerationId::parse("generation").unwrap(), + session_rotation: SessionRotation::new(1).unwrap(), + auth_epoch: CredentialEpoch::new(1).unwrap(), + gateway_token: SecretJwt::parse("gateway-token").unwrap(), + gateway_expires_at: 0, + sandbox_token: SecretJwt::parse("sandbox-token").unwrap(), + sandbox_expires_at: 0, + provider_spiffe_id: Some(sandbox.to_string()), + provider_launch_spiffe_id: Some(format!("{sandbox}/launch/generation")), + ssh_host_private_key: None, + traces_otlp_headers: None, + ocsf_otlp_headers: None, + agent_otlp_headers: None, + otlp_tls: Vec::new(), + traces_otlp_tls: None, + ocsf_otlp_tls: None, + agent_otlp_tls: None, + }, + gateway_id: "gateway".to_string(), + verification_keys: Vec::new(), + }; + validate_provider_launch_identity("sandbox-a", "generation", &authentication).unwrap(); + + let with_launch = |launch: Option| { + let mut changed = authentication.clone(); + changed.supervisor.provider_launch_spiffe_id = launch; + changed + }; + for (case, sandbox_id, generation_id, bundle) in [ + ( + "another generation", + "sandbox-a", + "other-generation", + authentication.clone(), + ), + ( + "another sandbox", + "sandbox-b", + "generation", + authentication.clone(), + ), + ( + "no launch identity", + "sandbox-a", + "generation", + with_launch(None), + ), + ( + "a launch identity of another sandbox", + "sandbox-a", + "generation", + with_launch(Some( + "spiffe://example.test/gateway/gateway/sandbox/sandbox-b/launch/generation" + .to_string(), + )), + ), + ( + "a launch identity for another generation", + "sandbox-a", + "generation", + with_launch(Some(format!("{sandbox}/launch/earlier-generation"))), + ), + ( + "a launch identity with extra segments", + "sandbox-a", + "generation", + with_launch(Some(format!("{sandbox}/launch/generation/extra"))), + ), + ] { + let error = + validate_provider_launch_identity(sandbox_id, generation_id, &bundle).unwrap_err(); + assert_eq!(error.code(), tonic::Code::InvalidArgument, "{case}"); + } + } } diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 1d6d57960b..a9515af295 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -47,6 +47,11 @@ pub const COMPUTE_SUSPEND_RESUME: &str = "openshell.compute.suspend-resume"; pub const COMPUTE_UPDATE_SANDBOX_CONFIGURATION: &str = "openshell.compute.update-sandbox-configuration"; +/// Driver gives each dedicated supervisor a Workload API socket and marks it +/// with the launch SPIFFE ID from its launch bundle. A start whose bundle +/// names a different launch replaces the supervisor. +pub const COMPUTE_PROVIDER_WORKLOAD_IDENTITY: &str = "openshell.compute.provider-workload-identity"; + /// Capability for supervisor middleware that implements HTTP hooks. /// /// A service selects HTTP hooks for all of its HTTP bindings by @@ -160,6 +165,7 @@ pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata { supported_capabilities.push(COMPUTE_LAUNCH_AUTHENTICATION.to_string()); supported_capabilities.push(COMPUTE_ISOLATION_BACKEND.to_string()); supported_capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string()); + supported_capabilities.push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.to_string()); } ExtensionFamily::SupervisorMiddleware => { supported_capabilities.push(SUPERVISOR_MIDDLEWARE_HTTP_HOOKS.to_string()); @@ -458,20 +464,15 @@ mod tests { use super::*; #[test] - fn compute_gateway_advertises_both_optional_extensions() { + fn compute_gateway_advertises_optional_extensions() { let gateway = gateway_metadata(ExtensionFamily::Compute); - assert!( - gateway - .supported_capabilities - .iter() - .any(|c| c == COMPUTE_ISOLATION_BACKEND) - ); - assert!( - gateway - .supported_capabilities - .iter() - .any(|c| c == COMPUTE_UPDATE_SANDBOX_CONFIGURATION) - ); + for capability in [ + COMPUTE_ISOLATION_BACKEND, + COMPUTE_UPDATE_SANDBOX_CONFIGURATION, + COMPUTE_PROVIDER_WORKLOAD_IDENTITY, + ] { + assert!(has_capability(&gateway.supported_capabilities, capability)); + } } fn compatible() -> (PeerMetadata, PeerMetadata) { diff --git a/crates/openshell-core/src/jwt.rs b/crates/openshell-core/src/jwt.rs index 84ffe98ec0..cae9fed81e 100644 --- a/crates/openshell-core/src/jwt.rs +++ b/crates/openshell-core/src/jwt.rs @@ -499,6 +499,12 @@ mod session { pub gateway_expires_at: i64, pub sandbox_token: SecretJwt, pub sandbox_expires_at: i64, + /// Exact provider identity selected by the gateway for this supervisor. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_spiffe_id: Option, + /// SPIFFE ID the issuer assigns to this supervisor launch. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub provider_launch_spiffe_id: Option, /// Never delivered to the workload. Missing only in older bundles. #[serde(default, skip_serializing_if = "Option::is_none")] pub ssh_host_private_key: Option, @@ -1787,6 +1793,8 @@ mod tests { gateway_expires_at: pair.gateway.expires_at, sandbox_token: pair.sandbox.token, sandbox_expires_at: pair.sandbox.expires_at, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, @@ -1935,6 +1943,8 @@ mod tests { gateway_expires_at: pair.gateway.expires_at, sandbox_token: pair.sandbox.token, sandbox_expires_at: pair.sandbox.expires_at, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: headers("traces"), ocsf_otlp_headers: headers("ocsf"), @@ -1974,6 +1984,8 @@ mod tests { gateway_expires_at: pair.gateway.expires_at, sandbox_token: pair.sandbox.token, sandbox_expires_at: pair.sandbox.expires_at, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: Some(SecretSshHostKey::new( "private-ssh-host-key".to_string(), )), diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index c86e2d068b..4248145235 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -63,6 +63,8 @@ pub fn test_launch_authentication() -> Vec { gateway_expires_at: i64::MAX, sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), sandbox_expires_at: i64::MAX, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index a263bcf7d2..d4000c15c2 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -2704,6 +2704,8 @@ mod tests { gateway_expires_at: i64::MAX, sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), sandbox_expires_at: i64::MAX, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-driver-podman/src/isolation.rs b/crates/openshell-driver-podman/src/isolation.rs index f9fc790588..7a40ba62ad 100644 --- a/crates/openshell-driver-podman/src/isolation.rs +++ b/crates/openshell-driver-podman/src/isolation.rs @@ -470,6 +470,8 @@ mod tests { gateway_expires_at: i64::MAX, sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(), sandbox_expires_at: i64::MAX, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..eb939c85bc 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -11265,6 +11265,8 @@ mod tests { gateway_expires_at: 1, sandbox_token: SecretJwt::parse(format!("sandbox-{label}")).expect("sandbox token"), sandbox_expires_at: 1, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs index f50183592c..1b5d09edd1 100644 --- a/crates/openshell-gateway/src/launcher.rs +++ b/crates/openshell-gateway/src/launcher.rs @@ -872,6 +872,7 @@ impl<'a> ConfigureInputs<'a> { .admission .and_then(|policy| serde_json::to_string(policy).ok()) .unwrap_or_default(), + verified_provider_workload_identity: None, } } } diff --git a/crates/openshell-server/src/auth/sandbox_jwt.rs b/crates/openshell-server/src/auth/sandbox_jwt.rs index 5d37d6c8a5..49f06b8356 100644 --- a/crates/openshell-server/src/auth/sandbox_jwt.rs +++ b/crates/openshell-server/src/auth/sandbox_jwt.rs @@ -264,6 +264,8 @@ impl SandboxSessionJwtAuthority { gateway_expires_at: pair.gateway.expires_at, sandbox_token: pair.sandbox.token, sandbox_expires_at: pair.sandbox.expires_at, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, @@ -616,6 +618,9 @@ mod tests { let first = authority .mint_persisted_launch("sandbox-a", &identity) .unwrap(); + // The session authority leaves the provider identities unset. + assert!(first.supervisor.provider_spiffe_id.is_none()); + assert!(first.supervisor.provider_launch_spiffe_id.is_none()); let mut annotations = std::collections::HashMap::new(); identity.write(&mut annotations); let mut reloaded = diff --git a/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs b/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs index 636fff35b8..6aedbbe5f1 100644 --- a/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs +++ b/crates/openshell-server/src/persistence/mutation_lock_pg_tests.rs @@ -89,6 +89,8 @@ async fn postgres_concurrent_sandbox_creates_with_ssh_identity_do_not_exhaust_lo gateway_expires_at: 0, sandbox_token: SecretJwt::parse("sandbox-token").unwrap(), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, @@ -211,6 +213,8 @@ fn ssh_launch_authentication() -> openshell_core::jwt::SandboxLaunchAuthenticati gateway_expires_at: 0, sandbox_token: SecretJwt::parse("sandbox-token").unwrap(), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-server/src/ssh_identity.rs b/crates/openshell-server/src/ssh_identity.rs index 5b6b0ee4c7..3a569d5e97 100644 --- a/crates/openshell-server/src/ssh_identity.rs +++ b/crates/openshell-server/src/ssh_identity.rs @@ -85,6 +85,8 @@ mod tests { gateway_expires_at: 0, sandbox_token: SecretJwt::parse("sandbox-token").unwrap(), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-spiffe/src/lib.rs b/crates/openshell-spiffe/src/lib.rs index 07ea123e43..334a58fea8 100644 --- a/crates/openshell-spiffe/src/lib.rs +++ b/crates/openshell-spiffe/src/lib.rs @@ -87,8 +87,7 @@ pub fn trust_domain(subject: &str) -> Option<&str> { /// Longest SPIFFE ID the SPIFFE specification permits. const MAX_SPIFFE_ID_BYTES: usize = 2048; -/// Operator-configured prefix of the stable SPIFFE IDs the gateway requests -/// for sandboxes using shared supervision. +/// Operator-configured prefix of stable sandbox SPIFFE IDs. /// /// A sandbox's ID is `/gateway//sandbox/`. /// Both IDs must already be valid SPIFFE path segments; nothing is encoded, @@ -142,6 +141,24 @@ impl SandboxSpiffeIdPrefix { } Ok(id) } + + /// Build the SPIFFE ID for one supervisor launch. + pub fn supervisor_launch_spiffe_id( + &self, + gateway_id: &str, + sandbox_id: &str, + launch_id: &str, + ) -> Result { + if !is_spiffe_path_segment(launch_id) { + return Err("supervisor launch ID must be a valid SPIFFE path segment".into()); + } + let sandbox = self.sandbox_spiffe_id(gateway_id, sandbox_id)?; + let id = format!("{sandbox}/launch/{launch_id}"); + if id.len() > MAX_SPIFFE_ID_BYTES { + return Err("supervisor launch SPIFFE ID exceeds 2048 bytes".into()); + } + Ok(id) + } } /// A JWT-SVID verified for a sandbox's stable SPIFFE ID and one audience. @@ -151,7 +168,7 @@ pub struct SandboxJwtSvid { pub spiffe_id: String, /// The signed token. It is a credential and never printed. pub token: String, - /// The verified `exp` claim, in Unix seconds. + /// When the verified identity expires for the grant, in Unix seconds. pub expires_at: i64, } @@ -297,6 +314,12 @@ mod tests { prefix.sandbox_spiffe_id("gw", "4f1c2b3a-9d8e").unwrap(), "spiffe://example.org/openshell/gateway/gw/sandbox/4f1c2b3a-9d8e" ); + assert_eq!( + prefix + .supervisor_launch_spiffe_id("gw", "4f1c2b3a-9d8e", "launch-1") + .unwrap(), + "spiffe://example.org/openshell/gateway/gw/sandbox/4f1c2b3a-9d8e/launch/launch-1" + ); for invalid in [ "spiffe://Example.org", "spiffe://example.org/", diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 0f5b2ec5e2..3bfd32ba82 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -158,6 +158,8 @@ impl TestSetup { gateway_expires_at: 0, sandbox_token: SecretJwt::parse("test-sandbox-token").unwrap(), sandbox_expires_at: i64::MAX, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index b3c56facda..3378a0c94b 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -271,6 +271,8 @@ async fn config_push_regression_legacy_gateway_never_observes_ready_before_workl gateway_expires_at: 0, sandbox_token: openshell_core::jwt::SecretJwt::parse("test-sandbox-token").unwrap(), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 3ec4035113..2a5d361256 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -4817,6 +4817,8 @@ mod tests { sandbox_token: openshell_core::jwt::SecretJwt::parse("test-sandbox-token") .expect("token"), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: None, ocsf_otlp_headers: None, diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index b455799f1e..906b8874be 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -1283,6 +1283,8 @@ mod tests { gateway_expires_at: 0, sandbox_token: SecretJwt::parse("test-sandbox-token").unwrap(), sandbox_expires_at: 0, + provider_spiffe_id: None, + provider_launch_spiffe_id: None, ssh_host_private_key: None, traces_otlp_headers: secret("lane=traces"), ocsf_otlp_headers: secret("lane=ocsf"), diff --git a/proto/driver_launch.proto b/proto/driver_launch.proto index c05fe0e775..5fba813ff1 100644 --- a/proto/driver_launch.proto +++ b/proto/driver_launch.proto @@ -59,6 +59,9 @@ message ConfigureRequest { // resource labels to the gateway. Empty means the defaults. A typed // `resource_admission_policy` is reserved for a later protocol version. string resource_admission_policy_json = 7; + // Whether the gateway selected verified provider workload identity. + // Managed Docker and Podman require an explicit true to qualify for this mode. + optional bool verified_provider_workload_identity = 8; } message ConfigureResponse {} From a48bc303478ea76ce5d69e2dd09725ff83a58359 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:27:20 +0530 Subject: [PATCH 2/5] feat(supervisor): present workload assertions for provider grants Let a dedicated supervisor prove its sandbox and launch identity when it asks the gateway for a provider access token. - GetSandboxProviderAccessToken accepts two optional JWT-SVIDs. Shared supervisors keep omitting them. - When the launch bundle carries provider SPIFFE IDs, the supervisor fetches one JWT-SVID for the stable sandbox ID and the provider audience, and one for the launch ID and the launch audience. It sends both over TLS or numeric loopback only. - The supervisor reuses a pair for up to five seconds, stops one second before either expires, and never reuses assertions that carry a JWT ID. - The provider audience rule moves to openshell-core so the supervisor and the gateway derive it the same way. A whitespace-only configured audience now derives the issuer on the direct path too. - A probe subcommand takes a Workload API socket path and reports whether the supervisor can see it, so drivers can qualify a supervisor before launch. Bundles without provider SPIFFE IDs keep the existing direct exchange. Signed-off-by: Shiju --- crates/openshell-core/build.rs | 1 + crates/openshell-core/src/grpc_client.rs | 97 ++++- crates/openshell-core/src/oauth.rs | 95 +++++ crates/openshell-core/src/proto/mod.rs | 28 ++ .../openshell-core/src/sandbox_generation.rs | 6 + .../src/proto_json.rs | 8 + crates/openshell-server/src/grpc/provider.rs | 2 + .../src/grpc/provider/access_token.rs | 2 + crates/openshell-server/src/storage_proto.rs | 4 +- crates/openshell-supervisor-network/README.md | 28 +- .../openshell-supervisor-network/src/run.rs | 8 +- .../src/token_grant.rs | 343 ++++++++++++------ crates/openshell-supervisor/src/main.rs | 121 +++++- .../openshell-supervisor/src/shared_host.rs | 4 +- .../kubernetes_shared_supervisor_spiffe.rs | 2 + proto/openshell.proto | 11 +- 16 files changed, 616 insertions(+), 144 deletions(-) diff --git a/crates/openshell-core/build.rs b/crates/openshell-core/build.rs index 2779e78fb9..fa51bace66 100644 --- a/crates/openshell-core/build.rs +++ b/crates/openshell-core/build.rs @@ -52,6 +52,7 @@ fn main() -> Result<(), Box> { let mut proto_config = tonic_prost_build::Config::new(); // Keep optional grant evidence off sandbox lifecycle futures' stacks. proto_config.boxed(".openshell.v1.SandboxStatus.last_token_grant_failure"); + proto_config.skip_debug([".openshell.v1.GetSandboxProviderAccessTokenRequest"]); let proto_include = if use_vendored_protoc { proto_config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); Some(protoc_bin_vendored::include_path()?) diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 2429f255cc..fec2217c71 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -1747,6 +1747,13 @@ pub async fn exchange_provider_subject_token( )) } +/// A dedicated supervisor's JWT-SVIDs for the provider and launch audiences. +#[derive(Clone)] +pub struct ProviderWorkloadAssertions { + pub jwt_svid: String, + pub launch_jwt_svid: String, +} + /// Final provider access tokens for one sandbox instance over one reused /// gateway channel. /// @@ -1782,9 +1789,20 @@ impl SandboxProviderTokenClient { } } - /// Obtain only the final access token; the gateway selects and verifies - /// the sandbox identity and resolves all grant parameters from its - /// configuration. + /// Validate the gateway before fetching a local workload assertion. + /// A plaintext endpoint must identify loopback without DNS. + /// + /// # Errors + /// Returns a configuration failure for an invalid gateway URL or a + /// remote plaintext endpoint. + pub fn require_attested_transport(&self) -> std::result::Result<(), TokenGrantFailure> { + let (endpoint, _) = self.gateway.as_ref().map_err(|failure| *failure)?; + validate_attested_token_grant_transport(endpoint) + } + + /// Obtain the final access token. The gateway verifies the sandbox + /// identity and resolves grant parameters from its configuration. + /// A dedicated supervisor can supply its attested JWT-SVIDs. /// /// One deadline bounds connection readiness and the call. Network failures /// do not serialize channel initialization for concurrent requests. @@ -1792,9 +1810,16 @@ impl SandboxProviderTokenClient { pub async fn get_access_token( &self, credential_key: &str, + assertions: Option, request_id: Option<&str>, ) -> std::result::Result { let (endpoint, gateway) = self.gateway.as_ref().map_err(|failure| *failure)?; + let (jwt_svid, launch_jwt_svid) = if let Some(assertions) = assertions { + self.require_attested_transport()?; + (Some(assertions.jwt_svid), Some(assertions.launch_jwt_svid)) + } else { + (None, None) + }; // Like connect(), refuse locally revoked sandbox instance credentials // before the call; the response boundary rejects them again. let unavailable = || gateway_grant_failure(TokenGrantFailureKind::Unavailable); @@ -1805,6 +1830,8 @@ impl SandboxProviderTokenClient { .ok_or_else(|| gateway_grant_failure(TokenGrantFailureKind::Configuration))?; let mut request = tonic::Request::new(crate::proto::GetSandboxProviderAccessTokenRequest { credential_key: key, + jwt_svid, + launch_jwt_svid, }); if let Some(value) = request_id.and_then(|value| value.parse().ok()) { request.metadata_mut().insert("x-request-id", value); @@ -1886,6 +1913,23 @@ pub fn token_grant_gateway_endpoint( Ok(endpoint) } +/// Check the transport of an authority parsed by [`token_grant_gateway_endpoint`]. +/// Plain HTTP is permitted only on a numeric loopback address. +pub fn validate_attested_token_grant_transport( + endpoint: &url::Url, +) -> std::result::Result<(), TokenGrantFailure> { + let direct_loopback = match endpoint.host() { + Some(url::Host::Ipv4(address)) => address.is_loopback(), + Some(url::Host::Ipv6(address)) => address.is_loopback(), + _ => false, + }; + if endpoint.scheme() == "https" || (endpoint.scheme() == "http" && direct_loopback) { + Ok(()) + } else { + Err(gateway_grant_failure(TokenGrantFailureKind::Configuration)) + } +} + fn provider_subject_token_exchange_result( inner: crate::proto::ExchangeProviderSubjectTokenResponse, ) -> std::result::Result { @@ -1993,8 +2037,8 @@ mod token_grant_exchange_tests { ); let started = tokio::time::Instant::now(); let results: [_; 2] = tokio::join!( - client.get_access_token("api.test\t443\t/\towner\tprovider:token", None), - client.get_access_token("api.test\t443\t/\towner\tprovider:token", None), + client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None), + client.get_access_token("api.test\t443\t/\towner\tprovider:token", None, None), ) .into(); for result in results { @@ -2016,10 +2060,51 @@ mod token_grant_exchange_tests { TokenSource::Env, ), )); - let failure = invalid.get_access_token("key", None).await.err().unwrap(); + let failure = invalid + .get_access_token("key", None, None) + .await + .err() + .unwrap(); assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration); } + #[tokio::test] + async fn access_token_client_keeps_assertions_off_nonlocal_plaintext() { + let client = |url| { + SandboxProviderTokenClient::new(GatewayEndpoint::new( + url, + GatewayCredentials::new( + AsciiMetadataValue::from_static("Bearer test"), + TokenSource::Env, + ), + )) + }; + for url in ["http://192.0.2.2:8080", "http://localhost:8080"] { + let client = client(url); + let failure = client + .get_access_token( + "api.test\t443\t/\towner\tprovider:token", + Some(ProviderWorkloadAssertions { + jwt_svid: "oauth-assertion-canary".into(), + launch_jwt_svid: "launch-assertion-canary".into(), + }), + None, + ) + .await + .err() + .expect("nonlocal plaintext must reject a workload assertion"); + assert_eq!(failure.kind(), TokenGrantFailureKind::Configuration); + assert!(client.client.get().is_none()); + } + for url in [ + "https://gateway.test:8080", + "http://127.0.0.1:8080", + "http://[::1]:8080", + ] { + assert!(client(url).require_attested_transport().is_ok()); + } + } + #[test] fn gateway_response_keeps_expiration_and_rejects_invalid_duration() { let response = |seconds, nanos| crate::proto::ExchangeProviderSubjectTokenResponse { diff --git a/crates/openshell-core/src/oauth.rs b/crates/openshell-core/src/oauth.rs index 7a9c2618f8..5acab801c5 100644 --- a/crates/openshell-core/src/oauth.rs +++ b/crates/openshell-core/src/oauth.rs @@ -267,6 +267,42 @@ pub fn effective_token_type(token_type: &str) -> &str { } } +/// The supervisor requests this JWT-SVID audience and the gateway verifies the +/// same value, so both sides must derive it here. +pub fn effective_jwt_svid_audience(token_endpoint: &str, jwt_svid_audience: &str) -> String { + if jwt_svid_audience.trim().is_empty() { + derive_issuer_from_token_endpoint(token_endpoint) + } else { + jwt_svid_audience.to_string() + } +} + +/// Derive the issuer/realm URL from a token endpoint URL. +/// +/// For Keycloak token endpoints like: +/// `https://auth.example.com/realms/openshell/protocol/openid-connect/token` +/// Returns: +/// `https://auth.example.com/realms/openshell` +/// +/// This is used as the JWT-SVID audience claim when authenticating to the +/// authorization server via JWT client assertion (RFC 7523). +fn derive_issuer_from_token_endpoint(token_endpoint: &str) -> String { + // For Keycloak, strip everything after /realms/{realm-name} + if let Some(realms_idx) = token_endpoint.find("/realms/") { + // Find the next path segment after the realm name + let after_realms = &token_endpoint[realms_idx + "/realms/".len()..]; + if let Some(slash_idx) = after_realms.find('/') { + // Return everything up to (but not including) the next slash + let realm_end = realms_idx + "/realms/".len() + slash_idx; + return token_endpoint[..realm_end].to_string(); + } + } + + // Fallback: if we can't parse it, use the full token endpoint + // This works for some OAuth2 servers that accept the token endpoint as aud + token_endpoint.to_string() +} + /// Cache lifetime for a granted access token. /// /// A configured override is used exactly, including zero to disable caching. @@ -987,6 +1023,65 @@ mod tests { assert_eq!(request.request_id, None); } + #[test] + fn jwt_svid_audience_is_the_configured_value_or_the_derived_issuer() { + const OPENSHELL_REALM: &str = + "https://auth.example.com/realms/openshell/protocol/openid-connect/token"; + const SHORT_REALM: &str = "https://kc.example/realms/a/protocol/openid-connect/token"; + + for (case, token_endpoint, issuer) in [ + ( + "keycloak realm", + OPENSHELL_REALM, + "https://auth.example.com/realms/openshell", + ), + ( + "another keycloak realm", + "https://auth.example.com/realms/production/protocol/openid-connect/token", + "https://auth.example.com/realms/production", + ), + // Fallback: returns the full token endpoint + ( + "non-keycloak fallback", + "https://oauth.example.com/token", + "https://oauth.example.com/token", + ), + ] { + assert_eq!( + derive_issuer_from_token_endpoint(token_endpoint), + issuer, + "{case}" + ); + } + + for (case, token_endpoint, configured, audience) in [ + ( + "explicit override", + OPENSHELL_REALM, + "spiffe://custom-audience", + "spiffe://custom-audience", + ), + ( + "empty value", + SHORT_REALM, + "", + "https://kc.example/realms/a", + ), + ( + "blank value", + SHORT_REALM, + " ", + "https://kc.example/realms/a", + ), + ] { + assert_eq!( + effective_jwt_svid_audience(token_endpoint, configured), + audience, + "{case}" + ); + } + } + #[test] fn token_endpoint_url_allows_https_loopback_and_in_cluster_http() { for endpoint in [ diff --git a/crates/openshell-core/src/proto/mod.rs b/crates/openshell-core/src/proto/mod.rs index c1dd2f5c7e..1bb86d9622 100644 --- a/crates/openshell-core/src/proto/mod.rs +++ b/crates/openshell-core/src/proto/mod.rs @@ -94,6 +94,20 @@ pub use openshell::*; pub use sandbox::v1::*; pub use test::ObjectForTest; +impl std::fmt::Debug for GetSandboxProviderAccessTokenRequest { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("GetSandboxProviderAccessTokenRequest") + .field("credential_key", &self.credential_key) + .field("jwt_svid", &self.jwt_svid.as_ref().map(|_| "[REDACTED]")) + .field( + "launch_jwt_svid", + &self.launch_jwt_svid.as_ref().map(|_| "[REDACTED]"), + ) + .finish() + } +} + impl SandboxPolicy { /// Returns whether the explicitly present Cedar message selects the Cedar engine. #[must_use] @@ -134,6 +148,20 @@ mod tests { use super::SandboxPolicy; + #[test] + fn provider_access_token_request_debug_redacts_the_assertion() { + let request = super::GetSandboxProviderAccessTokenRequest { + credential_key: "configured-key".into(), + jwt_svid: Some("oauth-assertion-canary".into()), + launch_jwt_svid: Some("launch-assertion-canary".into()), + }; + let output = format!("{request:?}"); + assert!(output.contains("configured-key")); + assert!(output.contains("[REDACTED]")); + assert!(!output.contains("oauth-assertion-canary")); + assert!(!output.contains("launch-assertion-canary")); + } + #[test] fn empty_cedar_message_preserves_format_and_policy_identity() { let yaml = SandboxPolicy::default(); diff --git a/crates/openshell-core/src/sandbox_generation.rs b/crates/openshell-core/src/sandbox_generation.rs index cf5e5dedf5..13d867dfe7 100644 --- a/crates/openshell-core/src/sandbox_generation.rs +++ b/crates/openshell-core/src/sandbox_generation.rs @@ -55,6 +55,12 @@ impl SandboxGenerationId { &self.0 } + /// Audience requested for the JWT-SVID that accompanies the OAuth assertion. + #[must_use] + pub fn provider_spiffe_audience(&self) -> String { + format!("urn:openshell:provider-grants:launch:{self}") + } + #[must_use] pub fn into_string(self) -> String { self.0 diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index f34c791adc..e880266580 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -411,6 +411,14 @@ mod tests { "openshell.v1.GetSandboxProviderEnvironmentResponse", "environment", ), + ( + "openshell.v1.GetSandboxProviderAccessTokenRequest", + "jwt_svid", + ), + ( + "openshell.v1.GetSandboxProviderAccessTokenRequest", + "launch_jwt_svid", + ), ] { let message = codec.message_descriptor(message_name).unwrap(); let field = message.get_field_by_name(field_name).unwrap(); diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index e14424bc9c..adc2a7617d 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -6568,6 +6568,8 @@ pub(super) mod tests { let mut request = Request::new( openshell_core::proto::GetSandboxProviderAccessTokenRequest { credential_key: SECRET.to_string(), + jwt_svid: None, + launch_jwt_svid: None, }, ); request diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index 2936803b0a..e703e49089 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -688,6 +688,8 @@ mod tests { ] { let mut request = Request::new(GetSandboxProviderAccessTokenRequest { credential_key: "untrusted".into(), + jwt_svid: None, + launch_jwt_svid: None, }); request.extensions_mut().insert(principal); let error = handle(&state, request).await.unwrap_err(); diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..3c2d674ba4 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -251,8 +251,10 @@ mod tests { // and the public/durable overlap remain unchanged. // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. + // Provider access token requests accept two optional supervisor SVIDs. + // The fields are public-only and older requests still omit them. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "7e0830b5850c3fde8deb4ae9b1ff05c83a52bf9b8615e5a0c5020ee86e3727fb"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = diff --git a/crates/openshell-supervisor-network/README.md b/crates/openshell-supervisor-network/README.md index c50383d556..b50167f5a1 100644 --- a/crates/openshell-supervisor-network/README.md +++ b/crates/openshell-supervisor-network/README.md @@ -26,17 +26,23 @@ several sandbox instances. `run_networking` selects the instance's token grant resolver once from its identity source; a token acquired for one sandbox is never served to another. -A dedicated supervisor uses `SpiffeTokenGrantResolver` with its SPIFFE Workload -API socket. That resolver owns the instance's token cache and HTTP client and -uses the gateway only for the intermediate exchange of RFC 8693 grants. -Without a socket, its grants fail closed. Shared sandbox instances use -`GatewayTokenGrantResolver`, which holds only the instance's authenticated -gateway channel, connected on the first grant and reused. Each admitted -operation forwards a configured dynamic credential key and request ID; the -gateway derives the sandbox identity, -validates current authorization, resolves grant parameters, and obtains the -final access token, which the resolver validates. No SPIRE client, SVID, -intermediate token, or grant cache is used in the shared supervisor. +A dedicated supervisor can use `SpiffeTokenGrantResolver` with its SPIFFE +Workload API socket. That resolver owns the instance's token cache and HTTP +client and uses the gateway for the intermediate exchange of RFC 8693 grants. + +`GatewayTokenGrantResolver` sends a configured credential key and request ID +over a reused, authenticated gateway channel. A dedicated supervisor with +provider workload identity enabled fetches two JWT-SVIDs for its expected +SPIFFE identities. The stable sandbox ID uses the provider audience and the +separate supervisor launch ID uses the launch audience. +The Workload API issuer authorizes the supervisor for both IDs. The +resolver can reuse assertions without a JWT ID for the same provider +audience for up to five seconds, stopping at least one second before either +assertion expires. It forwards both to the gateway over TLS or loopback. +For shared supervision, the gateway obtains the JWT-SVID directly. In both +cases, the gateway checks the assertions, active session, and grant before +returning the final provider access token. + `mise run e2e:kubernetes:shared-supervisor-spiffe` exercises the gateway's SPIFFE Broker API flow against a real server and agent. A process hosting several instances serves diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index b6b8b7cf59..f899c2d822 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -38,8 +38,8 @@ use crate::l7::tls::{ use crate::l7::token_grant_injection::TokenGrantResolver; use crate::policy_local::{DenialLogSource, PolicyLocalContext}; use crate::proxy::ProxyHandle; -pub use crate::token_grant::ProviderIdentitySource; use crate::token_grant::{GatewayTokenGrantResolver, SpiffeTokenGrantResolver}; +pub use crate::token_grant::{ProviderIdentitySource, ProviderWorkloadIdentity}; use openshell_core::endpoint_status::EndpointObservationSender; use openshell_core::grpc_client::GatewayEndpoint; @@ -319,12 +319,12 @@ pub async fn run_networking( } = instance; // Choose how this instance obtains provider tokens once, for every grant. let token_grants: Arc = match (provider_identity, gateway.clone()) { - (ProviderIdentitySource::Gateway, Some(gateway)) => { - Arc::new(GatewayTokenGrantResolver::new(gateway)) + (ProviderIdentitySource::Gateway(identity), Some(gateway)) => { + Arc::new(GatewayTokenGrantResolver::new(gateway, identity)) } // Nothing can issue this sandbox's tokens without a gateway; a // resolver without a workload identity fails every grant closed. - (ProviderIdentitySource::Gateway, None) => Arc::new(SpiffeTokenGrantResolver::new( + (ProviderIdentitySource::Gateway(_), None) => Arc::new(SpiffeTokenGrantResolver::new( None, sandbox_id.clone(), None, diff --git a/crates/openshell-supervisor-network/src/token_grant.rs b/crates/openshell-supervisor-network/src/token_grant.rs index df2a25a559..8ca76dcfee 100644 --- a/crates/openshell-supervisor-network/src/token_grant.rs +++ b/crates/openshell-supervisor-network/src/token_grant.rs @@ -32,34 +32,39 @@ //! Each sandbox instance selects one resolver when its networking starts, from //! its [`ProviderIdentitySource`]. A token is never served to another sandbox. //! -//! A dedicated supervisor uses a [`SpiffeTokenGrantResolver`], which presents -//! the supervisor's own identity from a SPIFFE Workload API socket and owns -//! the instance's token cache and HTTP client. Without a socket, its grants -//! fail closed with a configuration failure. A shared supervisor uses a -//! [`GatewayTokenGrantResolver`], which requests only the final provider access -//! token from the gateway; the gateway owns SPIRE acquisition, exchange, and -//! caching. +//! A dedicated supervisor can use a [`SpiffeTokenGrantResolver`] to perform +//! the exchange with its local SPIFFE identity. Shared supervisors and +//! dedicated supervisors with provider workload identity use a +//! [`GatewayTokenGrantResolver`] to obtain the final access token. +//! The gateway obtains the SPIFFE assertion for shared supervisors and +//! verifies both assertions supplied by an opted-in dedicated supervisor. use std::collections::HashMap; use std::future::Future; use std::path::PathBuf; use std::pin::Pin; use std::sync::{Arc, RwLock}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; -use openshell_core::grpc_client::{GatewayEndpoint, SandboxProviderTokenClient}; +use openshell_core::grpc_client::{ + GatewayEndpoint, ProviderWorkloadAssertions, SandboxProviderTokenClient, +}; use openshell_core::oauth::{ self, ACCESS_TOKEN_TYPE, OAuthTokenResponse, TokenExchangeParams, TokenGrantClient, - TokenGrantParams, effective_client_assertion_type, effective_token_type, token_cache_ttl, + TokenGrantParams, effective_client_assertion_type, effective_jwt_svid_audience, + effective_token_type, token_cache_ttl, }; use openshell_core::proto::ProviderCredentialTokenGrantType; use openshell_core::token_grant_failure::{ - TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, + TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, WORKLOAD_IDENTITY_CALL_TIMEOUT, }; -use spiffe::{WorkloadApiClient, WorkloadApiError}; +use spiffe::{JwtSvid, SpiffeId, WorkloadApiClient, WorkloadApiError}; +use tokio::sync::OnceCell; use crate::l7::token_grant_injection::{TokenGrantRequest, TokenGrantResolver}; +const WORKLOAD_ASSERTION_REUSE: Duration = Duration::from_secs(5); + /// Cached access token with expiration metadata. #[derive(Clone)] struct CachedToken { @@ -112,9 +117,9 @@ pub enum ProviderIdentitySource { /// Workload API socket, for a supervisor dedicated to one sandbox. /// Without a socket, every grant fails closed. WorkloadApi(Option), - /// Request final tokens from the gateway, which owns the sandbox's - /// workload identity. - Gateway, + /// Request final tokens from the gateway. Dedicated supervision supplies + /// its own JWT-SVIDs when provider workload identity is enabled. + Gateway(Option), } impl Default for ProviderIdentitySource { @@ -123,6 +128,15 @@ impl Default for ProviderIdentitySource { } } +/// Workload API settings supplied to one dedicated supervisor launch. +#[derive(Debug)] +pub struct ProviderWorkloadIdentity { + pub workload_api_socket: Option, + pub spiffe_id: String, + pub launch_spiffe_id: String, + pub launch_audience: String, +} + /// Provider token grants acquired with this supervisor's SPIFFE identity. /// /// The cache, HTTP connection pool, gateway credentials, sandbox ID, and @@ -161,7 +175,11 @@ impl SpiffeTokenGrantResolver { .workload_api_socket .as_deref() .ok_or_else(configuration_failure)?; - fetch_jwt_svid_from_socket(socket_path, audience).await + connect_workload_api(socket_path) + .await? + .fetch_jwt_token([audience], None) + .await + .map_err(workload_api_failure) } /// Obtain an `OAuth2` access token for a provider using JWT client assertion grant. @@ -286,24 +304,147 @@ impl TokenGrantResolver for SpiffeTokenGrantResolver { } } -/// Final provider access tokens from the gateway, for a sandbox instance whose -/// supervisor holds no workload identity of its own. +/// Final provider access tokens from the gateway. /// -/// It forwards only the credential key and request ID over the instance's -/// reused authenticated gateway connection and validates the returned token. -/// The gateway authorizes, acquires, exchanges, and caches on every request; -/// this resolver holds no cache, SVID, intermediate token, or HTTP client. +/// The resolver forwards the credential key and, for dedicated workload +/// identity, two JWT-SVIDs. The gateway verifies both assertions on every +/// request, including when this resolver reuses a recently fetched pair. pub struct GatewayTokenGrantResolver { gateway: SandboxProviderTokenClient, + workload_identity: Option, + workload_api_client: OnceCell, + cached_assertions: RwLock>, +} + +struct CachedWorkloadAssertions { + audience: String, + reuse_until: Instant, + refresh_at_ms: i64, + assertions: ProviderWorkloadAssertions, +} + +impl CachedWorkloadAssertions { + fn reusable_for(&self, audience: &str, now: Instant, now_ms: i64) -> bool { + self.audience == audience && now < self.reuse_until && now_ms < self.refresh_at_ms + } } impl GatewayTokenGrantResolver { #[must_use] - pub fn new(gateway: GatewayEndpoint) -> Self { + pub fn new( + gateway: GatewayEndpoint, + workload_identity: Option, + ) -> Self { Self { gateway: SandboxProviderTokenClient::new(gateway), + workload_identity, + workload_api_client: OnceCell::new(), + cached_assertions: RwLock::new(None), } } + + async fn fetch_dedicated_assertions( + &self, + identity: &ProviderWorkloadIdentity, + request: &TokenGrantRequest<'_>, + ) -> Result { + self.gateway.require_attested_transport()?; + let socket = identity + .workload_api_socket + .as_deref() + .filter(|path| path.is_absolute()) + .ok_or_else(configuration_failure)?; + let spiffe_id = + SpiffeId::try_from(identity.spiffe_id.as_str()).map_err(|_| configuration_failure())?; + let launch_spiffe_id = SpiffeId::try_from(identity.launch_spiffe_id.as_str()) + .map_err(|_| configuration_failure())?; + let audience = + effective_jwt_svid_audience(request.token_endpoint, request.jwt_svid_audience); + if spiffe_id == launch_spiffe_id || audience == identity.launch_audience { + return Err(configuration_failure()); + } + if let Ok(cache) = self.cached_assertions.read() + && let Some(cached) = cache.as_ref() + && cached.reusable_for(&audience, Instant::now(), current_time_ms()) + { + return Ok(cached.assertions.clone()); + } + tokio::time::timeout(WORKLOAD_IDENTITY_CALL_TIMEOUT, async { + let client = self + .workload_api_client + .get_or_try_init(|| connect_workload_api(socket)) + .await?; + // Workload API attestation controls entitlement to the SPIFFE ID. + let (provider_svid, launch_svid) = tokio::try_join!( + client.fetch_jwt_svid([audience.as_str()], Some(&spiffe_id)), + client.fetch_jwt_svid([identity.launch_audience.as_str()], Some(&launch_spiffe_id)), + ) + .map_err(workload_api_failure)?; + let provider_expiry = workload_assertion_expiry(&provider_svid, &spiffe_id, &audience)?; + let launch_expiry = workload_assertion_expiry( + &launch_svid, + &launch_spiffe_id, + &identity.launch_audience, + )?; + let assertions = ProviderWorkloadAssertions { + jwt_svid: provider_svid.token().to_owned(), + launch_jwt_svid: launch_svid.token().to_owned(), + }; + if assertion_allows_reuse(&assertions.jwt_svid) + && assertion_allows_reuse(&assertions.launch_jwt_svid) + && let Ok(mut cache) = self.cached_assertions.write() + { + *cache = Some(CachedWorkloadAssertions { + audience, + reuse_until: Instant::now() + WORKLOAD_ASSERTION_REUSE, + refresh_at_ms: provider_expiry.min(launch_expiry).saturating_sub(1_000), + assertions: assertions.clone(), + }); + } + Ok(assertions) + }) + .await + .map_err(|_| { + TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::WorkloadIdentity, + ) + })? + } +} + +// An issuer can add a JWT ID for recipients that require a fresh assertion. +fn assertion_allows_reuse(token: &str) -> bool { + use base64::Engine as _; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + + let Some(payload) = token.split('.').nth(1) else { + return false; + }; + let Ok(payload) = URL_SAFE_NO_PAD.decode(payload) else { + return false; + }; + serde_json::from_slice::(&payload) + .is_ok_and(|claims| claims.get("jti").is_none()) +} + +// Check the response before local reuse. The gateway verifies both signatures. +fn workload_assertion_expiry( + svid: &JwtSvid, + expected_id: &SpiffeId, + audience: &str, +) -> Result { + let expires_at_ms = svid.expiry().unix_timestamp().saturating_mul(1_000); + if svid.spiffe_id() == expected_id + && svid.audience() == [audience] + && expires_at_ms > current_time_ms() + { + return Ok(expires_at_ms); + } + Err(TokenGrantFailure::new( + TokenGrantFailureKind::WorkloadIdentityRejected, + TokenGrantStage::WorkloadIdentity, + )) } impl TokenGrantResolver for GatewayTokenGrantResolver { @@ -312,9 +453,13 @@ impl TokenGrantResolver for GatewayTokenGrantResolver { request: TokenGrantRequest<'a>, ) -> Pin> + Send + 'a>> { Box::pin(async move { + let assertions = match &self.workload_identity { + Some(identity) => Some(self.fetch_dedicated_assertions(identity, &request).await?), + None => None, + }; let token = self .gateway - .get_access_token(request.provider_key, Some(request.request_id)) + .get_access_token(request.provider_key, assertions, Some(request.request_id)) .await?; validate_access_token(&token.access_token)?; Ok(token.access_token) @@ -385,24 +530,11 @@ where Ok(token_response.access_token) } -/// Fetch a JWT-SVID from the SPIRE agent for token grant authentication. -/// -/// The JWT-SVID is used as the client assertion in the `OAuth2` grant request. -async fn fetch_jwt_svid_from_socket( +async fn connect_workload_api( socket_path: &std::path::Path, - audience: &str, -) -> Result { +) -> Result { let endpoint = openshell_spiffe::workload_api_endpoint(socket_path); - - // Connect to SPIRE agent - let client = WorkloadApiClient::connect_to(&endpoint) - .await - .map_err(workload_api_failure)?; - - // Fetch JWT-SVID with token service audience - // None = use the sandbox's default SPIFFE ID - client - .fetch_jwt_token([audience], None) + WorkloadApiClient::connect_to(&endpoint) .await .map_err(workload_api_failure) } @@ -472,40 +604,6 @@ async fn perform_token_exchange( pub use oauth::validate_access_token; -/// Derive the issuer/realm URL from a token endpoint URL. -/// -/// For Keycloak token endpoints like: -/// `https://auth.example.com/realms/openshell/protocol/openid-connect/token` -/// Returns: -/// `https://auth.example.com/realms/openshell` -/// -/// This is used as the JWT-SVID audience claim when authenticating to the -/// authorization server via JWT client assertion (RFC 7523). -fn derive_issuer_from_token_endpoint(token_endpoint: &str) -> String { - // For Keycloak, strip everything after /realms/{realm-name} - if let Some(realms_idx) = token_endpoint.find("/realms/") { - // Find the next path segment after the realm name - let after_realms = &token_endpoint[realms_idx + "/realms/".len()..]; - if let Some(slash_idx) = after_realms.find('/') { - // Return everything up to (but not including) the next slash - let realm_end = realms_idx + "/realms/".len() + slash_idx; - return token_endpoint[..realm_end].to_string(); - } - } - - // Fallback: if we can't parse it, use the full token endpoint - // This works for some OAuth2 servers that accept the token endpoint as aud - token_endpoint.to_string() -} - -fn effective_jwt_svid_audience(token_endpoint: &str, jwt_svid_audience: &str) -> String { - if jwt_svid_audience.is_empty() { - derive_issuer_from_token_endpoint(token_endpoint) - } else { - jwt_svid_audience.to_string() - } -} - fn parse_provider_credential_key(key: &str) -> Result<(&str, &str), TokenGrantFailure> { openshell_core::dynamic_credential_key::credential_identity(key) .and_then(|identity| identity.split_once(':')) @@ -707,6 +805,69 @@ mod tests { const TEST_REQUEST_ID: &str = "4f1c2b3a-9d8e-4c7b-a6f5-e4d3c2b1a098"; + #[test] + fn assertion_reuse_requires_matching_audience_and_both_lifetimes() { + let now = Instant::now(); + let cached = CachedWorkloadAssertions { + audience: "https://issuer.test/token".to_owned(), + reuse_until: now + WORKLOAD_ASSERTION_REUSE, + refresh_at_ms: 10_000, + assertions: ProviderWorkloadAssertions { + jwt_svid: "provider-assertion".to_owned(), + launch_jwt_svid: "launch-assertion".to_owned(), + }, + }; + assert!(cached.reusable_for(&cached.audience, now, 9_999)); + assert!(!cached.reusable_for("https://other.test/token", now, 9_999)); + assert!(!cached.reusable_for(&cached.audience, now, 10_000)); + assert!(!cached.reusable_for(&cached.audience, cached.reuse_until, 9_999)); + } + + fn unsigned_jwt(claims: &str) -> String { + use base64::Engine as _; + use base64::engine::general_purpose::URL_SAFE_NO_PAD; + + format!( + "{}.{}.signature", + URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256","kid":"key"}"#), + URL_SAFE_NO_PAD.encode(claims) + ) + } + + #[test] + fn assertion_with_a_jwt_id_requires_a_fresh_fetch() { + let with_jwt_id = unsigned_jwt(r#"{"exp":100,"jti":"unique"}"#); + assert!(assertion_allows_reuse(&unsigned_jwt(r#"{"exp":100}"#))); + assert!(!assertion_allows_reuse(&with_jwt_id)); + } + + #[test] + fn workload_assertion_expiry_requires_the_expected_id_one_audience_and_lifetime() { + const ID: &str = "spiffe://example.org/gateway/gw1/sandbox/sb1"; + const OTHER_ID: &str = "spiffe://example.org/gateway/gw1/sandbox/sb2"; + const AUDIENCE: &str = "https://kc.example/realms/a"; + const EXPIRY: i64 = 4_102_444_800; + let expected_id = SpiffeId::try_from(ID).unwrap(); + let one_audience = format!(r#"["{AUDIENCE}"]"#); + let two_audiences = format!(r#"["{AUDIENCE}","https://other.test"]"#); + let rejected = Err(TokenGrantFailureKind::WorkloadIdentityRejected); + for (sub, aud, exp, expected) in [ + (ID, &one_audience, EXPIRY, Ok(EXPIRY * 1_000)), + (OTHER_ID, &one_audience, EXPIRY, rejected), + (ID, &two_audiences, EXPIRY, rejected), + (ID, &one_audience, 1, rejected), + ] { + let claims = format!(r#"{{"sub":"{sub}","aud":{aud},"exp":{exp}}}"#); + let svid = JwtSvid::parse_insecure(&unsigned_jwt(&claims)).unwrap(); + assert_eq!( + workload_assertion_expiry(&svid, &expected_id, AUDIENCE) + .map_err(|failure| failure.kind()), + expected, + "{claims}" + ); + } + } + fn test_http_client() -> TokenGrantClient { TokenGrantClient::new().expect("token grant HTTP client") } @@ -1012,40 +1173,6 @@ mod tests { } } - #[test] - fn test_derive_issuer_from_keycloak_token_endpoint() { - let token_endpoint = - "https://auth.example.com/realms/openshell/protocol/openid-connect/token"; - let issuer = derive_issuer_from_token_endpoint(token_endpoint); - assert_eq!(issuer, "https://auth.example.com/realms/openshell"); - } - - #[test] - fn test_derive_issuer_from_https_keycloak_endpoint() { - let token_endpoint = - "https://auth.example.com/realms/production/protocol/openid-connect/token"; - let issuer = derive_issuer_from_token_endpoint(token_endpoint); - assert_eq!(issuer, "https://auth.example.com/realms/production"); - } - - #[test] - fn test_derive_issuer_fallback_for_non_keycloak() { - let token_endpoint = "https://oauth.example.com/token"; - let issuer = derive_issuer_from_token_endpoint(token_endpoint); - // Fallback: returns the full token endpoint - assert_eq!(issuer, "https://oauth.example.com/token"); - } - - #[test] - fn effective_jwt_svid_audience_prefers_explicit_override() { - let audience = effective_jwt_svid_audience( - "https://auth.example.com/realms/openshell/protocol/openid-connect/token", - "spiffe://custom-audience", - ); - - assert_eq!(audience, "spiffe://custom-audience"); - } - #[test] fn token_cache_key_varies_by_resource_audience_and_scopes() { let provider_name = "alpha.default.svc.cluster.local\t80\t\tprovider:access_token"; diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index 906b8874be..65d88a4f3f 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -16,6 +16,7 @@ use openshell_core::jwt::{ }; use openshell_core::sandbox_env::OtlpProtocol; use openshell_isolation_interface::contract::BackendDescriptor; +use openshell_supervisor_network::run::{ProviderIdentitySource, ProviderWorkloadIdentity}; use tracing::{error, info, warn}; use tracing_subscriber::EnvFilter; use tracing_subscriber::{Layer as _, layer::SubscriberExt as _, util::SubscriberInitExt as _}; @@ -497,8 +498,54 @@ fn validate_main_exit_marker(marker: Option<&Path>) -> Result<()> { Ok(()) } +/// Exit status of `provider-workload-identity-probe `. +fn provider_workload_identity_probe(args: &[String]) -> Result { + use openshell_core::driver_utils::{ + PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT, PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE, + provider_spiffe_socket_visible, + }; + + match args { + [socket] => Ok(if provider_spiffe_socket_visible(Path::new(socket)) { + PROVIDER_WORKLOAD_SOCKET_PROBE_PRESENT + } else { + PROVIDER_WORKLOAD_SOCKET_PROBE_UNAVAILABLE + }), + _ => Err(miette::miette!( + "provider workload identity probe accepts one socket path" + )), + } +} + +/// Dedicated provider identity mode selected by the launch bundle. +fn provider_identity_source( + auth_bundle: &SupervisorAuthBundle, + workload_api_socket: Option, +) -> Result { + Ok(match &auth_bundle.provider_spiffe_id { + Some(spiffe_id) => { + let launch_spiffe_id = auth_bundle + .provider_launch_spiffe_id + .clone() + .ok_or_else(|| miette::miette!("missing provider launch SPIFFE ID"))?; + ProviderIdentitySource::Gateway(Some(ProviderWorkloadIdentity { + workload_api_socket, + spiffe_id: spiffe_id.clone(), + launch_spiffe_id, + launch_audience: auth_bundle.runtime_generation.provider_spiffe_audience(), + })) + } + None => ProviderIdentitySource::WorkloadApi(workload_api_socket), + }) +} + fn main() -> Result<()> { + use openshell_core::driver_utils::PROVIDER_WORKLOAD_IDENTITY_PROBE; + let raw_args = std::env::args().collect::>(); + if raw_args.get(1).map(String::as_str) == Some(PROVIDER_WORKLOAD_IDENTITY_PROBE) { + std::process::exit(provider_workload_identity_probe(&raw_args[2..])?); + } if raw_args.get(1).map(String::as_str) == Some(DEBUG_RPC_SUBCOMMAND) { let runtime = tokio::runtime::Builder::new_current_thread() .enable_all() @@ -698,6 +745,13 @@ fn main() -> Result<()> { .map(openshell_supervisor::app_listener::Config::bind) .transpose()? .map(openshell_supervisor::app_listener::BoundListener::start); + let workload_api_socket = std::env::var_os( + openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET, + ) + .filter(|path| !path.is_empty()) + .map(PathBuf::from); + let provider_identity = + provider_identity_source(&auth_bundle, workload_api_socket)?; let config = openshell_supervisor::SandboxInstanceConfig { app_router: app_host .as_ref() @@ -734,14 +788,7 @@ fn main() -> Result<()> { args.attach_request_timeout_seconds, ), trace_context: openshell_supervisor::trace_context_from_environment(), - provider_identity: - openshell_supervisor_network::run::ProviderIdentitySource::WorkloadApi( - std::env::var_os( - openshell_core::sandbox_env::PROVIDER_SPIFFE_WORKLOAD_API_SOCKET, - ) - .filter(|path| !path.is_empty()) - .map(PathBuf::from), - ), + provider_identity, proxy_tls: openshell_supervisor_network::run::ProxyTlsFiles::from_environment(), takeover: None, supervisor_recovery_timeout_secs: None, @@ -1260,8 +1307,7 @@ mod tests { .await; } - #[test] - fn each_export_takes_its_own_settings_from_the_launch_bundle() { + fn launch_bundle() -> SupervisorAuthBundle { use openshell_core::jwt::{ CredentialEpoch, SecretJwt, SecretOtlpHeaders, SessionRotation, SupervisorAuthBundle, }; @@ -1271,7 +1317,7 @@ mod tests { ca_pem: Some(ca.to_string()), ..OtlpTlsMaterial::default() }; - let bundle = SupervisorAuthBundle { + SupervisorAuthBundle { session_id: openshell_core::SandboxSessionId::new(), runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( "generation-1", @@ -1293,7 +1339,60 @@ mod tests { traces_otlp_tls: Some(1), ocsf_otlp_tls: Some(0), agent_otlp_tls: None, + } + } + + #[test] + fn launch_bundle_selects_the_provider_identity_source() { + let socket = Some(PathBuf::from("/spiffe-workload-api/agent.sock")); + let spiffe_id = "spiffe://example.org/gateway/gw1/sandbox/sb1"; + let launch_spiffe_id = format!("{spiffe_id}/launch/l1"); + + let source = provider_identity_source(&launch_bundle(), socket.clone()).unwrap(); + assert!(matches!(source, ProviderIdentitySource::WorkloadApi(path) if path == socket)); + + let bundle = SupervisorAuthBundle { + provider_spiffe_id: Some(spiffe_id.to_owned()), + provider_launch_spiffe_id: Some(launch_spiffe_id.clone()), + ..launch_bundle() + }; + let ProviderIdentitySource::Gateway(Some(identity)) = + provider_identity_source(&bundle, socket.clone()).unwrap() + else { + panic!("both provider IDs select the gateway mode"); + }; + assert_eq!(identity.workload_api_socket, socket); + assert_eq!(identity.spiffe_id, spiffe_id); + assert_eq!(identity.launch_spiffe_id, launch_spiffe_id); + assert_eq!( + identity.launch_audience, + "urn:openshell:provider-grants:launch:generation-1" + ); + + let bundle = SupervisorAuthBundle { + provider_launch_spiffe_id: None, + ..bundle }; + assert!(provider_identity_source(&bundle, socket).is_err()); + } + + #[cfg(unix)] + #[test] + fn provider_workload_identity_probe_reports_socket_visibility() { + let directory = tempfile::tempdir().unwrap(); + let socket = directory.path().join("agent.sock"); + let _listener = std::os::unix::net::UnixListener::bind(&socket).unwrap(); + let probe = |path: PathBuf| { + provider_workload_identity_probe(&[path.into_os_string().into_string().unwrap()]) + }; + assert_eq!(probe(socket).unwrap(), 70); + assert_eq!(probe(directory.path().join("missing.sock")).unwrap(), 71); + assert!(provider_workload_identity_probe(&[]).is_err()); + } + + #[test] + fn each_export_takes_its_own_settings_from_the_launch_bundle() { + let bundle = launch_bundle(); let summary = |settings: ExportSettings<'_>| { ( diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 32108cdce4..0441835329 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -907,7 +907,9 @@ impl SharedHost { trace_context: registration.trace_context, // The gateway owns each sandbox's workload identity and returns // only final provider access tokens. - provider_identity: openshell_supervisor_network::run::ProviderIdentitySource::Gateway, + provider_identity: openshell_supervisor_network::run::ProviderIdentitySource::Gateway( + None, + ), proxy_tls: openshell_supervisor_network::run::ProxyTlsFiles { ca_certificate: Some(ca_certificate), ca_private_key: Some(ca_private_key), diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs index b89f60fd90..7d286f4057 100644 --- a/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs +++ b/e2e/rust/tests/kubernetes_shared_supervisor_spiffe.rs @@ -1009,6 +1009,8 @@ impl BrokerProbe { async fn access_token(&mut self) -> Result<(String, Duration), tonic::Status> { let request = self.request(GetSandboxProviderAccessTokenRequest { credential_key: self.credential_key.clone(), + jwt_svid: None, + launch_jwt_svid: None, }); self.client .get_sandbox_provider_access_token(request) diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..11c59cfa1a 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -658,7 +658,7 @@ service OpenShell { } // Obtain the final provider token for the authenticated sandbox session. - // SPIFFE assertions and intermediate credentials remain in the gateway. + // The gateway exchanges the JWT-SVID and returns only the final token. rpc GetSandboxProviderAccessToken(GetSandboxProviderAccessTokenRequest) returns (GetSandboxProviderAccessTokenResponse) { option (openshell.options.v1.authorization) = { auth_mode: "sandbox" }; @@ -3175,12 +3175,19 @@ message ProviderEnvironmentSnapshot { } // Supervisor-only request. Sandbox/workspace are derived from the verified -// session JWT. No caller-selected identity, endpoint, audience, or scope. +// session JWT. The gateway derives the required SPIFFE identity, endpoint, +// audience, and scope. message GetSandboxProviderAccessTokenRequest { // Opaque endpoint-bound credential key issued in the gateway's provider // configuration. Echo the configured key without supervisor-local revision // or installation decorations. Callers must not construct or parse it. string credential_key = 1; + // OAuth client assertion for the provider audience. A dedicated supervisor + // sets both JWT-SVID fields when provider workload identity is enabled. + optional string jwt_svid = 2 [(openshell.options.v1.secret) = true]; + // JWT-SVID for the supervisor launch identity and audience. Shared supervisors omit both + // fields so the gateway obtains the OAuth assertion. + optional string launch_jwt_svid = 3 [(openshell.options.v1.secret) = true]; } message GetSandboxProviderAccessTokenResponse { From 594bd13e616c60c80df296c7fe92277128d05f47 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:29:53 +0530 Subject: [PATCH 3/5] feat(gateway): name each supervisor launch in its launch bundle With provider workload identity configured, tell each dedicated supervisor which SPIFFE identities to request. - The launch bundle carries the stable sandbox SPIFFE ID and the launch SPIFFE ID. The gateway derives both from the configured prefix, its gateway ID, the sandbox ID and the sandbox's runtime generation. No new state is stored. - At startup the gateway requires the selected driver to advertise provider workload identity and names the capability when it is missing. - SpiffeWorkloadIdentityConfig holds the prefix and the gateway's Workload API socket path. Start, stop, restart and recovery are unchanged. No gateway setting enables the mode yet. Signed-off-by: Shiju --- crates/openshell-core/src/config.rs | 10 + crates/openshell-server/src/compute/mod.rs | 186 ++++++++++++++++++- crates/openshell-server/src/grpc/sandbox.rs | 2 +- crates/openshell-server/src/lib.rs | 7 +- crates/openshell-server/src/spiffe_broker.rs | 74 +++++++- 5 files changed, 272 insertions(+), 7 deletions(-) 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 From 064d09f94c4f3839b11d1bb6e2344e927ad031d5 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:32:28 +0530 Subject: [PATCH 4/5] feat(gateway): verify supervisor workload assertions for provider grants Authorize a dedicated supervisor's provider grant from its signed session and two JWT-SVIDs, then perform the OAuth exchange in the gateway. - The gateway derives the expected stable and launch SPIFFE IDs from the session's sandbox and runtime generation. It verifies both signatures against the Workload API trust bundle and requires the exact subject, a single audience, and an unexpired token for each. - The session and the provider attachment are rechecked before each OAuth exchange and before a cached or new token is returned. A stopped sandbox or a superseded generation is denied on cache hits too. - The token cache key includes the generation, the attachment epoch, the provider revision, and the resolved exchange subject. Token lifetime is capped by the session, both assertions, and the subject expiry. - Requests, cache misses, and OAuth exchanges have separate per-sandbox limits, and the gateway-wide cap scales with them, so warm grants are served while other grants wait on OAuth. - A token service timeout is shared with queued requests whatever status its response headers carried. - The stored token-exchange subject stays in the gateway, and the direct subject-exchange RPC is closed while this mode is configured. Signed-off-by: Shiju --- .../src/embedded/test_support.rs | 6 +- .../src/auth/sandbox_session.rs | 16 +- crates/openshell-server/src/grpc/provider.rs | 61 +- .../src/grpc/provider/access_token.rs | 798 +++++++++++++---- .../access_token/performance_tests.rs | 834 ++++++++++++++++++ crates/openshell-server/src/spiffe_broker.rs | 80 ++ 6 files changed, 1568 insertions(+), 227 deletions(-) create mode 100644 crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs diff --git a/crates/openshell-credential-issuer/src/embedded/test_support.rs b/crates/openshell-credential-issuer/src/embedded/test_support.rs index 1cbf8e5b91..1ff8cb7f2e 100644 --- a/crates/openshell-credential-issuer/src/embedded/test_support.rs +++ b/crates/openshell-credential-issuer/src/embedded/test_support.rs @@ -146,7 +146,11 @@ impl CredentialDriver for TestStaticCredentialDriver { responses.push(ResolvedCredential { request_id: request.request_id, value, - expiration_time: None, + expiration_time: handle.metadata.get("test_expiration_ms").map(|expiry| { + let expiry = expiry.parse().expect("test expiry in milliseconds"); + openshell_core::time::timestamp_from_millis(expiry) + .expect("test expiry timestamp") + }), }); } diff --git a/crates/openshell-server/src/auth/sandbox_session.rs b/crates/openshell-server/src/auth/sandbox_session.rs index 82f103f071..b978373ce4 100644 --- a/crates/openshell-server/src/auth/sandbox_session.rs +++ b/crates/openshell-server/src/auth/sandbox_session.rs @@ -321,11 +321,23 @@ pub async fn authorize_persisted( store: &Store, principal: &AuthenticatedSandboxSession, ) -> Result { - let (_, identity) = load_identity(store, principal).await?; + authorize_persisted_sandbox(store, principal) + .await + .map(|(_, identity)| identity) +} + +/// [`authorize_persisted`], also returning the sandbox record the identity +/// was read from. +#[allow(clippy::result_large_err)] +pub async fn authorize_persisted_sandbox( + store: &Store, + principal: &AuthenticatedSandboxSession, +) -> Result<(Sandbox, PersistedSandboxIdentity), AuthRejection> { + let (sandbox, identity) = load_identity(store, principal).await?; if principal.token_id != identity.gateway_token_id { return Err(stale_identity()); } - Ok(identity) + Ok((sandbox, identity)) } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index adc2a7617d..bb303e20c9 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -2800,7 +2800,7 @@ use crate::auth::workspace_authz::{ }; use openshell_core::oauth::{ self, TokenExchangeParams, TokenGrantClient, effective_client_assertion_type, - effective_token_type, + effective_jwt_svid_audience, effective_token_type, }; use openshell_core::token_grant_failure::{ TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, WORKLOAD_IDENTITY_CALL_TIMEOUT, @@ -4828,6 +4828,11 @@ async fn exchange_provider_subject_token_inner( ) .to_status_with_code(code)); } + if state.compute.provider_workload_identity().is_some() { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } drop(request); if req.provider.trim().is_empty() @@ -4919,7 +4924,7 @@ async fn exchange_provider_subject_token_inner( &provider, &subject_token.credential, )?; - let stored_subject_token = + let (stored_subject_token, _) = resolve_subject_token_credential(&state.credentials, &provider, &subject_token.credential) .await?; @@ -5012,29 +5017,30 @@ async fn resolve_subject_token_credential( credentials: &crate::credentials::CredentialRuntime, provider: &Provider, credential_key: &str, -) -> Result { +) -> Result<(String, Option), Status> { // Check the provider's expiry before asking a credential driver to resolve // a handle; stale stored material cannot authorize another grant attempt. - ensure_subject_token_credential_not_expired(provider, credential_key)?; + let provider_expires_at_ms = + ensure_subject_token_credential_not_expired(provider, credential_key)?; if let Some(value) = provider .credentials .get(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + return Ok((value.clone(), provider_expires_at_ms)); } if provider.credential_handles.contains_key(credential_key) { - let resolved = credentials + let mut resolved = credentials .resolve_provider_handles(provider, crate::persistence::current_time_ms()) .await .map_err(token_grant_dependency_status)?; if let Some(value) = resolved .values - .get(credential_key) + .remove(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + return Ok((value, resolved.expires_at_ms.get(credential_key).copied())); } } @@ -5044,12 +5050,12 @@ async fn resolve_subject_token_credential( fn ensure_subject_token_credential_not_expired( provider: &Provider, credential_key: &str, -) -> Result<(), Status> { +) -> Result, Status> { let expires_at_ms = provider_credential_expiration_ms(provider, credential_key)?; if expires_at_ms.is_some_and(|value| value <= crate::persistence::current_time_ms()) { return Err(token_grant_authorization_required_status()); } - Ok(()) + Ok(expires_at_ms) } /// The user's stored subject credential is absent or expired. Only the user @@ -5289,24 +5295,6 @@ async fn perform_intermediate_token_exchange( }) } -fn effective_jwt_svid_audience(token_endpoint: &str, jwt_svid_audience: &str) -> String { - if !jwt_svid_audience.trim().is_empty() { - return jwt_svid_audience.to_string(); - } - derive_issuer_from_token_endpoint(token_endpoint) -} - -fn derive_issuer_from_token_endpoint(token_endpoint: &str) -> String { - if let Some(realms_idx) = token_endpoint.find("/realms/") { - let after_realms = &token_endpoint[realms_idx + "/realms/".len()..]; - if let Some(slash_idx) = after_realms.find('/') { - let realm_end = realms_idx + "/realms/".len() + slash_idx; - return token_endpoint[..realm_end].to_string(); - } - } - token_endpoint.to_string() -} - pub(super) async fn handle_get_provider_refresh_status( state: &Arc, request: Request, @@ -6433,8 +6421,11 @@ pub(super) mod tests { let error = ensure_subject_token_credential_not_expired(&provider, "SUBJECT_TOKEN") .expect_err("the Unix epoch is a present, expired timestamp"); assert_eq!(error.code(), Code::FailedPrecondition); - ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") - .expect("an absent expiration remains non-expiring"); + assert_eq!( + ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") + .expect("an absent expiration remains non-expiring"), + None + ); } mod token_grant_failures { @@ -12191,13 +12182,21 @@ pub(super) mod tests { .await .unwrap(); provider.credential_handles = handles; + let expires_at_ms = crate::persistence::current_time_ms() + 60_000; + provider + .credential_handles + .get_mut("subject_token") + .unwrap() + .metadata + .insert("test_expiration_ms".into(), expires_at_ms.to_string()); - let subject_token = + let (subject_token, subject_expires_at_ms) = resolve_subject_token_credential(&credentials, &provider, "subject_token") .await .unwrap(); assert_eq!(subject_token, "user-token"); + assert_eq!(subject_expires_at_ms, Some(expires_at_ms)); } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index e703e49089..574770427d 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -4,14 +4,14 @@ //! Gateway-owned sandbox identity and provider-token acquisition. //! The caller selects an attached configured credential, never grant parameters. use super::{ - Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectWorkspace, Principal, - Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, Status, - TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, + Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectName, ObjectWorkspace, + Principal, Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, + Status, TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, canonical_request_id, effective_jwt_svid_audience, fetch_gateway_jwt_svid_from, get_provider_type_profile_for_scope, insert_dynamic_credentials_for_profile, jwt_exp_ms, log_token_grant_failure, oauth, perform_intermediate_token_exchange, - provider_credential_expiration_ms, resolve_subject_token_credential, - sanitize_token_grant_status, token_exchange_http_client, token_grant_configuration_status, + resolve_subject_token_credential, sanitize_token_grant_status, token_exchange_http_client, + token_grant_authorization_required_status, token_grant_configuration_status, token_grant_dependency_status, token_grant_identity_rejected, token_grant_store_status, }; use openshell_core::jwt::AuthenticatedSandboxSession; @@ -19,13 +19,22 @@ use openshell_core::proto::{ GetSandboxProviderAccessTokenRequest, GetSandboxProviderAccessTokenResponse, ProviderCredentialTokenGrant, }; -use openshell_core::token_grant_failure::BROKERED_TOKEN_GATEWAY_DEADLINE; -use openshell_spiffe::SandboxIdentityProvider; +use openshell_core::token_grant_failure::{ + BROKERED_TOKEN_GATEWAY_DEADLINE, WORKLOAD_IDENTITY_CALL_TIMEOUT, +}; +use openshell_spiffe::{SandboxIdentityProvider, SandboxJwtSvid}; use std::time::Duration; static ACCESS_TOKENS: LazyLock = LazyLock::new(IntermediateTokenCache::new); static ACQUISITIONS: LazyLock = LazyLock::new(Acquisitions::default); -static ADMISSION: LazyLock = LazyLock::new(Admission::default); +static REQUEST_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static EXCHANGE_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static MISS_ADMISSION: LazyLock = LazyLock::new(Admission::default); +const PER_SANDBOX_EXCHANGE_LIMIT: usize = 4; +const PER_SANDBOX_VERIFIED_REQUEST_LIMIT: usize = 16; +// Reserve request capacity for warm grants while other grants wait on OAuth. +const PER_SANDBOX_MISS_LIMIT: usize = + PER_SANDBOX_VERIFIED_REQUEST_LIMIT - PER_SANDBOX_EXCHANGE_LIMIT; pub(in crate::grpc) async fn handle( state: &Arc, @@ -63,10 +72,11 @@ pub(in crate::grpc) async fn handle( /// Verify the original bearer again after asynchronous work, including expiry /// and the persisted generation, epoch, active phase, and current token lineage. +/// A new launch has a new generation, so a bearer of an earlier launch fails. async fn authorize( state: &ServerState, bearer: &str, -) -> Result { +) -> Result<(AuthenticatedSandboxSession, Sandbox), Status> { let authority = state .sandbox_session_jwt_authority .as_ref() @@ -77,10 +87,11 @@ async fn authorize( if session.expires_at.saturating_mul(1000) <= crate::persistence::current_time_ms() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - crate::auth::sandbox_session::authorize_persisted(&state.store, &session) - .await - .map_err(|error| error.status)?; - Ok(session) + let (sandbox, _) = + crate::auth::sandbox_session::authorize_persisted_sandbox(&state.store, &session) + .await + .map_err(|error| error.status)?; + Ok((session, sandbox)) } /// One configured credential of an attached provider. @@ -89,6 +100,17 @@ struct ConfiguredGrant { grant: ProviderCredentialTokenGrant, /// The gateway's exact key for the credential, including its endpoint owner. key: String, + attachment_epoch: String, +} + +#[allow(clippy::result_large_err)] +fn provider_attachment<'a>(sandbox: &'a Sandbox, provider_name: &str) -> Result<&'a str, Status> { + sandbox + .spec + .as_ref() + .filter(|spec| spec.providers.iter().any(|name| name == provider_name)) + .map(|spec| spec.provider_attachment_epoch.as_str()) + .ok_or_else(|| token_grant_configuration_status(tonic::Code::PermissionDenied)) } /// Resolve the exact configured credential from the gateway's approved profile. @@ -98,7 +120,7 @@ struct ConfiguredGrant { /// generation a supervisor adds; a different or missing owner matches nothing. async fn grant_configuration( state: &ServerState, - sandbox_id: &str, + sandbox: &Sandbox, key: &str, ) -> Result { let invalid = || token_grant_configuration_status(tonic::Code::PermissionDenied); @@ -107,16 +129,7 @@ async fn grant_configuration( let identity = openshell_core::dynamic_credential_key::credential_identity(&key).ok_or_else(invalid)?; let (provider_name, _) = identity.split_once(':').ok_or_else(invalid)?; - let sandbox = state - .store - .get_message::(sandbox_id) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(invalid)?; - let spec = sandbox.spec.as_ref().ok_or_else(invalid)?; - if !spec.providers.iter().any(|name| name == provider_name) { - return Err(invalid()); - } + let attachment_epoch = provider_attachment(sandbox, provider_name)?.to_owned(); let provider = state .store .get_message_by_name::(sandbox.object_workspace(), provider_name) @@ -148,14 +161,15 @@ async fn grant_configuration( provider, grant, key, + attachment_epoch, }) } /// Bind a cached token to its runtime, configured credential, and subject. /// -/// Include the provider revision and resolved subject token, so an in-place -/// rotation of a handle-backed subject never serves a token minted from the -/// previous one. The digest is an in-memory map key and is never exposed. +/// Include the provider revision and resolved subject token. A request +/// that resolves a rotated subject gets a different key. The digest is an +/// in-memory map key and is never exposed. fn cache_key( session: &AuthenticatedSandboxSession, configured: &ConfiguredGrant, @@ -167,12 +181,13 @@ fn cache_key( .metadata .as_ref() .map_or(0, |metadata| metadata.resource_version); - let fields: [&[u8]; 11] = [ + let fields: [&[u8]; 12] = [ b"openshell-provider-access-token-v1", gateway_id.as_bytes(), session.sandbox_id.as_str().as_bytes(), session.runtime_generation.as_str().as_bytes(), &session.auth_epoch.get().to_be_bytes(), + configured.attachment_epoch.as_bytes(), configured.provider.object_id().as_bytes(), &resource_version.to_be_bytes(), configured.key.as_bytes(), @@ -202,6 +217,200 @@ struct Subject { expires_at_ms: Option, } +async fn resolve_subject( + state: &ServerState, + configured: &ConfiguredGrant, +) -> Result, Status> { + let configuration_failure = + || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let grant_type = ProviderCredentialTokenGrantType::try_from(configured.grant.grant_type) + .map_err(|_| configuration_failure())?; + if grant_type != ProviderCredentialTokenGrantType::TokenExchange { + return Ok(None); + } + let subject = configured + .grant + .subject_token + .as_ref() + .filter(|subject| subject.source == "provider_credential") + .ok_or_else(configuration_failure)?; + let (value, expires_at_ms) = resolve_subject_token_credential( + &state.credentials, + &configured.provider, + &subject.credential, + ) + .await?; + Ok(Some(Subject { + expires_at_ms, + value, + token_type: subject.subject_token_type.clone(), + })) +} + +/// Recheck the authorized grant and session after waits and before exposing +/// credentials to the issuer or returning an access token to the sandbox. +struct GrantAuthorization<'a> { + state: &'a ServerState, + bearer: &'a str, + session: &'a AuthenticatedSandboxSession, + /// The request's first snapshot. It only locates the provider; `revalidate` reads a fresh one. + sandbox: &'a Sandbox, + key: &'a str, + gateway_id: &'a str, + fingerprint: &'a str, + subject: Option<&'a Subject>, + revalidate_subject: bool, +} + +impl GrantAuthorization<'_> { + async fn revalidate(&self) -> Result, Status> { + let current = grant_configuration(self.state, self.sandbox, self.key).await?; + let resolved; + let subject = if self.revalidate_subject { + // A driver can replace a subject without changing the Provider row. + resolved = resolve_subject(self.state, ¤t).await?; + resolved.as_ref() + } else { + self.subject + }; + let subject_value = subject.map(|subject| subject.value.as_str()); + if cache_key(self.session, ¤t, subject_value, self.gateway_id)? != self.fingerprint { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + // Profile and subject lookup may await storage. Check the attachment + // and session on the same fresh snapshot afterward. + let (_, sandbox) = authorize(self.state, self.bearer).await?; + if provider_attachment(&sandbox, current.provider.object_name())? + != current.attachment_epoch + { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + let subject_expiry = [self.subject, subject] + .into_iter() + .flatten() + .filter_map(|subject| subject.expires_at_ms) + .min(); + if subject_expiry.is_some_and(|expiry| expiry <= crate::persistence::current_time_ms()) { + return Err(token_grant_authorization_required_status()); + } + Ok(subject_expiry) + } +} + +#[derive(Clone, Copy)] +enum GrantIdentity<'a> { + Broker(&'a dyn SandboxIdentityProvider), + Supervisor(&'a SandboxJwtSvid), +} + +impl GrantIdentity<'_> { + #[allow(clippy::result_large_err)] + fn cache_ttl_override( + self, + grant: &ProviderCredentialTokenGrant, + ) -> Result, Status> { + let ttl = grant + .cache_ttl + .as_ref() + .map(openshell_core::time::duration_to_std) + .transpose() + .map_err(|_| token_grant_configuration_status(tonic::Code::InvalidArgument))?; + if ttl.is_some_and(|ttl| !ttl.is_zero() && ttl < Duration::from_secs(1)) { + return match self { + Self::Broker(_) => Err(token_grant_configuration_status( + tonic::Code::InvalidArgument, + )), + // Direct grants accepted fractional overrides. Keep those + // grants usable by exchanging without caching. + Self::Supervisor(_) => Ok(Some(Duration::ZERO)), + }; + } + Ok(ttl) + } +} + +async fn validate_workload_assertion( + identity: &crate::spiffe_broker::SupervisorWorkloadIdentity, + session: &AuthenticatedSandboxSession, + grant: &ProviderCredentialTokenGrant, + token: &str, + launch_token: &str, +) -> Result { + let expected_id = identity + .sandbox_spiffe_id(session.sandbox_id.as_str()) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + // `authorize` matched this generation against the persisted identity, so + // it names the current launch. + let expected_launch_id = identity + .launch_spiffe_id(session.sandbox_id.as_str(), &session.runtime_generation) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + let audience = effective_jwt_svid_audience(&grant.token_endpoint, &grant.jwt_svid_audience); + let launch_audience = session.runtime_generation.provider_spiffe_audience(); + let bundles = tokio::time::timeout(WORKLOAD_IDENTITY_CALL_TIMEOUT, identity.jwt_bundles()) + .await + .map_err(|_| { + TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::WorkloadIdentity, + ) + .to_status() + })? + .map_err(|error| { + super::token_grant_workload_api_status(error, tonic::Code::FailedPrecondition) + })?; + verify_workload_assertion( + token, + launch_token, + &bundles, + expected_id, + &expected_launch_id, + &audience, + &launch_audience, + ) +} + +fn verify_workload_assertion( + token: &str, + launch_token: &str, + bundles: &spiffe::JwtBundleSet, + expected_id: String, + expected_launch_id: &str, + audience: &str, + launch_audience: &str, +) -> Result { + let rejection = || token_grant_identity_rejected(tonic::Code::PermissionDenied); + openshell_crypto::install_jwt_provider(); + if expected_id == expected_launch_id || audience == launch_audience { + return Err(rejection()); + } + let verify = |token: &str, expected_id: &str, audience: &str| { + let svid = spiffe::JwtSvid::parse_and_validate(token, bundles, &[audience]) + .map_err(|_| rejection())?; + let expires_at = svid.expiry().unix_timestamp(); + if svid.spiffe_id().to_string() != expected_id + || svid.audience().len() != 1 + || expires_at.saturating_mul(1000) <= crate::persistence::current_time_ms() + { + return Err(rejection()); + } + Ok(expires_at) + }; + let expires_at = verify(token, &expected_id, audience)?.min(verify( + launch_token, + expected_launch_id, + launch_audience, + )?); + Ok(SandboxJwtSvid { + spiffe_id: expected_id, + token: token.to_string(), + expires_at, + }) +} + #[allow(clippy::too_many_lines)] async fn obtain( state: &Arc, @@ -221,93 +430,93 @@ async fn obtain( if values.next().is_some() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - let session = authorize(state, &bearer).await?; + let (session, sandbox) = authorize(state, &bearer).await?; if principal.sandbox_id != session.sandbox_id.as_str() { return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); } - // Bound outstanding work after authentication, independently of caching. - // A busy sandbox cannot occupy the gateway's entire acquisition budget. - let _admission = ADMISSION.enter(session.sandbox_id.as_str())?; - // Startup enables an identity provider only with gateway session JWTs. - let (Some(identity), Some(gateway_jwt)) = ( - state.sandbox_identity.as_deref(), - state.config.gateway_jwt.as_ref(), - ) else { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - }; - if state.compute.configured_driver_name() != "kubernetes" { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); + let unavailable = || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let gateway_jwt = state.config.gateway_jwt.as_ref().ok_or_else(unavailable)?; + let supplied = request.get_ref().jwt_svid.as_deref(); + let launch_proof = request.get_ref().launch_jwt_svid.as_deref(); + let supervisor_identity = state.compute.provider_workload_identity(); + let broker = state.sandbox_identity.as_deref(); + if supervisor_identity.is_none() + && (broker.is_none() || state.compute.configured_driver_name() != "kubernetes") + { + return Err(unavailable()); } + let assertions = match (supervisor_identity, supplied, launch_proof) { + (Some(identity), Some(provider), Some(launch)) => Some((identity, provider, launch)), + (None, None, None) => None, + (Some(_), None, None) | (None, Some(_), Some(_)) => return Err(unavailable()), + _ => return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)), + }; + // Keep grant requests bounded. Verified requests have a separate, lower + // limit on OAuth exchanges so cache hits do not consume exchange slots. + let dedicated = supervisor_identity.is_some(); + let request_limit = if dedicated { + PER_SANDBOX_VERIFIED_REQUEST_LIMIT + } else { + PER_SANDBOX_EXCHANGE_LIMIT + }; + let _request_admission = REQUEST_ADMISSION.enter(session.sandbox_id.as_str(), request_limit)?; let gateway_id = gateway_jwt.gateway_id.as_str(); let key = &request.get_ref().credential_key; - let configured = grant_configuration(state, session.sandbox_id.as_str(), key).await?; + let configured = grant_configuration(state, &sandbox, key).await?; let grant = &configured.grant; - let ttl_override = grant - .cache_ttl - .as_ref() - .map(openshell_core::time::duration_to_std) - .transpose() - .map_err(|_| token_grant_configuration_status(tonic::Code::InvalidArgument))?; - // Millisecond truncation and final authorization reads would consume tiny - // cache lifetimes before they could be returned. Zero remains no-cache. - if ttl_override.is_some_and(|ttl| !ttl.is_zero() && ttl < Duration::from_secs(1)) { - return Err(token_grant_configuration_status( - tonic::Code::InvalidArgument, - )); - } - let grant_type = ProviderCredentialTokenGrantType::try_from(grant.grant_type) - .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - // Resolve the subject before any cache lookup, so its revocation or - // expiry also denies cached tokens. - let subject = if grant_type == ProviderCredentialTokenGrantType::TokenExchange { - let subject = grant - .subject_token - .as_ref() - .filter(|subject| subject.source == "provider_credential") - .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - Some(Subject { - expires_at_ms: provider_credential_expiration_ms( - &configured.provider, - &subject.credential, - )?, - value: resolve_subject_token_credential( - &state.credentials, - &configured.provider, - &subject.credential, - ) - .await?, - token_type: subject.subject_token_type.clone(), - }) - } else { - None + // Every dedicated request presents a verified assertion, including cache hits. + let assertion; + let identity = match assertions { + Some((identity, token, launch_proof)) => { + assertion = + validate_workload_assertion(identity, &session, grant, token, launch_proof).await?; + GrantIdentity::Supervisor(&assertion) + } + None => GrantIdentity::Broker(broker.ok_or_else(unavailable)?), }; + let ttl_override = identity.cache_ttl_override(grant)?; + // Resolve the subject before any cache lookup so its value binds the token. + let subject = resolve_subject(state, &configured).await?; let subject_value = subject.as_ref().map(|subject| subject.value.as_str()); let fingerprint = cache_key(&session, &configured, subject_value, gateway_id)?; + let authorization = GrantAuthorization { + state, + bearer: &bearer, + session: &session, + sandbox: &sandbox, + key, + gateway_id, + fingerprint: &fingerprint, + subject: subject.as_ref(), + revalidate_subject: dedicated && subject.is_some(), + }; // A zero override disables caching, and with it shared acquisition. let caching = ttl_override != Some(Duration::ZERO); - let mut refresh = false; + let mut retried_expired_hit = false; loop { let cached = || { - (caching && !refresh) + caching .then(|| ACCESS_TOKENS.get_until(&fingerprint)) .flatten() - .filter(|(_, until)| { - *until > crate::persistence::current_time_ms().saturating_add(1000) - }) }; // A miss holds its fingerprint's turn until its token is cached, so // concurrent misses wait and then find it. A miss is cached only after // the final validation below, which a hit passes as well. let mut turn = None; + let miss_admission; let (response, serve_until_ms, acquired) = if let Some((token, until)) = cached() { + miss_admission = None; (token, until, false) } else { + miss_admission = dedicated + .then(|| MISS_ADMISSION.enter(session.sandbox_id.as_str(), PER_SANDBOX_MISS_LIMIT)) + .transpose()?; let waited = if caching { - Some(ACQUISITIONS.turn(&fingerprint).await?) + let waited = ACQUISITIONS.turn(&fingerprint).await; + if let GrantIdentity::Supervisor(svid) = identity { + require_live_assertion(svid, crate::persistence::current_time_ms())?; + } + Some(waited?) } else { None }; @@ -315,42 +524,39 @@ async fn obtain( (token, until, false) } else { turn = waited; - let (token, until) = acquire( - state, - &bearer, - &session, - identity, - gateway_id, - grant, - subject.as_ref(), - ttl_override, - request_id, - ) - .await - .inspect_err(|status| { - if let Some(turn) = turn.as_mut() { - *turn.failure = Some(status.clone()); - } - })?; + let _exchange_admission = dedicated + .then(|| { + EXCHANGE_ADMISSION + .enter(session.sandbox_id.as_str(), PER_SANDBOX_EXCHANGE_LIMIT) + }) + .transpose()?; + let (token, until) = + acquire(&authorization, identity, grant, ttl_override, request_id) + .await + .inspect_err(|status| { + if let Some(turn) = turn.as_mut() { + turn.record_failure(status); + } + })?; (token, until, true) } }; - // Re-read attachment, provider revision, and profile, then the session, - // before serving or caching any token. - let current = grant_configuration(state, session.sandbox_id.as_str(), key).await?; - if cache_key(&session, ¤t, subject_value, gateway_id)? != fingerprint { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - } - authorize(state, &bearer).await?; + let subject_expiry = authorization.revalidate().await?; // The lifetime runs from when the token service answered, so time spent // in the final validation counts against it. - let remaining_ms = serve_until_ms.saturating_sub(crate::persistence::current_time_ms()); - if remaining_ms <= 0 && !acquired { - // A hit can expire during the final asynchronous checks. Refresh once; - // a fresh acquisition still must pass every check before it is served. - refresh = true; + let now_ms = crate::persistence::current_time_ms(); + let serve_until_ms = serve_until_ms.min(subject_expiry.unwrap_or(i64::MAX)); + let request_expires_at_ms = match identity { + GrantIdentity::Broker(_) => serve_until_ms, + GrantIdentity::Supervisor(svid) => { + require_live_assertion(svid, now_ms)?; + serve_until_ms.min(svid.expires_at.saturating_mul(1000)) + } + }; + let remaining_ms = request_expires_at_ms.saturating_sub(now_ms); + if remaining_ms <= 0 && !acquired && !retried_expired_hit { + // Another request may already have refreshed the expired entry. + retried_expired_hit = true; continue; } if remaining_ms <= 0 { @@ -364,70 +570,90 @@ async fn obtain( ACCESS_TOKENS.set(fingerprint, &response, serve_until_ms); } drop(turn); - return Ok(Response::new(GetSandboxProviderAccessTokenResponse { + let response = Response::new(GetSandboxProviderAccessTokenResponse { access_token: response.access_token, token_type: response.token_type, expires_after: openshell_core::time::duration_from_std(Duration::from_millis( u64::try_from(remaining_ms).unwrap_or_default(), )) .ok(), - })); + }); + drop(miss_admission); + return Ok(response); + } +} + +#[allow(clippy::result_large_err)] +fn require_live_assertion(svid: &SandboxJwtSvid, now_ms: i64) -> Result<(), Status> { + if svid.expires_at.saturating_mul(1000) <= now_ms { + return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); } + Ok(()) } -/// Acquire a final token, re-authorizing the session between network calls. +/// Acquire a final token, rechecking the grant before each OAuth exchange. /// Returns the token and when to stop serving it. -#[allow(clippy::too_many_arguments)] async fn acquire( - state: &ServerState, - bearer: &str, - session: &AuthenticatedSandboxSession, - identity: &dyn SandboxIdentityProvider, - gateway_id: &str, + authorization: &GrantAuthorization<'_>, + identity: GrantIdentity<'_>, grant: &ProviderCredentialTokenGrant, - subject: Option<&Subject>, ttl_override: Option, request_id: Option<&str>, ) -> Result<(oauth::OAuthTokenResponse, i64), Status> { - authorize(state, bearer).await?; + let GrantAuthorization { + state, + bearer, + session, + gateway_id, + subject, + .. + } = *authorization; let audience = effective_jwt_svid_audience(&grant.token_endpoint, &grant.jwt_svid_audience); - let sandbox = state - .store - .get_message::(session.sandbox_id.as_str()) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(|| token_grant_identity_rejected(tonic::Code::Unauthenticated))?; - let runtime_identity = sandbox - .metadata - .as_ref() - .and_then(|metadata| { - metadata - .annotations - .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) - }) - .map_or("", String::as_str); - let svid = identity - .fetch_jwt_svid( - gateway_id, - session.sandbox_id.as_str(), - &audience, - runtime_identity, - ) - .await - .map_err(TokenGrantFailure::to_status)?; - authorize(state, bearer).await?; + let issued; + let svid = match identity { + GrantIdentity::Broker(provider) => { + let (_, sandbox) = authorize(state, bearer).await?; + let runtime_identity = sandbox + .metadata + .as_ref() + .and_then(|metadata| { + metadata + .annotations + .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) + }) + .map_or("", String::as_str); + issued = provider + .fetch_jwt_svid( + gateway_id, + session.sandbox_id.as_str(), + &audience, + runtime_identity, + ) + .await + .map_err(TokenGrantFailure::to_status)?; + &issued + } + GrantIdentity::Supervisor(svid) => svid, + }; + let check_expiry = || require_live_assertion(svid, crate::persistence::current_time_ms()); let client = token_exchange_http_client()?; - let subject_expiry = subject.and_then(|subject| subject.expires_at_ms); + let mut subject_expiry = i64::MAX; let token = if let Some(subject) = subject { - let component_svid = fetch_gateway_jwt_svid_from( - &audience, - state - .config - .spiffe_broker - .as_ref() - .map(|broker| broker.workload_api_socket_path.as_str()), - ) - .await?; + let component_socket = state + .config + .spiffe_workload_identity + .as_ref() + .and_then(|identity| identity.workload_api_socket_path.to_str()) + .or_else(|| { + state + .config + .spiffe_broker + .as_ref() + .map(|broker| broker.workload_api_socket_path.as_str()) + }); + let component_svid = fetch_gateway_jwt_svid_from(&audience, component_socket).await?; + subject_expiry = authorization.revalidate().await?.unwrap_or(i64::MAX); + check_expiry()?; let intermediate = perform_intermediate_token_exchange( &grant.token_endpoint, &TokenExchangeParams { @@ -442,7 +668,8 @@ async fn acquire( request_id, ) .await?; - authorize(state, bearer).await?; + subject_expiry = subject_expiry.min(authorization.revalidate().await?.unwrap_or(i64::MAX)); + check_expiry()?; oauth::post_oauth_token_exchange( client, &grant.token_endpoint, @@ -460,6 +687,8 @@ async fn acquire( .await .map_err(TokenGrantFailure::to_status)? } else { + authorization.revalidate().await?; + check_expiry()?; oauth::post_oauth_token_grant( client, &grant.token_endpoint, @@ -475,11 +704,12 @@ async fn acquire( .map_err(TokenGrantFailure::to_status)? }; let obtained_at_ms = crate::persistence::current_time_ms(); + require_live_assertion(svid, obtained_at_ms)?; let identity_expires_at_ms = session .expires_at .saturating_mul(1000) .min(svid.expires_at.saturating_mul(1000)) - .min(subject_expiry.unwrap_or(i64::MAX)); + .min(subject_expiry); let serve_until_ms = serve_until_ms(&token, ttl_override, obtained_at_ms, identity_expires_at_ms).ok_or_else( || { @@ -490,7 +720,6 @@ async fn acquire( .to_status() }, )?; - authorize(state, bearer).await?; Ok((token, serve_until_ms)) } @@ -541,13 +770,14 @@ struct Admission { } impl Admission { - fn enter(&self, sandbox: &str) -> Result, Status> { + fn enter(&self, sandbox: &str, per_sandbox_limit: usize) -> Result, Status> { let mut active = self .active .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if active.values().sum::() >= 64 - || active.get(sandbox).copied().unwrap_or_default() >= 4 + // Sixteen sandboxes at their own limit fill the gateway, whatever that limit is. + if active.values().sum::() >= per_sandbox_limit * 16 + || active.get(sandbox).copied().unwrap_or_default() >= per_sandbox_limit { return Err(TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, @@ -587,8 +817,9 @@ impl Drop for AdmissionGuard<'_> { /// Coordinate token acquisition separately for each cache fingerprint. /// /// Concurrent misses share a single acquisition without locking unrelated -/// tokens. Current waiters receive the holder's acquisition failure; a new -/// group can retry after they leave. Entries exist only while held or awaited. +/// tokens. Current waiters share dependency outages. A caller's authorization +/// failure leaves the turn available to its waiters. Entries live only while +/// held or awaited. #[derive(Default)] struct Acquisitions { slots: std::sync::Mutex, @@ -647,6 +878,29 @@ struct AcquisitionTurn<'a> { _registration: Registration<'a>, } +impl AcquisitionTurn<'_> { + fn record_failure(&mut self, status: &Status) { + let failure = TokenGrantFailure::from_status(status); + if matches!( + (failure.kind(), failure.upstream_status()), + ( + TokenGrantFailureKind::Unavailable, + None | Some(429 | 500..=599) + ) | (TokenGrantFailureKind::Timeout, _) + ) && matches!( + failure.stage(), + TokenGrantStage::WorkloadIdentity + | TokenGrantStage::IntermediateExchange + | TokenGrantStage::TokenEndpoint + ) { + *self.failure = Some(status.clone()); + } + } +} + +#[cfg(test)] +mod performance_tests; + #[cfg(test)] mod tests { use super::*; @@ -655,22 +909,30 @@ mod tests { #[test] fn admission_is_bounded_per_sandbox_and_releases_cancelled_work() { let admission = Admission::default(); - let guards: Vec<_> = (0..4).map(|_| admission.enter("busy").unwrap()).collect(); - assert_eq!( - admission.enter("busy").err().unwrap().code(), - tonic::Code::ResourceExhausted - ); - let other = admission.enter("other").unwrap(); - drop(guards); - drop(admission.enter("busy").unwrap()); - drop(other); - assert!(admission.active.lock().unwrap().is_empty()); - let guards: Vec<_> = (0..64) - .map(|i| admission.enter(&i.to_string()).unwrap()) - .collect(); - assert!(admission.enter("overflow").is_err()); - drop(guards); - assert!(admission.active.lock().unwrap().is_empty()); + for limit in [ + PER_SANDBOX_EXCHANGE_LIMIT, + PER_SANDBOX_VERIFIED_REQUEST_LIMIT, + ] { + let guards: Vec<_> = (0..limit) + .map(|_| admission.enter("busy", limit).unwrap()) + .collect(); + assert_eq!( + admission.enter("busy", limit).err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + let other = admission.enter("other", limit).unwrap(); + drop(guards); + drop(admission.enter("busy", limit).unwrap()); + drop(other); + assert!(admission.active.lock().unwrap().is_empty()); + // Sixteen sandboxes at this limit fill the gateway; the next is refused. + let guards: Vec<_> = (0..limit * 16) + .map(|i| admission.enter(&(i / limit).to_string(), limit).unwrap()) + .collect(); + assert!(admission.enter("overflow", limit).is_err()); + drop(guards); + assert!(admission.active.lock().unwrap().is_empty()); + } } #[tokio::test] async fn broker_requires_a_signed_session_even_with_a_sandbox_principal() { @@ -700,6 +962,98 @@ mod tests { } } + #[test] + fn workload_assertion_requires_the_exact_sandbox_and_supervisor_launch() { + use openshell_core::sandbox_generation::SandboxGenerationId; + + let (bundles, header, encoding_key) = performance_tests::workload_trust(); + let now = crate::persistence::current_time_ms() / 1000; + let sign_until = |subject: &str, audiences: &[&str], expires_at| { + openshell_crypto::jwt::encode( + &header, + &serde_json::json!({"sub": subject, "aud": audiences, "exp": expires_at}), + &encoding_key, + ) + .unwrap() + }; + let sign = |subject: &str, audiences: &[&str]| sign_until(subject, audiences, now + 120); + let sandboxes = [ + "spiffe://test.example/gateway/gateway/sandbox/a", + "spiffe://test.example/gateway/gateway/sandbox/b", + ]; + let launches = [ + "spiffe://test.example/gateway/gateway/sandbox/a/launch/current", + "spiffe://test.example/gateway/gateway/sandbox/b/launch/current", + ]; + let launch = SandboxGenerationId::parse("g2") + .unwrap() + .provider_spiffe_audience(); + let older = SandboxGenerationId::parse("g1") + .unwrap() + .provider_spiffe_audience(); + let audience = "https://issuer.test/token"; + let verify = |token: &str, launch_token: &str, expected: &str, expected_launch: &str| { + verify_workload_assertion( + token, + launch_token, + &bundles, + expected.to_owned(), + expected_launch, + audience, + &launch, + ) + }; + for (subject, launch_subject) in sandboxes.into_iter().zip(launches) { + let token = sign(subject, &[audience]); + let launch_proof = sign(launch_subject, &[&launch]); + let verified = verify(&token, &launch_proof, subject, launch_subject).unwrap(); + assert_eq!(verified.spiffe_id, subject); + } + let token = sign(sandboxes[0], &[audience]); + let proof = sign(launches[0], &[&launch]); + // The accepted claims, signed by a key the trust bundle does not hold. + let (_, _, untrusted) = performance_tests::workload_trust(); + let forged = openshell_crypto::jwt::encode( + &header, + &serde_json::json!({"sub": sandboxes[0], "aud": [audience], "exp": now + 120}), + &untrusted, + ) + .unwrap(); + let shorter_provider = sign_until(sandboxes[0], &[audience], now + 60); + let shorter_launch = sign_until(launches[0], &[&launch], now + 60); + for (provider, launch_proof) in [(&shorter_provider, &proof), (&token, &shorter_launch)] { + assert_eq!( + verify(provider, launch_proof, sandboxes[0], launches[0]) + .unwrap() + .expires_at, + now + 60 + ); + } + for (token, proof) in [ + (forged, proof.clone()), + (sign(sandboxes[1], &[audience]), proof.clone()), + (token.clone(), sign(launches[1], &[&launch])), + (token.clone(), sign(launches[0], &[&older])), + ( + token.clone(), + sign( + "spiffe://test.example/gateway/gateway/sandbox/a/launch/outgoing", + &[&launch], + ), + ), + (token.clone(), sign(sandboxes[0], &[&launch])), + (token.clone(), token), + (sign(sandboxes[0], &[audience, &launch]), proof), + ] { + assert_eq!( + verify(&token, &proof, sandboxes[0], launches[0]) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + } + } + #[test] fn fingerprint_binds_the_runtime_configured_key_and_resolved_subject() { use openshell_core::jwt::{CredentialEpoch, SandboxId}; @@ -718,6 +1072,7 @@ mod tests { provider: Provider::default(), grant: ProviderCredentialTokenGrant::default(), key: key.to_string(), + attachment_epoch: String::new(), }; let owned = "api.example.com\t443\t/v1/**\towner\tprovider:access"; let fingerprint = |session, key, subject| { @@ -733,6 +1088,21 @@ mod tests { assert_eq!(fingerprint(&renewed, owned, Some("subject-a")), base); // A rotated subject, another credential, or another epoch does not. assert_ne!(fingerprint(&session, owned, Some("subject-b")), base); + let mut reattached = configured(owned); + reattached.attachment_epoch = "new-attachment".into(); + assert_ne!( + cache_key(&session, &reattached, Some("subject-a"), "gateway").unwrap(), + base + ); + // Another runtime generation is another launch. + let relaunched = AuthenticatedSandboxSession { + runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( + "g2", + ) + .unwrap(), + ..session.clone() + }; + assert_ne!(fingerprint(&relaunched, owned, Some("subject-a")), base); let spoofed = owned.replace("owner", "other"); assert_ne!(fingerprint(&session, &spoofed, Some("subject-a")), base); let rotated = AuthenticatedSandboxSession { @@ -746,6 +1116,27 @@ mod tests { ); } + #[test] + fn verified_grants_accept_fractional_overrides_without_caching() { + const NOW: i64 = 1_700_000_000_000; + let assertion = SandboxJwtSvid { + spiffe_id: "spiffe://test.example/sandbox".into(), + token: "fixture-assertion".into(), + expires_at: NOW / 1000 + 60, + }; + let grant = ProviderCredentialTokenGrant { + cache_ttl: Some(prost_types::Duration { + seconds: 0, + nanos: 500_000_000, + }), + ..Default::default() + }; + let ttl = GrantIdentity::Supervisor(&assertion) + .cache_ttl_override(&grant) + .unwrap(); + assert_eq!(ttl, Some(Duration::ZERO)); + } + #[test] fn served_lifetime_never_exceeds_the_token_or_identity() { const NOW: i64 = 1_700_000_000_000; @@ -851,11 +1242,32 @@ mod tests { }) .await .expect("all requests should join the in-flight acquisition"); + holder.record_failure(&Status::unauthenticated("superseded bearer")); + assert!(holder.failure.is_none()); + let rejected_assertion = TokenGrantFailure::new( + TokenGrantFailureKind::Unclassified, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(401); + holder.record_failure(&rejected_assertion.to_status()); + assert!(holder.failure.is_none()); + // A token service that stalls after its headers is an outage too. + let stalled_body = TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(200); + holder.record_failure(&stalled_body.to_status()); + assert_eq!( + holder.failure.as_ref().map(TokenGrantFailure::from_status), + Some(stalled_body) + ); let expected = TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, TokenGrantStage::TokenEndpoint, - ); - *holder.failure = Some(expected.to_status()); + ) + .with_upstream_status(503); + holder.record_failure(&expected.to_status()); drop(holder); for waiter in waiters { let result = tokio::time::timeout(Duration::from_secs(5), waiter) diff --git a/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs b/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs new file mode 100644 index 0000000000..d63743f068 --- /dev/null +++ b/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs @@ -0,0 +1,834 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::num::NonZeroU64; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use axum::{Json, Router, extract::Path, extract::State, routing::post}; +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use openshell_bootstrap::jwt::generate_jwt_key; +use openshell_core::config::{GatewayJwtConfig, SpiffeWorkloadIdentityConfig}; +use openshell_core::extension_protocol::COMPUTE_PROVIDER_WORKLOAD_IDENTITY; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriver as _; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use openshell_core::proto::{ + AttachSandboxProviderRequest, DetachSandboxProviderRequest, NetworkAccessPreset, + NetworkEndpoint, ProviderCredentialTokenGrantSubjectToken, ProviderProfile, + ProviderProfileCategory, ProviderProfileCredential, SandboxPhase, SandboxSpec, + workspace_selector, +}; +use rcgen::PublicKeyData as _; +use tokio::sync::Notify; +use tokio::task::JoinHandle; +use uuid::Uuid; + +use super::*; +use crate::auth::principal::{SandboxIdentitySource, SandboxPrincipal}; +use crate::auth::sandbox_jwt::SandboxSessionJwtAuthority; +use crate::auth::sandbox_session::PersistedSandboxIdentity; +use crate::compute::ComputeRuntime; +use crate::grpc::sandbox::{handle_attach_sandbox_provider, handle_detach_sandbox_provider}; +use crate::grpc::test_support::{ + authed_request, test_server_state_with_driver, test_server_state_without_provider_profiles, +}; +use crate::persistence::current_time_ms; +use crate::spiffe_broker::SupervisorWorkloadIdentity; +use crate::test_support::FakeComputeDriver; + +const GATEWAY_ID: &str = "performance-test-gateway"; +const ASSERTION_AUDIENCE: &str = "https://issuer.test/"; +const SUBJECT_KEY: &str = "subject_token"; +// Attaching a provider validates the sandbox name, and the sandbox ID is too long for one. +const SANDBOX_NAME: &str = "grant-sandbox"; + +/// A `test.example` trust bundle with the header and key that sign for it. +pub(super) fn workload_trust() -> ( + spiffe::JwtBundleSet, + jsonwebtoken::Header, + jsonwebtoken::EncodingKey, +) { + let key = openshell_crypto::pki::generate_keypair_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let public_key = key.der_bytes(); + let jwks = serde_json::json!({ + "keys": [{ + "kty": "EC", "crv": "P-256", "alg": "ES256", "kid": "workload-test", + "x": URL_SAFE_NO_PAD.encode(&public_key[1..33]), + "y": URL_SAFE_NO_PAD.encode(&public_key[33..65]), + }] + }); + let mut bundles = spiffe::JwtBundleSet::new(); + bundles.add_bundle( + spiffe::JwtBundle::from_jwt_authorities( + spiffe::TrustDomain::new("test.example").unwrap(), + &serde_json::to_vec(&jwks).unwrap(), + ) + .unwrap(), + ); + let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::ES256); + header.kid = Some("workload-test".into()); + let signing_key = + jsonwebtoken::EncodingKey::from_ec_pem(key.serialize_pem().unwrap().as_bytes()).unwrap(); + (bundles, header, signing_key) +} + +/// The assertion a Kubernetes identity broker would issue for the sandbox. +#[derive(Debug)] +struct TestSandboxIdentity; + +#[async_trait::async_trait] +impl SandboxIdentityProvider for TestSandboxIdentity { + type Error = TokenGrantFailure; + + async fn fetch_jwt_svid( + &self, + gateway_id: &str, + sandbox_id: &str, + _audience: &str, + _runtime_identity: &str, + ) -> Result { + Ok(SandboxJwtSvid { + spiffe_id: format!("spiffe://test.example/gateway/{gateway_id}/sandbox/{sandbox_id}"), + token: "fixture-assertion".to_string(), + expires_at: current_time_ms() / 1000 + 300, + }) + } +} + +#[derive(Default)] +struct Issuer { + warm_calls: AtomicUsize, + cold_calls: AtomicUsize, + cold_started: Notify, + release_cold: Notify, +} + +async fn issue( + State(issuer): State>, + Path(grant): Path, +) -> Json { + let count = match grant.as_str() { + "warm" => issuer.warm_calls.fetch_add(1, Ordering::Relaxed) + 1, + "cold" => { + let count = issuer.cold_calls.fetch_add(1, Ordering::Relaxed) + 1; + if count == 1 { + issuer.cold_started.notify_one(); + issuer.release_cold.notified().await; + } + count + } + _ => panic!("unexpected grant route"), + }; + Json(serde_json::json!({ + "access_token": format!("{grant}-{count}"), + "token_type": "Bearer", + "expires_in": 300, + })) +} + +struct Fixture { + state: Arc, + issuer: Arc, + issuer_task: JoinHandle<()>, + identity: SupervisorWorkloadIdentity, + bundles: spiffe::JwtBundleSet, + id: String, + spiffe_id: String, + launch_spiffe_id: String, + launch_audience: String, + bearer: String, + assertion_key: jsonwebtoken::EncodingKey, + assertion_header: jsonwebtoken::Header, + warm_key: String, + cold_key: String, +} + +impl Fixture { + /// A verified-grant gateway, or with `brokered` the Kubernetes broker path, + /// where requests carry no assertions. + #[allow( + clippy::literal_string_with_formatting_args, + reason = "Axum routes use braces for path parameters" + )] + async fn new(warm_ttl_seconds: i64, warm_subject: Option<&str>, brokered: bool) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let issuer = Arc::new(Issuer::default()); + let app = Router::new() + .route("/{grant}", post(issue)) + .with_state(issuer.clone()); + let issuer_task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let id = Uuid::new_v4().to_string(); + let provider_name = format!("grant-{id}"); + let mut state = if brokered { + test_server_state_with_driver("kubernetes").await + } else { + test_server_state_without_provider_profiles().await + }; + let server = Arc::get_mut(&mut state).unwrap(); + server.config.gateway_jwt = Some(GatewayJwtConfig { + gateway_id: GATEWAY_ID.into(), + ttl_secs: NonZeroU64::new(300), + signing_key_path: PathBuf::default(), + public_key_path: PathBuf::default(), + kid_path: PathBuf::default(), + }); + let workload = SpiffeWorkloadIdentityConfig { + spiffe_id_prefix: "spiffe://test.example".into(), + workload_api_socket_path: "/unused/test/workload.sock".into(), + }; + let identity = SupervisorWorkloadIdentity::from_settings( + Some(&workload), + server.config.gateway_jwt.as_ref(), + false, + ) + .unwrap() + .unwrap(); + let spiffe_id = identity.sandbox_spiffe_id(&id).unwrap(); + if brokered { + server.sandbox_identity = Some(Arc::new(TestSandboxIdentity)); + } else { + server.config.spiffe_workload_identity = Some(workload); + let driver = FakeComputeDriver::new(); + let mut capabilities = driver + .get_capabilities(Request::new(GetCapabilitiesRequest::default())) + .await + .unwrap() + .into_inner(); + capabilities + .extension + .as_mut() + .unwrap() + .supported_capabilities + .push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.into()); + server.compute = ComputeRuntime::from_driver( + "fake-compute-driver".into(), + Arc::new(driver.with_capabilities(capabilities)), + None, + server.store.clone(), + server.sandbox_index.clone(), + server.sandbox_watch_bus.clone(), + server.tracing_log_bus.clone(), + server.supervisor_sessions.clone(), + ) + .await + .unwrap() + .with_provider_workload_identity(Some(identity.clone())) + .unwrap(); + } + + let persisted = PersistedSandboxIdentity::new().unwrap(); + let launch_spiffe_id = identity + .launch_spiffe_id(&id, &persisted.runtime_generation) + .unwrap(); + let launch_audience = persisted.runtime_generation.provider_spiffe_audience(); + let gateway_key = generate_jwt_key().unwrap(); + let authority = Arc::new( + SandboxSessionJwtAuthority::from_pem( + gateway_key.signing_key_pem.as_bytes(), + gateway_key.public_key_pem.as_bytes(), + gateway_key.kid, + GATEWAY_ID, + Some(Duration::from_mins(5)), + ) + .unwrap(), + ); + let bearer = authority + .mint_persisted_launch(&id, &persisted) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + server.sandbox_session_jwt_authority = Some(authority); + let metadata = |name: &str| ObjectMeta { + id: name.into(), + name: name.into(), + workspace: "default".into(), + ..Default::default() + }; + let mut sandbox_meta = metadata(&id); + sandbox_meta.name = SANDBOX_NAME.into(); + persisted.write(&mut sandbox_meta.annotations); + let mut sandbox = Sandbox { + metadata: Some(sandbox_meta), + spec: Some(SandboxSpec { + providers: vec![provider_name.clone()], + provider_attachment_epoch: "attachment".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + server.store.put_message(&sandbox).await.unwrap(); + let credential = |name: &str, header: &str, ttl_seconds| ProviderProfileCredential { + name: name.into(), + auth_style: "header".into(), + header_name: header.into(), + token_grant: Some(ProviderCredentialTokenGrant { + token_endpoint: format!("{base_url}/{name}"), + jwt_svid_audience: ASSERTION_AUDIENCE.into(), + grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, + cache_ttl: Some(prost_types::Duration { + seconds: ttl_seconds, + nanos: 0, + }), + ..Default::default() + }), + ..Default::default() + }; + let mut warm = credential("warm", "X-Warm-Token", warm_ttl_seconds); + let mut provider = Provider { + metadata: Some(metadata(&provider_name)), + r#type: format!("profile-{id}"), + ..Default::default() + }; + let mut subject_credentials = Vec::new(); + if let Some(value) = warm_subject { + let grant = warm.token_grant.as_mut().unwrap(); + grant.grant_type = ProviderCredentialTokenGrantType::TokenExchange.into(); + grant.subject_token = Some(ProviderCredentialTokenGrantSubjectToken { + source: "provider_credential".into(), + credential: SUBJECT_KEY.into(), + subject_token_type: oauth::ACCESS_TOKEN_TYPE.into(), + }); + subject_credentials.push(ProviderProfileCredential { + name: SUBJECT_KEY.into(), + ..Default::default() + }); + provider.credential_handles = server + .credentials + .store_provider_credentials( + &provider_name, + "default", + &provider_name, + &HashMap::from([(SUBJECT_KEY.into(), value.into())]), + &HashMap::new(), + ) + .await + .unwrap(); + } + subject_credentials.extend([warm, credential("cold", "X-Cold-Token", 300)]); + let profile = ProviderProfile { + id: provider.r#type.clone(), + display_name: "Grant performance test profile".into(), + category: ProviderProfileCategory::Other as i32, + endpoints: vec![NetworkEndpoint { + host: "api.example.test".into(), + port: 443, + path: "/**".into(), + protocol: "rest".into(), + access: NetworkAccessPreset::Full as i32, + ..Default::default() + }], + credentials: subject_credentials, + ..Default::default() + }; + let mut credentials = HashMap::new(); + insert_dynamic_credentials_for_profile( + &mut credentials, + &openshell_providers::ProviderTypeProfile::from_proto(&profile), + &provider_name, + &provider_name, + ) + .unwrap(); + let key = |name| { + credentials + .keys() + .find(|key| key.ends_with(name)) + .unwrap() + .clone() + }; + let (warm_key, cold_key) = (key(":warm"), key(":cold")); + server.store.put_message(&provider).await.unwrap(); + server + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + profile, + )) + .await + .unwrap(); + + let (bundles, assertion_header, assertion_key) = workload_trust(); + identity.seed_test_jwt_bundles(bundles.clone()).await; + + Self { + state, + issuer, + issuer_task, + identity, + bundles, + id, + spiffe_id, + launch_spiffe_id, + launch_audience, + bearer, + assertion_key, + assertion_header, + warm_key, + cold_key, + } + } + + fn request(&self, key: &str, expires_at: i64) -> Request { + let sign = |subject: &str, audience: &str| { + openshell_crypto::jwt::encode( + &self.assertion_header, + &serde_json::json!({ + "sub": subject, + "aud": [audience], + "exp": expires_at, + }), + &self.assertion_key, + ) + .unwrap() + }; + let verified = self.state.compute.provider_workload_identity().is_some(); + let mut request = Request::new(GetSandboxProviderAccessTokenRequest { + credential_key: key.into(), + jwt_svid: verified.then(|| sign(&self.spiffe_id, ASSERTION_AUDIENCE)), + launch_jwt_svid: verified.then(|| sign(&self.launch_spiffe_id, &self.launch_audience)), + }); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: self.id.clone(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: format!("openshell-gateway:{GATEWAY_ID}"), + auth_epoch: None, + }, + trust_domain: None, + })); + request.metadata_mut().insert( + "authorization", + format!("Bearer {}", self.bearer).parse().unwrap(), + ); + request + } + + async fn fingerprint(&self, key: &str) -> String { + let (session, sandbox) = authorize(&self.state, &self.bearer).await.unwrap(); + let configured = grant_configuration(&self.state, &sandbox, key) + .await + .unwrap(); + let subject = resolve_subject(&self.state, &configured).await.unwrap(); + cache_key( + &session, + &configured, + subject.as_ref().map(|subject| subject.value.as_str()), + GATEWAY_ID, + ) + .unwrap() + } + + fn spawn_request( + &self, + key: &str, + expires_at: i64, + ) -> JoinHandle, Status>> { + let state = self.state.clone(); + let request = self.request(key, expires_at); + tokio::spawn(async move { handle(&state, request).await }) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.issuer_task.abort(); + } +} + +fn registered(fingerprint: &str) -> usize { + ACQUISITIONS + .lock() + .get(fingerprint) + .map_or(0, |(_, users)| *users) +} + +/// Cache `token` under `fingerprint` for a minute, as a finished acquisition would. +fn cache(fingerprint: String, token: &str) { + ACCESS_TOKENS.set( + fingerprint, + &oauth::OAuthTokenResponse { + access_token: token.into(), + token_type: "Bearer".into(), + expires_in: 60, + }, + current_time_ms() + 60_000, + ); +} + +async fn wait_until(mut ready: impl FnMut() -> bool) { + tokio::time::timeout(Duration::from_secs(5), async { + while !ready() { + tokio::task::yield_now().await; + } + }) + .await + .expect("requests reached acquisition admission"); +} + +#[tokio::test] +async fn a_one_second_ttl_reuses_a_live_token() { + let fixture = Fixture::new(1, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let first = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + let second = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + + assert_eq!(first.access_token, "warm-1"); + assert_eq!(second.access_token, first.access_token); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn dedicated_cold_waiters_leave_capacity_for_warm_grants() { + let fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let warm = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + let fingerprint = fixture.fingerprint(&fixture.cold_key).await; + let leader = fixture.spawn_request(&fixture.cold_key, expires); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("cold leader started its OAuth request"); + let waiters: Vec<_> = (1..PER_SANDBOX_VERIFIED_REQUEST_LIMIT) + .map(|_| fixture.spawn_request(&fixture.cold_key, expires)) + .collect(); + wait_until(|| { + registered(&fingerprint) + waiters.iter().filter(|task| task.is_finished()).count() + == PER_SANDBOX_VERIFIED_REQUEST_LIMIT + }) + .await; + fixture + .identity + .seed_test_jwt_bundles(fixture.bundles.clone()) + .await; + + let cached = tokio::time::timeout( + Duration::from_secs(5), + handle(&fixture.state, fixture.request(&fixture.warm_key, expires)), + ) + .await + .expect("warm request returned while cold leader was blocked") + .unwrap() + .into_inner(); + assert_eq!(cached.access_token, warm.access_token); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); + + fixture.issuer.release_cold.notify_one(); + assert_eq!( + leader.await.unwrap().unwrap().into_inner().access_token, + "cold-1" + ); + let mut refused = 0; + for waiter in waiters { + match waiter.await.unwrap() { + Ok(response) => assert_eq!(response.into_inner().access_token, "cold-1"), + Err(error) => { + assert_eq!(error.code(), tonic::Code::ResourceExhausted); + refused += 1; + } + } + } + assert!(refused > 0); + assert_eq!(fixture.issuer.cold_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn a_queued_expired_proof_does_not_fail_a_fresh_waiter() { + let fixture = Fixture::new(300, None, false).await; + let fingerprint = fixture.fingerprint(&fixture.warm_key).await; + let occupied = ACQUISITIONS.turn(&fingerprint).await.unwrap(); + let now = current_time_ms(); + let short_expiry = now / 1000 + 3; + let short = fixture.spawn_request(&fixture.warm_key, short_expiry); + wait_until(|| registered(&fingerprint) == 2).await; + let fresh = fixture.spawn_request(&fixture.warm_key, now / 1000 + 60); + wait_until(|| registered(&fingerprint) == 3).await; + let remaining = short_expiry.saturating_mul(1000) - current_time_ms(); + tokio::time::sleep(Duration::from_millis(u64::try_from(remaining).unwrap_or(0))).await; + drop(occupied); + + let error = short.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + let response = fresh.await.unwrap().unwrap().into_inner(); + assert_eq!(response.access_token, "warm-1"); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn queued_token_exchange_rejects_a_subject_rotated_under_the_same_handle() { + let fixture = Fixture::new(300, Some("original-subject"), false).await; + let old_fingerprint = fixture.fingerprint(&fixture.warm_key).await; + let occupied = ACQUISITIONS.turn(&old_fingerprint).await.unwrap(); + let expires_at = current_time_ms() / 1000 + 60; + let waiter = fixture.spawn_request(&fixture.warm_key, expires_at); + wait_until(|| registered(&old_fingerprint) == 2).await; + + let provider_id = format!("grant-{}", fixture.id); + let provider = fixture + .state + .store + .get_message::(&provider_id) + .await + .unwrap() + .unwrap(); + let replacement_handles = fixture + .state + .credentials + .store_provider_credentials( + &provider_id, + "default", + &provider_id, + &HashMap::from([(SUBJECT_KEY.into(), "replacement-subject".into())]), + &provider.credential_handles, + ) + .await + .unwrap(); + assert_eq!(replacement_handles, provider.credential_handles); + let new_fingerprint = fixture.fingerprint(&fixture.warm_key).await; + assert_ne!(new_fingerprint, old_fingerprint); + + // Publish the result for the original subject while the request is still + // waiting for the acquisition that produced it. + cache(old_fingerprint, "old-access-token"); + drop(occupied); + + let error = waiter.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + cache(new_fingerprint, "new-access-token"); + let response = handle( + &fixture.state, + fixture.request(&fixture.warm_key, expires_at), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(response.access_token, "new-access-token"); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 0); +} + +#[tokio::test] +async fn a_cache_hit_is_not_served_past_the_subject_expiry() { + let fixture = Fixture::new(300, Some("subject"), false).await; + let store = &fixture.state.store; + let mut provider = store + .get_message::(&format!("grant-{}", fixture.id)) + .await + .unwrap() + .unwrap(); + provider + .credential_handles + .get_mut(SUBJECT_KEY) + .unwrap() + .metadata + .insert( + "test_expiration_ms".into(), + (current_time_ms() + 10_000).to_string(), + ); + store.put_message(&provider).await.unwrap(); + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let expires = current_time_ms() / 1000 + 60; + let response = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + assert_eq!(response.access_token, "cached-access-token"); + let lifetime = openshell_core::time::duration_to_std(&response.expires_after.unwrap()).unwrap(); + assert!( + lifetime <= Duration::from_secs(10), + "served for {lifetime:?}" + ); +} + +#[tokio::test] +async fn brokered_token_exchange_cache_hit_resolves_the_subject_once() { + let fixture = Fixture::new(300, Some("user-token"), true).await; + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let (first_read, release_first_read) = fixture.state.credentials.gate_next_resolve(); + let exchange = handle(&fixture.state, fixture.request(&fixture.warm_key, 0)); + tokio::pin!(exchange); + tokio::select! { + result = &mut exchange => panic!("grant finished before resolving the subject: {result:?}"), + first_read = first_read => first_read.unwrap(), + } + let (second_read, _release_second_read) = fixture.state.credentials.gate_next_resolve(); + release_first_read.send(()).unwrap(); + let response = tokio::select! { + result = exchange => result.unwrap().into_inner(), + _ = second_read => panic!("cache hit resolved the subject again"), + }; + assert_eq!(response.access_token, "cached-access-token"); +} + +#[tokio::test] +async fn reattaching_provider_during_exchange_rejects_the_in_flight_token() { + let fixture = Fixture::new(300, None, true).await; + let exchange = fixture.spawn_request(&fixture.cold_key, 0); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let provider = format!("grant-{}", fixture.id); + let detached = handle_detach_sandbox_provider( + &fixture.state, + authed_request(DetachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider: provider.clone(), + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(detached.detached); + let attached = handle_attach_sandbox_provider( + &fixture.state, + authed_request(AttachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider, + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(attached.attached); + fixture.issuer.release_cold.notify_one(); + + let error = exchange + .await + .unwrap() + .expect_err("reject the detached grant"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + let new_token = handle(&fixture.state, fixture.request(&fixture.cold_key, 0)) + .await + .unwrap() + .into_inner(); + assert_eq!(new_token.access_token, "cold-2"); +} + +#[tokio::test] +async fn direct_subject_exchange_is_closed_while_workload_identity_is_configured() { + let fixture = Fixture::new(300, None, false).await; + let (metadata, extensions, _) = fixture.request(&fixture.warm_key, 0).into_parts(); + let request = Request::from_parts( + metadata, + extensions, + openshell_core::proto::ExchangeProviderSubjectTokenRequest { + sandbox_id: fixture.id.clone(), + ..Default::default() + }, + ); + let error = + crate::grpc::provider::handle_exchange_provider_subject_token(&fixture.state, request) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn verified_grants_require_both_assertions() { + let fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + for (provider, launch, code) in [ + (false, false, tonic::Code::FailedPrecondition), + (true, false, tonic::Code::PermissionDenied), + (false, true, tonic::Code::PermissionDenied), + ] { + let mut request = fixture.request(&fixture.warm_key, expires); + if !provider { + request.get_mut().jwt_svid = None; + } + if !launch { + request.get_mut().launch_jwt_svid = None; + } + let error = handle(&fixture.state, request).await.unwrap_err(); + assert_eq!(error.code(), code); + } + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 0); +} + +#[tokio::test] +async fn stopping_or_restarting_during_exchange_rejects_the_in_flight_token() { + for (restart, code) in [ + (false, tonic::Code::FailedPrecondition), + (true, tonic::Code::Unauthenticated), + ] { + let mut fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let in_flight = fixture.spawn_request(&fixture.cold_key, expires); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let store = fixture.state.store.clone(); + let mut sandbox = store + .get_message::(&fixture.id) + .await + .unwrap() + .unwrap(); + if restart { + // A restart installs a new identity: a new generation and launch. + let annotations = &mut sandbox.metadata.as_mut().unwrap().annotations; + let launch = PersistedSandboxIdentity::new().unwrap(); + launch.write(annotations); + let authority = fixture.state.sandbox_session_jwt_authority.as_ref(); + fixture.bearer = authority + .unwrap() + .mint_persisted_launch(&fixture.id, &launch) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + fixture.launch_spiffe_id = fixture + .identity + .launch_spiffe_id(&fixture.id, &launch.runtime_generation) + .unwrap(); + fixture.launch_audience = launch.runtime_generation.provider_spiffe_audience(); + } else { + sandbox.set_phase(SandboxPhase::Stopping as i32); + } + store.put_message(&sandbox).await.unwrap(); + fixture.issuer.release_cold.notify_one(); + assert_eq!(in_flight.await.unwrap().unwrap_err().code(), code); + + // The rejected token was not cached: the next request exchanges again. + sandbox.set_phase(SandboxPhase::Ready as i32); + store.put_message(&sandbox).await.unwrap(); + let next = handle(&fixture.state, fixture.request(&fixture.cold_key, expires)) + .await + .unwrap() + .into_inner(); + assert_eq!(next.access_token, "cold-2"); + } +} diff --git a/crates/openshell-server/src/spiffe_broker.rs b/crates/openshell-server/src/spiffe_broker.rs index 5498b6f2c1..fd298a5c67 100644 --- a/crates/openshell-server/src/spiffe_broker.rs +++ b/crates/openshell-server/src/spiffe_broker.rs @@ -7,6 +7,7 @@ //! [`SandboxIdentityProvider`]; this module chooses the SPIRE adapter when //! `[openshell.gateway.spiffe_broker]` is configured. use std::sync::Arc; +use std::time::{Duration, Instant}; use openshell_core::config::{ Config, GatewayJwtConfig, SpiffeBrokerConfig, SpiffeWorkloadIdentityConfig, @@ -14,6 +15,8 @@ use openshell_core::config::{ use openshell_core::sandbox_generation::SandboxGenerationId; use openshell_core::token_grant_failure::TokenGrantFailure; use openshell_spiffe::{SandboxIdentityProvider, SandboxSpiffeIdPrefix}; +use spiffe::{JwtBundleSet, WorkloadApiClient, WorkloadApiError}; +use tokio::sync::Mutex; /// Check the broker settings `config` enables without building them. /// @@ -31,6 +34,13 @@ pub fn validate_config(config: &Config) -> Result<(), String> { pub struct SupervisorWorkloadIdentity { prefix: SandboxSpiffeIdPrefix, gateway_id: String, + workload_api_socket_path: std::path::PathBuf, + jwt_bundles: Arc>>, +} + +struct JwtBundleSnapshot { + fetched_at: Instant, + bundles: Arc, } impl SupervisorWorkloadIdentity { @@ -73,6 +83,8 @@ impl SupervisorWorkloadIdentity { Ok(Some(Self { prefix, gateway_id: jwt.gateway_id.clone(), + workload_api_socket_path: workload.workload_api_socket_path.clone(), + jwt_bundles: Arc::default(), })) } @@ -90,6 +102,34 @@ impl SupervisorWorkloadIdentity { self.prefix .supervisor_launch_spiffe_id(&self.gateway_id, sandbox_id, generation.as_str()) } + + #[cfg(test)] + pub(crate) async fn seed_test_jwt_bundles(&self, bundles: JwtBundleSet) { + *self.jwt_bundles.lock().await = Some(JwtBundleSnapshot { + fetched_at: Instant::now(), + bundles: Arc::new(bundles), + }); + } + + pub(crate) async fn jwt_bundles(&self) -> Result, WorkloadApiError> { + // Share a very recent bundle across grants. An expired snapshot never + // authorizes a request if the Workload API fails during refresh. + let mut snapshot = self.jwt_bundles.lock().await; + if let Some(snapshot) = snapshot.as_ref() + && snapshot.fetched_at.elapsed() < Duration::from_secs(5) + { + return Ok(snapshot.bundles.clone()); + } + + let endpoint = openshell_spiffe::workload_api_endpoint(&self.workload_api_socket_path); + let client = WorkloadApiClient::connect_to(&endpoint).await?; + let bundles = Arc::new(client.fetch_jwt_bundles().await?); + *snapshot = Some(JwtBundleSnapshot { + fetched_at: Instant::now(), + bundles: bundles.clone(), + }); + Ok(bundles) + } } /// The sandbox identity provider `config` enables, if any. @@ -122,3 +162,43 @@ fn enabled(config: &Config) -> Result, String> { } Ok(Some(broker)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn jwt_bundles_serves_a_fresh_snapshot_and_never_a_stale_one() { + let identity = SupervisorWorkloadIdentity::from_settings( + Some(&SpiffeWorkloadIdentityConfig { + spiffe_id_prefix: "spiffe://test.example".into(), + workload_api_socket_path: "/nonexistent/workload.sock".into(), + }), + Some(&GatewayJwtConfig { + gateway_id: "bundle-test".into(), + ttl_secs: std::num::NonZeroU64::new(300), + signing_key_path: std::path::PathBuf::default(), + public_key_path: std::path::PathBuf::default(), + kid_path: std::path::PathBuf::default(), + }), + false, + ) + .unwrap() + .unwrap(); + let bundles = Arc::new(JwtBundleSet::new()); + let aged = |age| { + Some(JwtBundleSnapshot { + fetched_at: Instant::now().checked_sub(age).unwrap(), + bundles: bundles.clone(), + }) + }; + // The Workload API socket does not exist, so every refresh fails. + *identity.jwt_bundles.lock().await = aged(Duration::from_secs(6)); + assert!(identity.jwt_bundles().await.is_err()); + *identity.jwt_bundles.lock().await = aged(Duration::ZERO); + assert!(Arc::ptr_eq( + &identity.jwt_bundles().await.unwrap(), + &bundles + )); + } +} From 8ed1b3b94d7e94469aa68e548c5c047a71fe72cb Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:35:01 +0530 Subject: [PATCH 5/5] 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 {