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 {