From 1358794c2d217143660e01665ed416a2a2291bb9 Mon Sep 17 00:00:00 2001 From: Shiju Date: Sun, 29 Nov 2026 04:24:27 +0530 Subject: [PATCH 1/2] 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/2] 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 {