From 2e6c1d4ad57573cf62f82d8b04b7bc8622accd33 Mon Sep 17 00:00:00 2001 From: Shiju Date: Fri, 4 Dec 2026 17:07:46 +0530 Subject: [PATCH] feat(gateway): broker provider grants for a live local workload Signed-off-by: Shiju --- .../src/embedded/test_support.rs | 6 +- crates/openshell-server/src/grpc/provider.rs | 51 +- .../src/grpc/provider/access_token.rs | 613 +++++++++++++----- .../provider/access_token/broker_tests.rs | 514 +++++++++++++++ crates/openshell-spiffe/src/lib.rs | 16 +- crates/openshell-spire/src/broker.rs | 214 +++++- crates/openshell-spire/src/lib.rs | 15 +- 7 files changed, 1197 insertions(+), 232 deletions(-) create mode 100644 crates/openshell-server/src/grpc/provider/access_token/broker_tests.rs diff --git a/crates/openshell-credential-issuer/src/embedded/test_support.rs b/crates/openshell-credential-issuer/src/embedded/test_support.rs index 1cbf8e5b91..1ff8cb7f2e 100644 --- a/crates/openshell-credential-issuer/src/embedded/test_support.rs +++ b/crates/openshell-credential-issuer/src/embedded/test_support.rs @@ -146,7 +146,11 @@ impl CredentialDriver for TestStaticCredentialDriver { responses.push(ResolvedCredential { request_id: request.request_id, value, - expiration_time: None, + expiration_time: handle.metadata.get("test_expiration_ms").map(|expiry| { + let expiry = expiry.parse().expect("test expiry in milliseconds"); + openshell_core::time::timestamp_from_millis(expiry) + .expect("test expiry timestamp") + }), }); } diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index bfc34f9835..5a31c980b1 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -4829,6 +4829,13 @@ async fn exchange_provider_subject_token_inner( ) .to_status_with_code(code)); } + // Local broker mode obtains the final token at the gateway. The legacy + // exchange would bypass the trusted driver's live workload checks. + if access_token::uses_local_broker(state) { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } drop(request); if req.provider.trim().is_empty() @@ -4920,7 +4927,7 @@ async fn exchange_provider_subject_token_inner( &provider, &subject_token.credential, )?; - let stored_subject_token = + let (stored_subject_token, _) = resolve_subject_token_credential(&state.credentials, &provider, &subject_token.credential) .await?; @@ -5013,29 +5020,37 @@ async fn resolve_subject_token_credential( credentials: &crate::credentials::CredentialRuntime, provider: &Provider, credential_key: &str, -) -> Result { +) -> Result<(String, Option), Status> { // Check the provider's expiry before asking a credential driver to resolve // a handle; stale stored material cannot authorize another grant attempt. - ensure_subject_token_credential_not_expired(provider, credential_key)?; + let provider_expires_at_ms = + ensure_subject_token_credential_not_expired(provider, credential_key)?; if let Some(value) = provider .credentials .get(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + return Ok((value.clone(), provider_expires_at_ms)); } if provider.credential_handles.contains_key(credential_key) { - let resolved = credentials + let mut resolved = credentials .resolve_provider_handles(provider, crate::persistence::current_time_ms()) .await .map_err(token_grant_dependency_status)?; if let Some(value) = resolved .values - .get(credential_key) + .remove(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + let expires_at_ms = provider_expires_at_ms + .into_iter() + .chain(resolved.expires_at_ms.get(credential_key).copied()) + .min(); + if expires_at_ms.is_some_and(|expiry| expiry <= crate::persistence::current_time_ms()) { + return Err(token_grant_authorization_required_status()); + } + return Ok((value, expires_at_ms)); } } @@ -5045,12 +5060,12 @@ async fn resolve_subject_token_credential( fn ensure_subject_token_credential_not_expired( provider: &Provider, credential_key: &str, -) -> Result<(), Status> { +) -> Result, Status> { let expires_at_ms = provider_credential_expiration_ms(provider, credential_key)?; if expires_at_ms.is_some_and(|value| value <= crate::persistence::current_time_ms()) { return Err(token_grant_authorization_required_status()); } - Ok(()) + Ok(expires_at_ms) } /// The user's stored subject credential is absent or expired. Only the user @@ -6434,8 +6449,11 @@ pub(super) mod tests { let error = ensure_subject_token_credential_not_expired(&provider, "SUBJECT_TOKEN") .expect_err("the Unix epoch is a present, expired timestamp"); assert_eq!(error.code(), Code::FailedPrecondition); - ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") - .expect("an absent expiration remains non-expiring"); + assert_eq!( + ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") + .expect("an absent expiration remains non-expiring"), + None + ); } mod token_grant_failures { @@ -12191,12 +12209,21 @@ pub(super) mod tests { .unwrap(); provider.credential_handles = handles; - let subject_token = + let expires_at_ms = crate::persistence::current_time_ms() + 60_000; + provider + .credential_handles + .get_mut("subject_token") + .unwrap() + .metadata + .insert("test_expiration_ms".into(), expires_at_ms.to_string()); + + let (subject_token, subject_expires_at_ms) = resolve_subject_token_credential(&credentials, &provider, "subject_token") .await .unwrap(); assert_eq!(subject_token, "user-token"); + assert_eq!(subject_expires_at_ms, Some(expires_at_ms)); } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index a65d10cf52..c3106c8448 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -4,14 +4,14 @@ //! Gateway-owned sandbox identity and provider-token acquisition. //! The caller selects an attached configured credential, never grant parameters. use super::{ - Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectWorkspace, Principal, - Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, Status, - TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, + Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectName, ObjectWorkspace, + Principal, Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, + Status, TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, canonical_request_id, effective_jwt_svid_audience, fetch_gateway_jwt_svid_from, get_provider_type_profile_for_scope, insert_dynamic_credentials_for_profile, jwt_exp_ms, log_token_grant_failure, oauth, perform_intermediate_token_exchange, - provider_credential_expiration_ms, resolve_subject_token_credential, - sanitize_token_grant_status, token_exchange_http_client, token_grant_configuration_status, + resolve_subject_token_credential, sanitize_token_grant_status, token_exchange_http_client, + token_grant_authorization_required_status, token_grant_configuration_status, token_grant_dependency_status, token_grant_identity_rejected, token_grant_store_status, }; use openshell_core::jwt::AuthenticatedSandboxSession; @@ -20,12 +20,19 @@ use openshell_core::proto::{ ProviderCredentialTokenGrant, }; use openshell_core::token_grant_failure::BROKERED_TOKEN_GATEWAY_DEADLINE; -use openshell_spiffe::SandboxIdentityProvider; +use openshell_core::workload_reference::LocalProcessHandle; +use openshell_spiffe::{SandboxIdentityProvider, SandboxJwtSvid, SandboxWorkloadReference}; use std::time::Duration; static ACCESS_TOKENS: LazyLock = LazyLock::new(IntermediateTokenCache::new); static ACQUISITIONS: LazyLock = LazyLock::new(Acquisitions::default); -static ADMISSION: LazyLock = LazyLock::new(Admission::default); +static REQUEST_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static EXCHANGE_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static MISS_ADMISSION: LazyLock = LazyLock::new(Admission::default); +const PER_SANDBOX_EXCHANGE_LIMIT: usize = 4; +const PER_SANDBOX_REQUEST_LIMIT: usize = 16; +// Reserve request capacity for warm grants while other grants wait on OAuth. +const PER_SANDBOX_MISS_LIMIT: usize = PER_SANDBOX_REQUEST_LIMIT - PER_SANDBOX_EXCHANGE_LIMIT; pub(in crate::grpc) async fn handle( state: &Arc, @@ -63,10 +70,11 @@ pub(in crate::grpc) async fn handle( /// Verify the original bearer again after asynchronous work, including expiry /// and the persisted generation, epoch, active phase, and current token lineage. +/// A new launch has a new generation, so a bearer of an earlier launch fails. async fn authorize( state: &ServerState, bearer: &str, -) -> Result { +) -> Result<(AuthenticatedSandboxSession, Sandbox), Status> { let authority = state .sandbox_session_jwt_authority .as_ref() @@ -77,10 +85,11 @@ async fn authorize( if session.expires_at.saturating_mul(1000) <= crate::persistence::current_time_ms() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - crate::auth::sandbox_session::authorize_persisted(&state.store, &session) - .await - .map_err(|error| error.status)?; - Ok(session) + let (sandbox, _) = + crate::auth::sandbox_session::authorize_persisted_sandbox(&state.store, &session) + .await + .map_err(|error| error.status)?; + Ok((session, sandbox)) } /// One configured credential of an attached provider. @@ -89,6 +98,17 @@ struct ConfiguredGrant { grant: ProviderCredentialTokenGrant, /// The gateway's exact key for the credential, including its endpoint owner. key: String, + attachment_epoch: String, +} + +#[allow(clippy::result_large_err)] +fn provider_attachment<'a>(sandbox: &'a Sandbox, provider_name: &str) -> Result<&'a str, Status> { + sandbox + .spec + .as_ref() + .filter(|spec| spec.providers.iter().any(|name| name == provider_name)) + .map(|spec| spec.provider_attachment_epoch.as_str()) + .ok_or_else(|| token_grant_configuration_status(tonic::Code::PermissionDenied)) } /// Resolve the exact configured credential from the gateway's approved profile. @@ -98,7 +118,7 @@ struct ConfiguredGrant { /// generation a supervisor adds; a different or missing owner matches nothing. async fn grant_configuration( state: &ServerState, - sandbox_id: &str, + sandbox: &Sandbox, key: &str, ) -> Result { let invalid = || token_grant_configuration_status(tonic::Code::PermissionDenied); @@ -107,16 +127,7 @@ async fn grant_configuration( let identity = openshell_core::dynamic_credential_key::credential_identity(&key).ok_or_else(invalid)?; let (provider_name, _) = identity.split_once(':').ok_or_else(invalid)?; - let sandbox = state - .store - .get_message::(sandbox_id) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(invalid)?; - let spec = sandbox.spec.as_ref().ok_or_else(invalid)?; - if !spec.providers.iter().any(|name| name == provider_name) { - return Err(invalid()); - } + let attachment_epoch = provider_attachment(sandbox, provider_name)?.to_owned(); let provider = state .store .get_message_by_name::(sandbox.object_workspace(), provider_name) @@ -148,31 +159,35 @@ async fn grant_configuration( provider, grant, key, + attachment_epoch, }) } /// Bind a cached token to its runtime, configured credential, and subject. /// -/// Include the provider revision and resolved subject token, so an in-place -/// rotation of a handle-backed subject never serves a token minted from the -/// previous one. The digest is an in-memory map key and is never exposed. +/// Include the provider revision and resolved subject token. A request +/// that resolves a rotated subject gets a different key. The digest is an +/// in-memory map key and is never exposed. fn cache_key( session: &AuthenticatedSandboxSession, configured: &ConfiguredGrant, subject: Option<&str>, gateway_id: &str, + workload: &[u8], ) -> Result { let resource_version = configured .provider .metadata .as_ref() .map_or(0, |metadata| metadata.resource_version); - let fields: [&[u8]; 11] = [ + let fields: [&[u8]; 13] = [ b"openshell-provider-access-token-v1", gateway_id.as_bytes(), session.sandbox_id.as_str().as_bytes(), session.runtime_generation.as_str().as_bytes(), &session.auth_epoch.get().to_be_bytes(), + configured.attachment_epoch.as_bytes(), + workload, configured.provider.object_id().as_bytes(), &resource_version.to_be_bytes(), configured.key.as_bytes(), @@ -202,6 +217,193 @@ struct Subject { expires_at_ms: Option, } +async fn resolve_subject( + state: &ServerState, + configured: &ConfiguredGrant, +) -> Result, Status> { + let configuration_failure = + || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let grant_type = ProviderCredentialTokenGrantType::try_from(configured.grant.grant_type) + .map_err(|_| configuration_failure())?; + if grant_type != ProviderCredentialTokenGrantType::TokenExchange { + return Ok(None); + } + let subject = configured + .grant + .subject_token + .as_ref() + .filter(|subject| subject.source == "provider_credential") + .ok_or_else(configuration_failure)?; + let (value, expires_at_ms) = resolve_subject_token_credential( + &state.credentials, + &configured.provider, + &subject.credential, + ) + .await?; + Ok(Some(Subject { + expires_at_ms, + value, + token_type: subject.subject_token_type.clone(), + })) +} + +/// Recheck the authorized grant and session after waits and before exposing +/// credentials to the issuer or returning an access token to the sandbox. +struct GrantAuthorization<'a> { + state: &'a ServerState, + bearer: &'a str, + session: &'a AuthenticatedSandboxSession, + /// The request's first snapshot. It only locates the provider; `revalidate` reads a fresh one. + sandbox: &'a Sandbox, + key: &'a str, + gateway_id: &'a str, + fingerprint: &'a str, + subject: Option<&'a Subject>, + workload: &'a GrantWorkload, + workload_binding: &'a [u8], +} + +impl GrantAuthorization<'_> { + async fn revalidate(&self) -> Result, Status> { + let current = grant_configuration(self.state, self.sandbox, self.key).await?; + let resolved; + let subject = if matches!(self.workload, GrantWorkload::Local(_)) && self.subject.is_some() + { + // A driver can replace a subject without changing the Provider row. + resolved = resolve_subject(self.state, ¤t).await?; + resolved.as_ref() + } else { + self.subject + }; + let subject_value = subject.map(|subject| subject.value.as_str()); + if cache_key( + self.session, + ¤t, + subject_value, + self.gateway_id, + self.workload_binding, + )? != self.fingerprint + { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + // Profile and subject lookup may await storage. Check the attachment + // and session on the same fresh snapshot afterward. + let sandbox = self.workload.reauthorize(self.state, self.bearer).await?; + if provider_attachment(&sandbox, current.provider.object_name())? + != current.attachment_epoch + { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + let subject_expiry = [self.subject, subject] + .into_iter() + .flatten() + .filter_map(|subject| subject.expires_at_ms) + .min(); + if subject_expiry.is_some_and(|expiry| expiry <= crate::persistence::current_time_ms()) { + return Err(token_grant_authorization_required_status()); + } + Ok(subject_expiry) + } +} + +enum GrantWorkload { + Kubernetes(String), + Local(LocalProcessHandle), +} + +impl GrantWorkload { + async fn resolve(state: &ServerState, sandbox: &Sandbox) -> Result { + if state.compute.configured_driver_name() == "kubernetes" { + return Ok(Self::Kubernetes(kubernetes_runtime(sandbox)?.to_owned())); + } + if !uses_local_broker(state) { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + state + .compute + .resolve_provider_workload_process(sandbox) + .await + .map(Self::Local) + .map_err(|_| token_grant_identity_rejected(tonic::Code::PermissionDenied)) + } + + fn cache_binding(&self) -> Vec { + match self { + Self::Kubernetes(runtime) => runtime.as_bytes().to_vec(), + Self::Local(process) => process.reference().encode_to_vec(), + } + } + + #[allow(clippy::result_large_err)] + fn broker_reference(&self) -> Result, Status> { + match self { + Self::Kubernetes(runtime) => Ok(SandboxWorkloadReference::Kubernetes(runtime)), + Self::Local(process) => std::num::NonZeroU32::new(process.reference().pid) + .map(SandboxWorkloadReference::LocalProcess) + .ok_or_else(|| token_grant_identity_rejected(tonic::Code::PermissionDenied)), + } + } + + async fn reauthorize(&self, state: &ServerState, bearer: &str) -> Result { + let (_, sandbox) = authorize(state, bearer).await?; + let reject = || token_grant_identity_rejected(tonic::Code::PermissionDenied); + match self { + Self::Kubernetes(runtime) => { + if kubernetes_runtime(&sandbox)? != runtime { + return Err(reject()); + } + Ok(sandbox) + } + Self::Local(process) => { + // The driver can replace a container while the gateway waits + // for SPIRE or OAuth. Ask about the current generation and + // retain the pidfd for the original process across both calls. + let current = state + .compute + .resolve_provider_workload_process(&sandbox) + .await + .map_err(|_| reject())?; + if current.reference() != process.reference() { + return Err(reject()); + } + let (_, sandbox) = authorize(state, bearer).await?; + process.ensure_live().map_err(|_| reject())?; + Ok(sandbox) + } + } + } +} + +#[allow(clippy::result_large_err)] +fn kubernetes_runtime(sandbox: &Sandbox) -> Result<&str, Status> { + sandbox + .metadata + .as_ref() + .and_then(|metadata| { + metadata + .annotations + .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) + }) + .map(String::as_str) + .filter(|runtime| !runtime.is_empty()) + .ok_or_else(|| token_grant_identity_rejected(tonic::Code::PermissionDenied)) +} + +/// A Unix broker endpoint selects host-local workload identity for grants. +pub(super) fn uses_local_broker(state: &ServerState) -> bool { + state + .config + .spiffe_broker + .as_ref() + .is_some_and(|broker| broker.endpoint.starts_with("unix:")) +} + #[allow(clippy::too_many_lines)] async fn obtain( state: &Arc, @@ -221,30 +423,23 @@ async fn obtain( if values.next().is_some() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - let session = authorize(state, &bearer).await?; + let (session, sandbox) = authorize(state, &bearer).await?; if principal.sandbox_id != session.sandbox_id.as_str() { return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); } - // Bound outstanding work after authentication, independently of caching. - // A busy sandbox cannot occupy the gateway's entire acquisition budget. - let _admission = ADMISSION.enter(session.sandbox_id.as_str())?; - // Startup enables an identity provider only with gateway session JWTs. - let (Some(identity), Some(gateway_jwt)) = ( - state.sandbox_identity.as_deref(), - state.config.gateway_jwt.as_ref(), - ) else { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); + let unavailable = || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let gateway_jwt = state.config.gateway_jwt.as_ref().ok_or_else(unavailable)?; + let identity = state.sandbox_identity.as_deref().ok_or_else(unavailable)?; + let local = state.compute.configured_driver_name() != "kubernetes"; + let request_limit = if local { + PER_SANDBOX_REQUEST_LIMIT + } else { + PER_SANDBOX_EXCHANGE_LIMIT }; - if state.compute.configured_driver_name() != "kubernetes" { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - } + let _request_admission = REQUEST_ADMISSION.enter(session.sandbox_id.as_str(), request_limit)?; let gateway_id = gateway_jwt.gateway_id.as_str(); let key = &request.get_ref().credential_key; - let configured = grant_configuration(state, session.sandbox_id.as_str(), key).await?; + let configured = grant_configuration(state, &sandbox, key).await?; let grant = &configured.grant; let ttl_override = grant .cache_ttl @@ -259,53 +454,51 @@ async fn obtain( tonic::Code::InvalidArgument, )); } - let grant_type = ProviderCredentialTokenGrantType::try_from(grant.grant_type) - .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - // Resolve the subject before any cache lookup, so its revocation or - // expiry also denies cached tokens. - let subject = if grant_type == ProviderCredentialTokenGrantType::TokenExchange { - let subject = grant - .subject_token - .as_ref() - .filter(|subject| subject.source == "provider_credential") - .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - Some(Subject { - expires_at_ms: provider_credential_expiration_ms( - &configured.provider, - &subject.credential, - )?, - value: resolve_subject_token_credential( - &state.credentials, - &configured.provider, - &subject.credential, - ) - .await?, - token_type: subject.subject_token_type.clone(), - }) - } else { - None - }; + // Resolve the subject before any cache lookup so its value binds the token. + let subject = resolve_subject(state, &configured).await?; let subject_value = subject.as_ref().map(|subject| subject.value.as_str()); - let fingerprint = cache_key(&session, &configured, subject_value, gateway_id)?; + let workload = GrantWorkload::resolve(state, &sandbox).await?; + let workload_binding = workload.cache_binding(); + let fingerprint = cache_key( + &session, + &configured, + subject_value, + gateway_id, + &workload_binding, + )?; + let authorization = GrantAuthorization { + state, + bearer: &bearer, + session: &session, + sandbox: &sandbox, + key, + gateway_id, + fingerprint: &fingerprint, + subject: subject.as_ref(), + workload: &workload, + workload_binding: &workload_binding, + }; // A zero override disables caching, and with it shared acquisition. let caching = ttl_override != Some(Duration::ZERO); - let mut refresh = false; + let mut retried_expired_hit = false; loop { let cached = || { - (caching && !refresh) + caching .then(|| ACCESS_TOKENS.get_until(&fingerprint)) .flatten() - .filter(|(_, until)| { - *until > crate::persistence::current_time_ms().saturating_add(1000) - }) }; // A miss holds its fingerprint's turn until its token is cached, so // concurrent misses wait and then find it. A miss is cached only after // the final validation below, which a hit passes as well. let mut turn = None; + let miss_admission; let (response, serve_until_ms, acquired) = if let Some((token, until)) = cached() { + miss_admission = None; (token, until, false) } else { + miss_admission = local + .then(|| MISS_ADMISSION.enter(session.sandbox_id.as_str(), PER_SANDBOX_MISS_LIMIT)) + .transpose()?; let waited = if caching { Some(ACQUISITIONS.turn(&fingerprint).await?) } else { @@ -315,42 +508,32 @@ async fn obtain( (token, until, false) } else { turn = waited; - let (token, until) = acquire( - state, - &bearer, - &session, - identity, - gateway_id, - grant, - subject.as_ref(), - ttl_override, - request_id, - ) - .await - .inspect_err(|status| { - if let Some(turn) = turn.as_mut() { - *turn.failure = Some(status.clone()); - } - })?; + let _exchange_admission = local + .then(|| { + EXCHANGE_ADMISSION + .enter(session.sandbox_id.as_str(), PER_SANDBOX_EXCHANGE_LIMIT) + }) + .transpose()?; + let (token, until) = + acquire(&authorization, identity, grant, ttl_override, request_id) + .await + .inspect_err(|status| { + if let Some(turn) = turn.as_mut() { + turn.record_failure(status); + } + })?; (token, until, true) } }; - // Re-read attachment, provider revision, and profile, then the session, - // before serving or caching any token. - let current = grant_configuration(state, session.sandbox_id.as_str(), key).await?; - if cache_key(&session, ¤t, subject_value, gateway_id)? != fingerprint { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - } - authorize(state, &bearer).await?; + let subject_expiry = authorization.revalidate().await?; // The lifetime runs from when the token service answered, so time spent // in the final validation counts against it. - let remaining_ms = serve_until_ms.saturating_sub(crate::persistence::current_time_ms()); - if remaining_ms <= 0 && !acquired { - // A hit can expire during the final asynchronous checks. Refresh once; - // a fresh acquisition still must pass every check before it is served. - refresh = true; + let now_ms = crate::persistence::current_time_ms(); + let serve_until_ms = serve_until_ms.min(subject_expiry.unwrap_or(i64::MAX)); + let remaining_ms = serve_until_ms.saturating_sub(now_ms); + if remaining_ms <= 0 && !acquired && !retried_expired_hit { + // Another request may already have refreshed the expired entry. + retried_expired_hit = true; continue; } if remaining_ms <= 0 { @@ -364,70 +547,66 @@ async fn obtain( ACCESS_TOKENS.set(fingerprint, &response, serve_until_ms); } drop(turn); - return Ok(Response::new(GetSandboxProviderAccessTokenResponse { + let response = Response::new(GetSandboxProviderAccessTokenResponse { access_token: response.access_token, token_type: response.token_type, expires_after: openshell_core::time::duration_from_std(Duration::from_millis( u64::try_from(remaining_ms).unwrap_or_default(), )) .ok(), - })); + }); + drop(miss_admission); + return Ok(response); } } -/// Acquire a final token, re-authorizing the session between network calls. +#[allow(clippy::result_large_err)] +fn require_live_assertion(svid: &SandboxJwtSvid, now_ms: i64) -> Result<(), Status> { + if svid.expires_at.saturating_mul(1000) <= now_ms { + return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); + } + Ok(()) +} + +/// Acquire a final token, rechecking the grant before each OAuth exchange. /// Returns the token and when to stop serving it. -#[allow(clippy::too_many_arguments)] async fn acquire( - state: &ServerState, - bearer: &str, - session: &AuthenticatedSandboxSession, + authorization: &GrantAuthorization<'_>, identity: &dyn SandboxIdentityProvider, - gateway_id: &str, grant: &ProviderCredentialTokenGrant, - subject: Option<&Subject>, ttl_override: Option, request_id: Option<&str>, ) -> Result<(oauth::OAuthTokenResponse, i64), Status> { - authorize(state, bearer).await?; + let GrantAuthorization { + state, + session, + gateway_id, + subject, + .. + } = *authorization; let audience = effective_jwt_svid_audience(&grant.token_endpoint, &grant.jwt_svid_audience); - let sandbox = state - .store - .get_message::(session.sandbox_id.as_str()) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(|| token_grant_identity_rejected(tonic::Code::Unauthenticated))?; - let runtime_identity = sandbox - .metadata - .as_ref() - .and_then(|metadata| { - metadata - .annotations - .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) - }) - .map_or("", String::as_str); + authorization.revalidate().await?; let svid = identity .fetch_jwt_svid( gateway_id, session.sandbox_id.as_str(), &audience, - runtime_identity, + authorization.workload.broker_reference()?, ) .await .map_err(TokenGrantFailure::to_status)?; - authorize(state, bearer).await?; + let check_expiry = || require_live_assertion(&svid, crate::persistence::current_time_ms()); let client = token_exchange_http_client()?; - let subject_expiry = subject.and_then(|subject| subject.expires_at_ms); + let mut subject_expiry = i64::MAX; let token = if let Some(subject) = subject { - let component_svid = fetch_gateway_jwt_svid_from( - &audience, - state - .config - .spiffe_broker - .as_ref() - .map(|broker| broker.workload_api_socket_path.as_str()), - ) - .await?; + let component_socket = state + .config + .spiffe_broker + .as_ref() + .map(|broker| broker.workload_api_socket_path.as_str()); + let component_svid = fetch_gateway_jwt_svid_from(&audience, component_socket).await?; + subject_expiry = authorization.revalidate().await?.unwrap_or(i64::MAX); + check_expiry()?; let intermediate = perform_intermediate_token_exchange( &grant.token_endpoint, &TokenExchangeParams { @@ -442,7 +621,8 @@ async fn acquire( request_id, ) .await?; - authorize(state, bearer).await?; + subject_expiry = subject_expiry.min(authorization.revalidate().await?.unwrap_or(i64::MAX)); + check_expiry()?; oauth::post_oauth_token_exchange( client, &grant.token_endpoint, @@ -460,6 +640,8 @@ async fn acquire( .await .map_err(TokenGrantFailure::to_status)? } else { + authorization.revalidate().await?; + check_expiry()?; oauth::post_oauth_token_grant( client, &grant.token_endpoint, @@ -475,11 +657,12 @@ async fn acquire( .map_err(TokenGrantFailure::to_status)? }; let obtained_at_ms = crate::persistence::current_time_ms(); + require_live_assertion(&svid, obtained_at_ms)?; let identity_expires_at_ms = session .expires_at .saturating_mul(1000) .min(svid.expires_at.saturating_mul(1000)) - .min(subject_expiry.unwrap_or(i64::MAX)); + .min(subject_expiry); let serve_until_ms = serve_until_ms(&token, ttl_override, obtained_at_ms, identity_expires_at_ms).ok_or_else( || { @@ -490,7 +673,6 @@ async fn acquire( .to_status() }, )?; - authorize(state, bearer).await?; Ok((token, serve_until_ms)) } @@ -541,13 +723,14 @@ struct Admission { } impl Admission { - fn enter(&self, sandbox: &str) -> Result, Status> { + fn enter(&self, sandbox: &str, per_sandbox_limit: usize) -> Result, Status> { let mut active = self .active .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if active.values().sum::() >= 64 - || active.get(sandbox).copied().unwrap_or_default() >= 4 + // Sixteen sandboxes at their own limit fill the gateway, whatever that limit is. + if active.values().sum::() >= per_sandbox_limit * 16 + || active.get(sandbox).copied().unwrap_or_default() >= per_sandbox_limit { return Err(TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, @@ -587,8 +770,9 @@ impl Drop for AdmissionGuard<'_> { /// Coordinate token acquisition separately for each cache fingerprint. /// /// Concurrent misses share a single acquisition without locking unrelated -/// tokens. Current waiters receive the holder's acquisition failure; a new -/// group can retry after they leave. Entries exist only while held or awaited. +/// tokens. Current waiters share dependency outages. A caller's authorization +/// failure leaves the turn available to its waiters. Entries live only while +/// held or awaited. #[derive(Default)] struct Acquisitions { slots: std::sync::Mutex, @@ -647,6 +831,29 @@ struct AcquisitionTurn<'a> { _registration: Registration<'a>, } +impl AcquisitionTurn<'_> { + fn record_failure(&mut self, status: &Status) { + let failure = TokenGrantFailure::from_status(status); + if matches!( + (failure.kind(), failure.upstream_status()), + ( + TokenGrantFailureKind::Unavailable, + None | Some(429 | 500..=599) + ) | (TokenGrantFailureKind::Timeout, _) + ) && matches!( + failure.stage(), + TokenGrantStage::WorkloadIdentity + | TokenGrantStage::IntermediateExchange + | TokenGrantStage::TokenEndpoint + ) { + *self.failure = Some(status.clone()); + } + } +} + +#[cfg(test)] +mod broker_tests; + #[cfg(test)] mod tests { use super::*; @@ -655,22 +862,27 @@ mod tests { #[test] fn admission_is_bounded_per_sandbox_and_releases_cancelled_work() { let admission = Admission::default(); - let guards: Vec<_> = (0..4).map(|_| admission.enter("busy").unwrap()).collect(); - assert_eq!( - admission.enter("busy").err().unwrap().code(), - tonic::Code::ResourceExhausted - ); - let other = admission.enter("other").unwrap(); - drop(guards); - drop(admission.enter("busy").unwrap()); - drop(other); - assert!(admission.active.lock().unwrap().is_empty()); - let guards: Vec<_> = (0..64) - .map(|i| admission.enter(&i.to_string()).unwrap()) - .collect(); - assert!(admission.enter("overflow").is_err()); - drop(guards); - assert!(admission.active.lock().unwrap().is_empty()); + for limit in [PER_SANDBOX_EXCHANGE_LIMIT, PER_SANDBOX_REQUEST_LIMIT] { + let guards: Vec<_> = (0..limit) + .map(|_| admission.enter("busy", limit).unwrap()) + .collect(); + assert_eq!( + admission.enter("busy", limit).err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + let other = admission.enter("other", limit).unwrap(); + drop(guards); + drop(admission.enter("busy", limit).unwrap()); + drop(other); + assert!(admission.active.lock().unwrap().is_empty()); + // Sixteen sandboxes at this limit fill the gateway; the next is refused. + let guards: Vec<_> = (0..limit * 16) + .map(|i| admission.enter(&(i / limit).to_string(), limit).unwrap()) + .collect(); + assert!(admission.enter("overflow", limit).is_err()); + drop(guards); + assert!(admission.active.lock().unwrap().is_empty()); + } } #[tokio::test] async fn broker_requires_a_signed_session_even_with_a_sandbox_principal() { @@ -702,8 +914,8 @@ mod tests { fn fingerprint_binds_the_runtime_configured_key_and_resolved_subject() { use openshell_core::jwt::{CredentialEpoch, SandboxId}; let session = AuthenticatedSandboxSession { - sandbox_id: SandboxId::parse(uuid::Uuid::new_v4().to_string()).unwrap(), resource_binding: std::collections::BTreeMap::new(), + sandbox_id: SandboxId::parse(uuid::Uuid::new_v4().to_string()).unwrap(), runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( "g1", ) @@ -717,10 +929,11 @@ mod tests { provider: Provider::default(), grant: ProviderCredentialTokenGrant::default(), key: key.to_string(), + attachment_epoch: String::new(), }; let owned = "api.example.com\t443\t/v1/**\towner\tprovider:access"; let fingerprint = |session, key, subject| { - cache_key(session, &configured(key), subject, "gateway").unwrap() + cache_key(session, &configured(key), subject, "gateway", b"runtime").unwrap() }; let base = fingerprint(&session, owned, Some("subject-a")); // A renewed session token of the same runtime shares cached tokens. @@ -732,6 +945,39 @@ mod tests { assert_eq!(fingerprint(&renewed, owned, Some("subject-a")), base); // A rotated subject, another credential, or another epoch does not. assert_ne!(fingerprint(&session, owned, Some("subject-b")), base); + let mut reattached = configured(owned); + reattached.attachment_epoch = "new-attachment".into(); + assert_ne!( + cache_key( + &session, + &reattached, + Some("subject-a"), + "gateway", + b"runtime" + ) + .unwrap(), + base + ); + assert_ne!( + cache_key( + &session, + &configured(owned), + Some("subject-a"), + "gateway", + b"replacement-process" + ) + .unwrap(), + base + ); + // Another runtime generation is another launch. + let relaunched = AuthenticatedSandboxSession { + runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( + "g2", + ) + .unwrap(), + ..session.clone() + }; + assert_ne!(fingerprint(&relaunched, owned, Some("subject-a")), base); let spoofed = owned.replace("owner", "other"); assert_ne!(fingerprint(&session, &spoofed, Some("subject-a")), base); let rotated = AuthenticatedSandboxSession { @@ -850,11 +1096,32 @@ mod tests { }) .await .expect("all requests should join the in-flight acquisition"); + holder.record_failure(&Status::unauthenticated("superseded bearer")); + assert!(holder.failure.is_none()); + let rejected_assertion = TokenGrantFailure::new( + TokenGrantFailureKind::Unclassified, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(401); + holder.record_failure(&rejected_assertion.to_status()); + assert!(holder.failure.is_none()); + // A token service that stalls after its headers is an outage too. + let stalled_body = TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(200); + holder.record_failure(&stalled_body.to_status()); + assert_eq!( + holder.failure.as_ref().map(TokenGrantFailure::from_status), + Some(stalled_body) + ); let expected = TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, TokenGrantStage::TokenEndpoint, - ); - *holder.failure = Some(expected.to_status()); + ) + .with_upstream_status(503); + holder.record_failure(&expected.to_status()); drop(holder); for waiter in waiters { let result = tokio::time::timeout(Duration::from_secs(5), waiter) diff --git a/crates/openshell-server/src/grpc/provider/access_token/broker_tests.rs b/crates/openshell-server/src/grpc/provider/access_token/broker_tests.rs new file mode 100644 index 0000000000..6b44607d25 --- /dev/null +++ b/crates/openshell-server/src/grpc/provider/access_token/broker_tests.rs @@ -0,0 +1,514 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use axum::{ + Json, Router, + extract::{Path, State}, + routing::post, +}; +use openshell_bootstrap::jwt::generate_jwt_key; +use openshell_core::config::GatewayJwtConfig; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use openshell_core::proto::{ + AttachSandboxProviderRequest, DetachSandboxProviderRequest, NetworkAccessPreset, + NetworkEndpoint, ProviderCredentialTokenGrantSubjectToken, ProviderProfile, + ProviderProfileCategory, ProviderProfileCredential, SandboxPhase, SandboxSpec, + workspace_selector, +}; +use std::{ + num::NonZeroU64, + path::PathBuf, + sync::atomic::{AtomicUsize, Ordering}, +}; +use tokio::{sync::Notify, task::JoinHandle}; +use uuid::Uuid; + +use super::*; +use crate::auth::principal::{SandboxIdentitySource, SandboxPrincipal}; +use crate::auth::sandbox_jwt::SandboxSessionJwtAuthority; +use crate::auth::sandbox_session::PersistedSandboxIdentity; +use crate::grpc::sandbox::{handle_attach_sandbox_provider, handle_detach_sandbox_provider}; +use crate::grpc::test_support::{authed_request, test_server_state_with_driver}; +use crate::persistence::current_time_ms; + +const GATEWAY_ID: &str = "performance-test-gateway"; +const ASSERTION_AUDIENCE: &str = "https://issuer.test/"; +const SUBJECT_KEY: &str = "subject_token"; +// Attaching a provider validates the sandbox name, and the sandbox ID is too long for one. +const SANDBOX_NAME: &str = "grant-sandbox"; + +#[derive(Debug)] +struct TestSandboxIdentity; + +#[async_trait::async_trait] +impl SandboxIdentityProvider for TestSandboxIdentity { + type Error = TokenGrantFailure; + + async fn fetch_jwt_svid( + &self, + gateway_id: &str, + sandbox_id: &str, + _audience: &str, + reference: SandboxWorkloadReference<'_>, + ) -> Result { + assert!( + matches!(reference, SandboxWorkloadReference::Kubernetes(value) if value.starts_with("kubernetes://ns/")) + ); + Ok(SandboxJwtSvid { + spiffe_id: format!("spiffe://test.example/gateway/{gateway_id}/sandbox/{sandbox_id}"), + token: "fixture-assertion".to_string(), + expires_at: current_time_ms() / 1000 + 300, + }) + } +} + +#[derive(Default)] +struct Issuer { + warm_calls: AtomicUsize, + cold_calls: AtomicUsize, + cold_started: Notify, + release_cold: Notify, +} + +async fn issue( + State(issuer): State>, + Path(grant): Path, +) -> Json { + let count = match grant.as_str() { + "warm" => issuer.warm_calls.fetch_add(1, Ordering::Relaxed) + 1, + "cold" => { + let count = issuer.cold_calls.fetch_add(1, Ordering::Relaxed) + 1; + if count == 1 { + issuer.cold_started.notify_one(); + issuer.release_cold.notified().await; + } + count + } + _ => panic!("unexpected grant route"), + }; + Json(serde_json::json!({ + "access_token": format!("{grant}-{count}"), + "token_type": "Bearer", + "expires_in": 300, + })) +} + +struct Fixture { + state: Arc, + issuer: Arc, + issuer_task: JoinHandle<()>, + id: String, + bearer: String, + warm_key: String, + cold_key: String, +} + +impl Fixture { + #[allow( + clippy::literal_string_with_formatting_args, + reason = "Axum routes use braces for path parameters" + )] + async fn new(warm_ttl_seconds: i64, warm_subject: Option<&str>) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let issuer = Arc::new(Issuer::default()); + let app = Router::new() + .route("/{grant}", post(issue)) + .with_state(issuer.clone()); + let issuer_task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let id = Uuid::new_v4().to_string(); + let provider_name = format!("grant-{id}"); + let mut state = test_server_state_with_driver("kubernetes").await; + let server = Arc::get_mut(&mut state).unwrap(); + server.config.gateway_jwt = Some(GatewayJwtConfig { + gateway_id: GATEWAY_ID.into(), + ttl_secs: NonZeroU64::new(300), + signing_key_path: PathBuf::default(), + public_key_path: PathBuf::default(), + kid_path: PathBuf::default(), + }); + server.sandbox_identity = Some(Arc::new(TestSandboxIdentity)); + let persisted = PersistedSandboxIdentity::new().unwrap(); + let gateway_key = generate_jwt_key().unwrap(); + let authority = Arc::new( + SandboxSessionJwtAuthority::from_pem( + gateway_key.signing_key_pem.as_bytes(), + gateway_key.public_key_pem.as_bytes(), + gateway_key.kid, + GATEWAY_ID, + Some(Duration::from_mins(5)), + ) + .unwrap(), + ); + let bearer = authority + .mint_persisted_launch(&id, &persisted) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + server.sandbox_session_jwt_authority = Some(authority); + let metadata = |name: &str| ObjectMeta { + id: name.into(), + name: name.into(), + workspace: "default".into(), + ..Default::default() + }; + let mut sandbox_meta = metadata(&id); + sandbox_meta.name = SANDBOX_NAME.into(); + persisted.write(&mut sandbox_meta.annotations); + sandbox_meta.annotations.insert( + crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION.into(), + format!("kubernetes://ns/{id}/runtime"), + ); + let mut sandbox = Sandbox { + metadata: Some(sandbox_meta), + spec: Some(SandboxSpec { + providers: vec![provider_name.clone()], + provider_attachment_epoch: "attachment".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + server.store.put_message(&sandbox).await.unwrap(); + let credential = |name: &str, header: &str, ttl_seconds| ProviderProfileCredential { + name: name.into(), + auth_style: "header".into(), + header_name: header.into(), + token_grant: Some(ProviderCredentialTokenGrant { + token_endpoint: format!("{base_url}/{name}"), + jwt_svid_audience: ASSERTION_AUDIENCE.into(), + grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, + cache_ttl: Some(prost_types::Duration { + seconds: ttl_seconds, + nanos: 0, + }), + ..Default::default() + }), + ..Default::default() + }; + let mut warm = credential("warm", "X-Warm-Token", warm_ttl_seconds); + let mut provider = Provider { + metadata: Some(metadata(&provider_name)), + r#type: format!("profile-{id}"), + ..Default::default() + }; + let mut subject_credentials = Vec::new(); + if let Some(value) = warm_subject { + let grant = warm.token_grant.as_mut().unwrap(); + grant.grant_type = ProviderCredentialTokenGrantType::TokenExchange.into(); + grant.subject_token = Some(ProviderCredentialTokenGrantSubjectToken { + source: "provider_credential".into(), + credential: SUBJECT_KEY.into(), + subject_token_type: oauth::ACCESS_TOKEN_TYPE.into(), + }); + subject_credentials.push(ProviderProfileCredential { + name: SUBJECT_KEY.into(), + ..Default::default() + }); + provider.credential_handles = server + .credentials + .store_provider_credentials( + &provider_name, + "default", + &provider_name, + &HashMap::from([(SUBJECT_KEY.into(), value.into())]), + &HashMap::new(), + ) + .await + .unwrap(); + } + subject_credentials.extend([warm, credential("cold", "X-Cold-Token", 300)]); + let profile = ProviderProfile { + id: provider.r#type.clone(), + display_name: "Grant performance test profile".into(), + category: ProviderProfileCategory::Other as i32, + endpoints: vec![NetworkEndpoint { + host: "api.example.test".into(), + port: 443, + path: "/**".into(), + protocol: "rest".into(), + access: NetworkAccessPreset::Full as i32, + ..Default::default() + }], + credentials: subject_credentials, + ..Default::default() + }; + let mut credentials = HashMap::new(); + insert_dynamic_credentials_for_profile( + &mut credentials, + &openshell_providers::ProviderTypeProfile::from_proto(&profile), + &provider_name, + &provider_name, + ) + .unwrap(); + let key = |name| { + credentials + .keys() + .find(|key| key.ends_with(name)) + .unwrap() + .clone() + }; + let (warm_key, cold_key) = (key(":warm"), key(":cold")); + server.store.put_message(&provider).await.unwrap(); + server + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + profile, + )) + .await + .unwrap(); + + Self { + state, + issuer, + issuer_task, + id, + bearer, + warm_key, + cold_key, + } + } + + fn request(&self, key: &str) -> Request { + let mut request = Request::new(GetSandboxProviderAccessTokenRequest { + credential_key: key.into(), + }); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: self.id.clone(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: format!("openshell-gateway:{GATEWAY_ID}"), + auth_epoch: None, + }, + trust_domain: None, + })); + request.metadata_mut().insert( + "authorization", + format!("Bearer {}", self.bearer).parse().unwrap(), + ); + request + } + + async fn fingerprint(&self, key: &str) -> String { + let (session, sandbox) = authorize(&self.state, &self.bearer).await.unwrap(); + let configured = grant_configuration(&self.state, &sandbox, key) + .await + .unwrap(); + let subject = resolve_subject(&self.state, &configured).await.unwrap(); + cache_key( + &session, + &configured, + subject.as_ref().map(|subject| subject.value.as_str()), + GATEWAY_ID, + kubernetes_runtime(&sandbox).unwrap().as_bytes(), + ) + .unwrap() + } + + fn spawn_request( + &self, + key: &str, + ) -> JoinHandle, Status>> { + let state = self.state.clone(); + let request = self.request(key); + tokio::spawn(async move { handle(&state, request).await }) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.issuer_task.abort(); + } +} + +fn cache(fingerprint: String, token: &str) { + ACCESS_TOKENS.set( + fingerprint, + &oauth::OAuthTokenResponse { + access_token: token.into(), + token_type: "Bearer".into(), + expires_in: 60, + }, + current_time_ms() + 60_000, + ); +} + +#[tokio::test] +async fn a_cache_hit_is_not_served_past_the_subject_expiry() { + let fixture = Fixture::new(300, Some("subject")).await; + let store = &fixture.state.store; + let mut provider = store + .get_message::(&format!("grant-{}", fixture.id)) + .await + .unwrap() + .unwrap(); + provider + .credential_handles + .get_mut(SUBJECT_KEY) + .unwrap() + .metadata + .insert( + "test_expiration_ms".into(), + (current_time_ms() + 10_000).to_string(), + ); + store.put_message(&provider).await.unwrap(); + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let response = handle(&fixture.state, fixture.request(&fixture.warm_key)) + .await + .unwrap() + .into_inner(); + assert_eq!(response.access_token, "cached-access-token"); + let lifetime = openshell_core::time::duration_to_std(&response.expires_after.unwrap()).unwrap(); + assert!( + lifetime <= Duration::from_secs(10), + "served for {lifetime:?}" + ); +} + +#[tokio::test] +async fn brokered_token_exchange_cache_hit_resolves_the_subject_once() { + let fixture = Fixture::new(300, Some("user-token")).await; + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let (first_read, release_first_read) = fixture.state.credentials.gate_next_resolve(); + let exchange = handle(&fixture.state, fixture.request(&fixture.warm_key)); + tokio::pin!(exchange); + tokio::select! { + result = &mut exchange => panic!("grant finished before resolving the subject: {result:?}"), + first_read = first_read => first_read.unwrap(), + } + let (second_read, _release_second_read) = fixture.state.credentials.gate_next_resolve(); + release_first_read.send(()).unwrap(); + let response = tokio::select! { + result = exchange => result.unwrap().into_inner(), + _ = second_read => panic!("cache hit resolved the subject again"), + }; + assert_eq!(response.access_token, "cached-access-token"); +} + +#[tokio::test] +async fn reattaching_provider_during_exchange_rejects_the_in_flight_token() { + let fixture = Fixture::new(300, None).await; + let exchange = fixture.spawn_request(&fixture.cold_key); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let provider = format!("grant-{}", fixture.id); + let detached = handle_detach_sandbox_provider( + &fixture.state, + authed_request(DetachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider: provider.clone(), + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(detached.detached); + let attached = handle_attach_sandbox_provider( + &fixture.state, + authed_request(AttachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider, + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(attached.attached); + fixture.issuer.release_cold.notify_one(); + + let error = exchange + .await + .unwrap() + .expect_err("reject the detached grant"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + let new_token = handle(&fixture.state, fixture.request(&fixture.cold_key)) + .await + .unwrap() + .into_inner(); + assert_eq!(new_token.access_token, "cold-2"); +} + +#[tokio::test] +async fn stopping_or_restarting_during_exchange_rejects_the_in_flight_token() { + for (restart, code) in [ + (false, tonic::Code::FailedPrecondition), + (true, tonic::Code::Unauthenticated), + ] { + let mut fixture = Fixture::new(300, None).await; + let warm = handle(&fixture.state, fixture.request(&fixture.warm_key)) + .await + .unwrap(); + assert_eq!(warm.into_inner().access_token, "warm-1"); + let old_warm_request = fixture.request(&fixture.warm_key); + let in_flight = fixture.spawn_request(&fixture.cold_key); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let store = fixture.state.store.clone(); + let mut sandbox = store + .get_message::(&fixture.id) + .await + .unwrap() + .unwrap(); + if restart { + // A restart installs a new identity: a new generation and launch. + let annotations = &mut sandbox.metadata.as_mut().unwrap().annotations; + let launch = PersistedSandboxIdentity::new().unwrap(); + launch.write(annotations); + let authority = fixture.state.sandbox_session_jwt_authority.as_ref(); + fixture.bearer = authority + .unwrap() + .mint_persisted_launch(&fixture.id, &launch) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + } else { + sandbox.set_phase(SandboxPhase::Stopping as i32); + } + store.put_message(&sandbox).await.unwrap(); + assert_eq!( + handle(&fixture.state, old_warm_request) + .await + .unwrap_err() + .code(), + code + ); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); + fixture.issuer.release_cold.notify_one(); + assert_eq!(in_flight.await.unwrap().unwrap_err().code(), code); + + // The rejected token was not cached: the next request exchanges again. + sandbox.set_phase(SandboxPhase::Ready as i32); + store.put_message(&sandbox).await.unwrap(); + let next = handle(&fixture.state, fixture.request(&fixture.cold_key)) + .await + .unwrap() + .into_inner(); + assert_eq!(next.access_token, "cold-2"); + } +} diff --git a/crates/openshell-spiffe/src/lib.rs b/crates/openshell-spiffe/src/lib.rs index 07ea123e43..49ccabd689 100644 --- a/crates/openshell-spiffe/src/lib.rs +++ b/crates/openshell-spiffe/src/lib.rs @@ -165,6 +165,15 @@ impl fmt::Debug for SandboxJwtSvid { } } +/// Workload named by a trusted compute driver for a brokered grant. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SandboxWorkloadReference<'a> { + /// Immutable Kubernetes Sandbox reference persisted by the gateway. + Kubernetes(&'a str), + /// Workload process visible to the SPIRE agent on the gateway host. + LocalProcess(std::num::NonZeroU32), +} + /// Source of verified sandbox JWT-SVIDs for the gateway's provider broker. /// /// The gateway authorizes the sandbox session and the provider credential @@ -177,9 +186,8 @@ pub trait SandboxIdentityProvider: fmt::Debug + Send + Sync { /// Obtain a JWT-SVID for `audience` whose identity is exactly the stable /// SPIFFE ID of `sandbox_id` under `gateway_id`. - /// `runtime_identity` is the compute driver's immutable runtime reference - /// persisted by the gateway. It must never come from a workload request; - /// adapters use it to bind issuance to the attested backing object. + /// The gateway derives the reference from the authenticated compute driver + /// and holds a local process live check across issuance and exchange. /// /// # Errors /// @@ -190,7 +198,7 @@ pub trait SandboxIdentityProvider: fmt::Debug + Send + Sync { gateway_id: &str, sandbox_id: &str, audience: &str, - runtime_identity: &str, + workload: SandboxWorkloadReference<'_>, ) -> Result; } diff --git a/crates/openshell-spire/src/broker.rs b/crates/openshell-spire/src/broker.rs index e58d9cf14e..921dc047c6 100644 --- a/crates/openshell-spire/src/broker.rs +++ b/crates/openshell-spire/src/broker.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! SPIFFE Broker API JWT profile with attested Kubernetes object references. +//! SPIFFE Broker API JWT profile with attested Kubernetes objects or node-local processes. use crate::{configuration_failure, identity_rejected}; use hyper_util::rt::TokioIo; @@ -9,7 +9,7 @@ use openshell_core::config::SpiffeBrokerConfig; use openshell_core::token_grant_failure::{ TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, WORKLOAD_IDENTITY_CALL_TIMEOUT, }; -use openshell_spiffe::SandboxJwtSvid; +use openshell_spiffe::{SandboxJwtSvid, SandboxWorkloadReference}; use prost::Message; use rustls::{ RootCertStore, @@ -36,6 +36,11 @@ struct WorkloadReference { reference: Option, } #[derive(Clone, PartialEq, Message)] +struct WorkloadPidReference { + #[prost(int32, tag = "1")] + pid: i32, +} +#[derive(Clone, PartialEq, Message)] struct ObjectType { #[prost(string, tag = "1")] plural: String, @@ -155,7 +160,35 @@ fn request(message: T) -> Request { /// The reference is derived only from the driver's immutable identity retained /// by the gateway, not mutable workload labels or caller-provided selectors. -fn reference(runtime: &str) -> Result { +fn reference( + workload: SandboxWorkloadReference<'_>, + endpoint: &str, +) -> Result { + let reference = match workload { + SandboxWorkloadReference::Kubernetes(runtime) => kubernetes_reference(runtime)?, + SandboxWorkloadReference::LocalProcess(pid) => { + // A numeric PID identifies a workload only on the agent's own node. + if !endpoint + .strip_prefix("unix:") + .is_some_and(|path| std::path::Path::new(path).is_absolute()) + { + return Err(configuration_failure()); + } + AnyReference { + type_url: "type.googleapis.com/spiffe.broker.WorkloadPIDReference".into(), + value: WorkloadPidReference { + pid: i32::try_from(pid.get()).map_err(|_| configuration_failure())?, + } + .encode_to_vec(), + } + } + }; + Ok(WorkloadReference { + reference: Some(reference), + }) +} + +fn kubernetes_reference(runtime: &str) -> Result { let parts: Vec<_> = runtime .strip_prefix("kubernetes://") .ok_or_else(configuration_failure)? @@ -167,21 +200,19 @@ fn reference(runtime: &str) -> Result { if namespace.is_empty() || component.is_empty() || uid.parse::().is_err() { return Err(configuration_failure()); } - Ok(WorkloadReference { - reference: Some(AnyReference { - type_url: "type.googleapis.com/spiffe.broker.KubernetesObjectReference".into(), - value: ObjectReference { - r#type: Some(ObjectType { - plural: "sandboxes".into(), - group: "agents.x-k8s.io".into(), - }), - // Kubernetes UIDs are cluster-unique. SPIRE resolves this UID itself; - // an object recreated with the same name cannot satisfy the reference. - key: None, - uid: (*uid).to_string(), - } - .encode_to_vec(), - }), + Ok(AnyReference { + type_url: "type.googleapis.com/spiffe.broker.KubernetesObjectReference".into(), + value: ObjectReference { + r#type: Some(ObjectType { + plural: "sandboxes".into(), + group: "agents.x-k8s.io".into(), + }), + // Kubernetes UIDs are cluster-unique. SPIRE resolves this UID itself; + // an object recreated with the same name cannot satisfy the reference. + key: None, + uid: (*uid).to_string(), + } + .encode_to_vec(), }) } @@ -238,6 +269,25 @@ async fn channel( .map_err(|_| configuration_failure())?; tls.alpn_protocols = vec![b"h2".to_vec()]; let connector = tokio_rustls::TlsConnector::from(Arc::new(tls)); + #[cfg(target_os = "linux")] + if let Some(path) = endpoint.strip_prefix("unix:") { + let path = std::path::PathBuf::from(path); + let workload_api_socket = std::path::PathBuf::from(&config.workload_api_socket_path); + return Endpoint::from_static("http://broker.invalid") + .connect_with_connector(tower::service_fn(move |_| { + let connector = connector.clone(); + let path = path.clone(); + let workload_api_socket = workload_api_socket.clone(); + async move { + let socket = tokio::net::UnixStream::connect(path).await?; + let workload_api = tokio::net::UnixStream::connect(workload_api_socket).await?; + verify_broker_peer(&socket, &workload_api)?; + broker_tls(connector, socket).await + } + })) + .await + .map_err(|error| transport_failure(&error)); + } let uri: http::Uri = endpoint.parse().map_err(|_| configuration_failure())?; let host = uri .host() @@ -253,27 +303,66 @@ async fn channel( let tcp = openshell_core::net::connect_tcp_nodelay_best_effort((host.as_str(), port)) .await?; - let stream = connector - .connect( - ServerName::try_from("broker.invalid").expect("static name"), - tcp, - ) - .await?; - Ok::<_, std::io::Error>(TokioIo::new(stream)) + broker_tls(connector, tcp).await } })) .await .map_err(|error| transport_failure(&error)) } +#[cfg(target_os = "linux")] +fn verify_broker_peer( + broker: &tokio::net::UnixStream, + workload_api: &tokio::net::UnixStream, +) -> std::io::Result<()> { + use std::os::unix::fs::MetadataExt as _; + let denied = || std::io::Error::from(std::io::ErrorKind::PermissionDenied); + // SPIRE Agent creates both listeners. Bind the broker connection to the + // process behind the protected Workload API socket that supplies our trust + // bundles. A broker-only forwarding proxy has different peer credentials. + let pid = broker + .peer_cred()? + .pid() + .filter(|pid| *pid > 0) + .ok_or_else(denied)?; + if workload_api.peer_cred()?.pid() != Some(pid) { + return Err(denied()); + } + // A mounted agent socket in another PID namespace would give a numeric + // workload reference a different meaning. + let agent = std::fs::metadata(format!("/proc/{pid}/ns/pid"))?; + let gateway = std::fs::metadata("/proc/self/ns/pid")?; + if (agent.dev(), agent.ino()) != (gateway.dev(), gateway.ino()) { + return Err(denied()); + } + Ok(()) +} + +// SPIRE uses the same mutually authenticated listener on TCP and Unix sockets. +async fn broker_tls( + connector: tokio_rustls::TlsConnector, + socket: S, +) -> std::io::Result>> +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let stream = connector + .connect( + ServerName::try_from("broker.invalid").expect("static name"), + socket, + ) + .await?; + Ok(TokioIo::new(stream)) +} + pub async fn fetch( config: &SpiffeBrokerConfig, endpoint: &str, - runtime: &str, + workload: SandboxWorkloadReference<'_>, expected: &str, audience: &str, ) -> Result { - let reference = reference(runtime)?; + let reference = reference(workload, endpoint)?; tokio::time::timeout(WORKLOAD_IDENTITY_CALL_TIMEOUT, async { let mut grpc = tonic::client::Grpc::new(channel(config, endpoint).await?); grpc.ready() @@ -375,14 +464,75 @@ mod tests { "kubernetes://ns/not-a-uid/component", "kubernetes://ns/3d185166-01ad-4696-8d7c-ac315d4c01e3/", ] { - assert!(reference(runtime).is_err()); + assert!(kubernetes_reference(runtime).is_err()); } - let reference = reference("kubernetes://ns/3d185166-01ad-4696-8d7c-ac315d4c01e3/component") - .unwrap() - .reference - .unwrap(); + let reference = + kubernetes_reference("kubernetes://ns/3d185166-01ad-4696-8d7c-ac315d4c01e3/component") + .unwrap(); let object = ObjectReference::decode(reference.value.as_slice()).unwrap(); assert_eq!(object.uid, "3d185166-01ad-4696-8d7c-ac315d4c01e3"); assert!(object.key.is_none()); } + #[test] + fn process_references_use_the_broker_pid_field_only_over_a_local_socket() { + let workload = + SandboxWorkloadReference::LocalProcess(std::num::NonZeroU32::new(412).unwrap()); + assert!(reference(workload, "https://127.0.0.1").is_err()); + assert!(reference(workload, "unix:relative").is_err()); + let encoded = reference(workload, "unix:/run/spire/broker.sock") + .unwrap() + .reference + .unwrap(); + assert_eq!( + encoded.type_url, + "type.googleapis.com/spiffe.broker.WorkloadPIDReference" + ); + assert_eq!( + WorkloadPidReference::decode(encoded.value.as_slice()) + .unwrap() + .pid, + 412 + ); + } + + #[cfg(target_os = "linux")] + #[tokio::test] + async fn local_broker_and_workload_api_must_have_the_same_peer() { + use std::os::linux::net::SocketAddrExt as _; + use std::os::unix::net::{SocketAddr, UnixListener, UnixStream}; + use std::process::Stdio; + + const RELAY_ADDRESS: &str = "OPENSHELL_TEST_BROKER_RELAY_ADDRESS"; + if let Ok(name) = std::env::var(RELAY_ADDRESS) { + let address = SocketAddr::from_abstract_name(name).unwrap(); + let mut socket = UnixStream::connect_addr(&address).unwrap(); + // Keep the relay alive until the parent has read its peer credentials. + assert_eq!(std::io::Read::read(&mut socket, &mut [0]).unwrap(), 0); + return; + } + + let (broker, workload_api) = tokio::net::UnixStream::pair().unwrap(); + verify_broker_peer(&broker, &workload_api).unwrap(); + let name = format!("openshell-broker-test-{}", std::process::id()); + let address = SocketAddr::from_abstract_name(&name).unwrap(); + let listener = UnixListener::bind_addr(&address).unwrap(); + listener.set_nonblocking(true).unwrap(); + let listener = tokio::net::UnixListener::from_std(listener).unwrap(); + let mut relay = tokio::process::Command::new(std::env::current_exe().unwrap()) + .arg("local_broker_and_workload_api_must_have_the_same_peer") + .env(RELAY_ADDRESS, name) + .stdout(Stdio::null()) + .kill_on_drop(true) + .spawn() + .unwrap(); + let (socket, _) = listener.accept().await.unwrap(); + assert_eq!( + verify_broker_peer(&socket, &workload_api) + .unwrap_err() + .kind(), + std::io::ErrorKind::PermissionDenied + ); + drop(socket); + assert!(relay.wait().await.unwrap().success()); + } } diff --git a/crates/openshell-spire/src/lib.rs b/crates/openshell-spire/src/lib.rs index c19f8d430e..aa5a05af50 100644 --- a/crates/openshell-spire/src/lib.rs +++ b/crates/openshell-spire/src/lib.rs @@ -9,7 +9,9 @@ use openshell_core::config::SpiffeBrokerConfig; use openshell_core::token_grant_failure::{ TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, }; -use openshell_spiffe::{SandboxIdentityProvider, SandboxJwtSvid, SandboxSpiffeIdPrefix}; +use openshell_spiffe::{ + SandboxIdentityProvider, SandboxJwtSvid, SandboxSpiffeIdPrefix, SandboxWorkloadReference, +}; /// SPIRE Broker API adapter. Each acquisition gets current Workload API /// credentials and verifies an exact sandbox identity and audience. @@ -44,20 +46,13 @@ impl SandboxIdentityProvider for SpireSandboxIdentity { gateway_id: &str, sandbox_id: &str, audience: &str, - runtime_identity: &str, + workload: SandboxWorkloadReference<'_>, ) -> Result { let expected = self .prefix .sandbox_spiffe_id(gateway_id, sandbox_id) .map_err(|_| configuration_failure())?; - broker::fetch( - &self.config, - &self.endpoint, - runtime_identity, - &expected, - audience, - ) - .await + broker::fetch(&self.config, &self.endpoint, workload, &expected, audience).await } }