diff --git a/crates/openshell-credential-issuer/src/embedded/test_support.rs b/crates/openshell-credential-issuer/src/embedded/test_support.rs index 1cbf8e5b91..1ff8cb7f2e 100644 --- a/crates/openshell-credential-issuer/src/embedded/test_support.rs +++ b/crates/openshell-credential-issuer/src/embedded/test_support.rs @@ -146,7 +146,11 @@ impl CredentialDriver for TestStaticCredentialDriver { responses.push(ResolvedCredential { request_id: request.request_id, value, - expiration_time: None, + expiration_time: handle.metadata.get("test_expiration_ms").map(|expiry| { + let expiry = expiry.parse().expect("test expiry in milliseconds"); + openshell_core::time::timestamp_from_millis(expiry) + .expect("test expiry timestamp") + }), }); } diff --git a/crates/openshell-server/src/auth/sandbox_session.rs b/crates/openshell-server/src/auth/sandbox_session.rs index 82f103f071..b978373ce4 100644 --- a/crates/openshell-server/src/auth/sandbox_session.rs +++ b/crates/openshell-server/src/auth/sandbox_session.rs @@ -321,11 +321,23 @@ pub async fn authorize_persisted( store: &Store, principal: &AuthenticatedSandboxSession, ) -> Result { - let (_, identity) = load_identity(store, principal).await?; + authorize_persisted_sandbox(store, principal) + .await + .map(|(_, identity)| identity) +} + +/// [`authorize_persisted`], also returning the sandbox record the identity +/// was read from. +#[allow(clippy::result_large_err)] +pub async fn authorize_persisted_sandbox( + store: &Store, + principal: &AuthenticatedSandboxSession, +) -> Result<(Sandbox, PersistedSandboxIdentity), AuthRejection> { + let (sandbox, identity) = load_identity(store, principal).await?; if principal.token_id != identity.gateway_token_id { return Err(stale_identity()); } - Ok(identity) + Ok((sandbox, identity)) } #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index adc2a7617d..bb303e20c9 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -2800,7 +2800,7 @@ use crate::auth::workspace_authz::{ }; use openshell_core::oauth::{ self, TokenExchangeParams, TokenGrantClient, effective_client_assertion_type, - effective_token_type, + effective_jwt_svid_audience, effective_token_type, }; use openshell_core::token_grant_failure::{ TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, WORKLOAD_IDENTITY_CALL_TIMEOUT, @@ -4828,6 +4828,11 @@ async fn exchange_provider_subject_token_inner( ) .to_status_with_code(code)); } + if state.compute.provider_workload_identity().is_some() { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } drop(request); if req.provider.trim().is_empty() @@ -4919,7 +4924,7 @@ async fn exchange_provider_subject_token_inner( &provider, &subject_token.credential, )?; - let stored_subject_token = + let (stored_subject_token, _) = resolve_subject_token_credential(&state.credentials, &provider, &subject_token.credential) .await?; @@ -5012,29 +5017,30 @@ async fn resolve_subject_token_credential( credentials: &crate::credentials::CredentialRuntime, provider: &Provider, credential_key: &str, -) -> Result { +) -> Result<(String, Option), Status> { // Check the provider's expiry before asking a credential driver to resolve // a handle; stale stored material cannot authorize another grant attempt. - ensure_subject_token_credential_not_expired(provider, credential_key)?; + let provider_expires_at_ms = + ensure_subject_token_credential_not_expired(provider, credential_key)?; if let Some(value) = provider .credentials .get(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + return Ok((value.clone(), provider_expires_at_ms)); } if provider.credential_handles.contains_key(credential_key) { - let resolved = credentials + let mut resolved = credentials .resolve_provider_handles(provider, crate::persistence::current_time_ms()) .await .map_err(token_grant_dependency_status)?; if let Some(value) = resolved .values - .get(credential_key) + .remove(credential_key) .filter(|value| !value.is_empty()) { - return Ok(value.clone()); + return Ok((value, resolved.expires_at_ms.get(credential_key).copied())); } } @@ -5044,12 +5050,12 @@ async fn resolve_subject_token_credential( fn ensure_subject_token_credential_not_expired( provider: &Provider, credential_key: &str, -) -> Result<(), Status> { +) -> Result, Status> { let expires_at_ms = provider_credential_expiration_ms(provider, credential_key)?; if expires_at_ms.is_some_and(|value| value <= crate::persistence::current_time_ms()) { return Err(token_grant_authorization_required_status()); } - Ok(()) + Ok(expires_at_ms) } /// The user's stored subject credential is absent or expired. Only the user @@ -5289,24 +5295,6 @@ async fn perform_intermediate_token_exchange( }) } -fn effective_jwt_svid_audience(token_endpoint: &str, jwt_svid_audience: &str) -> String { - if !jwt_svid_audience.trim().is_empty() { - return jwt_svid_audience.to_string(); - } - derive_issuer_from_token_endpoint(token_endpoint) -} - -fn derive_issuer_from_token_endpoint(token_endpoint: &str) -> String { - if let Some(realms_idx) = token_endpoint.find("/realms/") { - let after_realms = &token_endpoint[realms_idx + "/realms/".len()..]; - if let Some(slash_idx) = after_realms.find('/') { - let realm_end = realms_idx + "/realms/".len() + slash_idx; - return token_endpoint[..realm_end].to_string(); - } - } - token_endpoint.to_string() -} - pub(super) async fn handle_get_provider_refresh_status( state: &Arc, request: Request, @@ -6433,8 +6421,11 @@ pub(super) mod tests { let error = ensure_subject_token_credential_not_expired(&provider, "SUBJECT_TOKEN") .expect_err("the Unix epoch is a present, expired timestamp"); assert_eq!(error.code(), Code::FailedPrecondition); - ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") - .expect("an absent expiration remains non-expiring"); + assert_eq!( + ensure_subject_token_credential_not_expired(&provider, "UNSET_TOKEN") + .expect("an absent expiration remains non-expiring"), + None + ); } mod token_grant_failures { @@ -12191,13 +12182,21 @@ pub(super) mod tests { .await .unwrap(); provider.credential_handles = handles; + let expires_at_ms = crate::persistence::current_time_ms() + 60_000; + provider + .credential_handles + .get_mut("subject_token") + .unwrap() + .metadata + .insert("test_expiration_ms".into(), expires_at_ms.to_string()); - let subject_token = + let (subject_token, subject_expires_at_ms) = resolve_subject_token_credential(&credentials, &provider, "subject_token") .await .unwrap(); assert_eq!(subject_token, "user-token"); + assert_eq!(subject_expires_at_ms, Some(expires_at_ms)); } #[tokio::test] diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index e703e49089..574770427d 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -4,14 +4,14 @@ //! Gateway-owned sandbox identity and provider-token acquisition. //! The caller selects an attached configured credential, never grant parameters. use super::{ - Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectWorkspace, Principal, - Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, Status, - TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, + Arc, HashMap, IntermediateTokenCache, LazyLock, Message, ObjectId, ObjectName, ObjectWorkspace, + Principal, Provider, ProviderCredentialTokenGrantType, Request, Response, Sandbox, ServerState, + Status, TokenExchangeParams, TokenGrantFailure, TokenGrantFailureKind, TokenGrantStage, canonical_request_id, effective_jwt_svid_audience, fetch_gateway_jwt_svid_from, get_provider_type_profile_for_scope, insert_dynamic_credentials_for_profile, jwt_exp_ms, log_token_grant_failure, oauth, perform_intermediate_token_exchange, - provider_credential_expiration_ms, resolve_subject_token_credential, - sanitize_token_grant_status, token_exchange_http_client, token_grant_configuration_status, + resolve_subject_token_credential, sanitize_token_grant_status, token_exchange_http_client, + token_grant_authorization_required_status, token_grant_configuration_status, token_grant_dependency_status, token_grant_identity_rejected, token_grant_store_status, }; use openshell_core::jwt::AuthenticatedSandboxSession; @@ -19,13 +19,22 @@ use openshell_core::proto::{ GetSandboxProviderAccessTokenRequest, GetSandboxProviderAccessTokenResponse, ProviderCredentialTokenGrant, }; -use openshell_core::token_grant_failure::BROKERED_TOKEN_GATEWAY_DEADLINE; -use openshell_spiffe::SandboxIdentityProvider; +use openshell_core::token_grant_failure::{ + BROKERED_TOKEN_GATEWAY_DEADLINE, WORKLOAD_IDENTITY_CALL_TIMEOUT, +}; +use openshell_spiffe::{SandboxIdentityProvider, SandboxJwtSvid}; use std::time::Duration; static ACCESS_TOKENS: LazyLock = LazyLock::new(IntermediateTokenCache::new); static ACQUISITIONS: LazyLock = LazyLock::new(Acquisitions::default); -static ADMISSION: LazyLock = LazyLock::new(Admission::default); +static REQUEST_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static EXCHANGE_ADMISSION: LazyLock = LazyLock::new(Admission::default); +static MISS_ADMISSION: LazyLock = LazyLock::new(Admission::default); +const PER_SANDBOX_EXCHANGE_LIMIT: usize = 4; +const PER_SANDBOX_VERIFIED_REQUEST_LIMIT: usize = 16; +// Reserve request capacity for warm grants while other grants wait on OAuth. +const PER_SANDBOX_MISS_LIMIT: usize = + PER_SANDBOX_VERIFIED_REQUEST_LIMIT - PER_SANDBOX_EXCHANGE_LIMIT; pub(in crate::grpc) async fn handle( state: &Arc, @@ -63,10 +72,11 @@ pub(in crate::grpc) async fn handle( /// Verify the original bearer again after asynchronous work, including expiry /// and the persisted generation, epoch, active phase, and current token lineage. +/// A new launch has a new generation, so a bearer of an earlier launch fails. async fn authorize( state: &ServerState, bearer: &str, -) -> Result { +) -> Result<(AuthenticatedSandboxSession, Sandbox), Status> { let authority = state .sandbox_session_jwt_authority .as_ref() @@ -77,10 +87,11 @@ async fn authorize( if session.expires_at.saturating_mul(1000) <= crate::persistence::current_time_ms() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - crate::auth::sandbox_session::authorize_persisted(&state.store, &session) - .await - .map_err(|error| error.status)?; - Ok(session) + let (sandbox, _) = + crate::auth::sandbox_session::authorize_persisted_sandbox(&state.store, &session) + .await + .map_err(|error| error.status)?; + Ok((session, sandbox)) } /// One configured credential of an attached provider. @@ -89,6 +100,17 @@ struct ConfiguredGrant { grant: ProviderCredentialTokenGrant, /// The gateway's exact key for the credential, including its endpoint owner. key: String, + attachment_epoch: String, +} + +#[allow(clippy::result_large_err)] +fn provider_attachment<'a>(sandbox: &'a Sandbox, provider_name: &str) -> Result<&'a str, Status> { + sandbox + .spec + .as_ref() + .filter(|spec| spec.providers.iter().any(|name| name == provider_name)) + .map(|spec| spec.provider_attachment_epoch.as_str()) + .ok_or_else(|| token_grant_configuration_status(tonic::Code::PermissionDenied)) } /// Resolve the exact configured credential from the gateway's approved profile. @@ -98,7 +120,7 @@ struct ConfiguredGrant { /// generation a supervisor adds; a different or missing owner matches nothing. async fn grant_configuration( state: &ServerState, - sandbox_id: &str, + sandbox: &Sandbox, key: &str, ) -> Result { let invalid = || token_grant_configuration_status(tonic::Code::PermissionDenied); @@ -107,16 +129,7 @@ async fn grant_configuration( let identity = openshell_core::dynamic_credential_key::credential_identity(&key).ok_or_else(invalid)?; let (provider_name, _) = identity.split_once(':').ok_or_else(invalid)?; - let sandbox = state - .store - .get_message::(sandbox_id) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(invalid)?; - let spec = sandbox.spec.as_ref().ok_or_else(invalid)?; - if !spec.providers.iter().any(|name| name == provider_name) { - return Err(invalid()); - } + let attachment_epoch = provider_attachment(sandbox, provider_name)?.to_owned(); let provider = state .store .get_message_by_name::(sandbox.object_workspace(), provider_name) @@ -148,14 +161,15 @@ async fn grant_configuration( provider, grant, key, + attachment_epoch, }) } /// Bind a cached token to its runtime, configured credential, and subject. /// -/// Include the provider revision and resolved subject token, so an in-place -/// rotation of a handle-backed subject never serves a token minted from the -/// previous one. The digest is an in-memory map key and is never exposed. +/// Include the provider revision and resolved subject token. A request +/// that resolves a rotated subject gets a different key. The digest is an +/// in-memory map key and is never exposed. fn cache_key( session: &AuthenticatedSandboxSession, configured: &ConfiguredGrant, @@ -167,12 +181,13 @@ fn cache_key( .metadata .as_ref() .map_or(0, |metadata| metadata.resource_version); - let fields: [&[u8]; 11] = [ + let fields: [&[u8]; 12] = [ b"openshell-provider-access-token-v1", gateway_id.as_bytes(), session.sandbox_id.as_str().as_bytes(), session.runtime_generation.as_str().as_bytes(), &session.auth_epoch.get().to_be_bytes(), + configured.attachment_epoch.as_bytes(), configured.provider.object_id().as_bytes(), &resource_version.to_be_bytes(), configured.key.as_bytes(), @@ -202,6 +217,200 @@ struct Subject { expires_at_ms: Option, } +async fn resolve_subject( + state: &ServerState, + configured: &ConfiguredGrant, +) -> Result, Status> { + let configuration_failure = + || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let grant_type = ProviderCredentialTokenGrantType::try_from(configured.grant.grant_type) + .map_err(|_| configuration_failure())?; + if grant_type != ProviderCredentialTokenGrantType::TokenExchange { + return Ok(None); + } + let subject = configured + .grant + .subject_token + .as_ref() + .filter(|subject| subject.source == "provider_credential") + .ok_or_else(configuration_failure)?; + let (value, expires_at_ms) = resolve_subject_token_credential( + &state.credentials, + &configured.provider, + &subject.credential, + ) + .await?; + Ok(Some(Subject { + expires_at_ms, + value, + token_type: subject.subject_token_type.clone(), + })) +} + +/// Recheck the authorized grant and session after waits and before exposing +/// credentials to the issuer or returning an access token to the sandbox. +struct GrantAuthorization<'a> { + state: &'a ServerState, + bearer: &'a str, + session: &'a AuthenticatedSandboxSession, + /// The request's first snapshot. It only locates the provider; `revalidate` reads a fresh one. + sandbox: &'a Sandbox, + key: &'a str, + gateway_id: &'a str, + fingerprint: &'a str, + subject: Option<&'a Subject>, + revalidate_subject: bool, +} + +impl GrantAuthorization<'_> { + async fn revalidate(&self) -> Result, Status> { + let current = grant_configuration(self.state, self.sandbox, self.key).await?; + let resolved; + let subject = if self.revalidate_subject { + // A driver can replace a subject without changing the Provider row. + resolved = resolve_subject(self.state, ¤t).await?; + resolved.as_ref() + } else { + self.subject + }; + let subject_value = subject.map(|subject| subject.value.as_str()); + if cache_key(self.session, ¤t, subject_value, self.gateway_id)? != self.fingerprint { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + // Profile and subject lookup may await storage. Check the attachment + // and session on the same fresh snapshot afterward. + let (_, sandbox) = authorize(self.state, self.bearer).await?; + if provider_attachment(&sandbox, current.provider.object_name())? + != current.attachment_epoch + { + return Err(token_grant_configuration_status( + tonic::Code::FailedPrecondition, + )); + } + let subject_expiry = [self.subject, subject] + .into_iter() + .flatten() + .filter_map(|subject| subject.expires_at_ms) + .min(); + if subject_expiry.is_some_and(|expiry| expiry <= crate::persistence::current_time_ms()) { + return Err(token_grant_authorization_required_status()); + } + Ok(subject_expiry) + } +} + +#[derive(Clone, Copy)] +enum GrantIdentity<'a> { + Broker(&'a dyn SandboxIdentityProvider), + Supervisor(&'a SandboxJwtSvid), +} + +impl GrantIdentity<'_> { + #[allow(clippy::result_large_err)] + fn cache_ttl_override( + self, + grant: &ProviderCredentialTokenGrant, + ) -> Result, Status> { + let ttl = grant + .cache_ttl + .as_ref() + .map(openshell_core::time::duration_to_std) + .transpose() + .map_err(|_| token_grant_configuration_status(tonic::Code::InvalidArgument))?; + if ttl.is_some_and(|ttl| !ttl.is_zero() && ttl < Duration::from_secs(1)) { + return match self { + Self::Broker(_) => Err(token_grant_configuration_status( + tonic::Code::InvalidArgument, + )), + // Direct grants accepted fractional overrides. Keep those + // grants usable by exchanging without caching. + Self::Supervisor(_) => Ok(Some(Duration::ZERO)), + }; + } + Ok(ttl) + } +} + +async fn validate_workload_assertion( + identity: &crate::spiffe_broker::SupervisorWorkloadIdentity, + session: &AuthenticatedSandboxSession, + grant: &ProviderCredentialTokenGrant, + token: &str, + launch_token: &str, +) -> Result { + let expected_id = identity + .sandbox_spiffe_id(session.sandbox_id.as_str()) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + // `authorize` matched this generation against the persisted identity, so + // it names the current launch. + let expected_launch_id = identity + .launch_spiffe_id(session.sandbox_id.as_str(), &session.runtime_generation) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + let audience = effective_jwt_svid_audience(&grant.token_endpoint, &grant.jwt_svid_audience); + let launch_audience = session.runtime_generation.provider_spiffe_audience(); + let bundles = tokio::time::timeout(WORKLOAD_IDENTITY_CALL_TIMEOUT, identity.jwt_bundles()) + .await + .map_err(|_| { + TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::WorkloadIdentity, + ) + .to_status() + })? + .map_err(|error| { + super::token_grant_workload_api_status(error, tonic::Code::FailedPrecondition) + })?; + verify_workload_assertion( + token, + launch_token, + &bundles, + expected_id, + &expected_launch_id, + &audience, + &launch_audience, + ) +} + +fn verify_workload_assertion( + token: &str, + launch_token: &str, + bundles: &spiffe::JwtBundleSet, + expected_id: String, + expected_launch_id: &str, + audience: &str, + launch_audience: &str, +) -> Result { + let rejection = || token_grant_identity_rejected(tonic::Code::PermissionDenied); + openshell_crypto::install_jwt_provider(); + if expected_id == expected_launch_id || audience == launch_audience { + return Err(rejection()); + } + let verify = |token: &str, expected_id: &str, audience: &str| { + let svid = spiffe::JwtSvid::parse_and_validate(token, bundles, &[audience]) + .map_err(|_| rejection())?; + let expires_at = svid.expiry().unix_timestamp(); + if svid.spiffe_id().to_string() != expected_id + || svid.audience().len() != 1 + || expires_at.saturating_mul(1000) <= crate::persistence::current_time_ms() + { + return Err(rejection()); + } + Ok(expires_at) + }; + let expires_at = verify(token, &expected_id, audience)?.min(verify( + launch_token, + expected_launch_id, + launch_audience, + )?); + Ok(SandboxJwtSvid { + spiffe_id: expected_id, + token: token.to_string(), + expires_at, + }) +} + #[allow(clippy::too_many_lines)] async fn obtain( state: &Arc, @@ -221,93 +430,93 @@ async fn obtain( if values.next().is_some() { return Err(token_grant_identity_rejected(tonic::Code::Unauthenticated)); } - let session = authorize(state, &bearer).await?; + let (session, sandbox) = authorize(state, &bearer).await?; if principal.sandbox_id != session.sandbox_id.as_str() { return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); } - // Bound outstanding work after authentication, independently of caching. - // A busy sandbox cannot occupy the gateway's entire acquisition budget. - let _admission = ADMISSION.enter(session.sandbox_id.as_str())?; - // Startup enables an identity provider only with gateway session JWTs. - let (Some(identity), Some(gateway_jwt)) = ( - state.sandbox_identity.as_deref(), - state.config.gateway_jwt.as_ref(), - ) else { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - }; - if state.compute.configured_driver_name() != "kubernetes" { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); + let unavailable = || token_grant_configuration_status(tonic::Code::FailedPrecondition); + let gateway_jwt = state.config.gateway_jwt.as_ref().ok_or_else(unavailable)?; + let supplied = request.get_ref().jwt_svid.as_deref(); + let launch_proof = request.get_ref().launch_jwt_svid.as_deref(); + let supervisor_identity = state.compute.provider_workload_identity(); + let broker = state.sandbox_identity.as_deref(); + if supervisor_identity.is_none() + && (broker.is_none() || state.compute.configured_driver_name() != "kubernetes") + { + return Err(unavailable()); } + let assertions = match (supervisor_identity, supplied, launch_proof) { + (Some(identity), Some(provider), Some(launch)) => Some((identity, provider, launch)), + (None, None, None) => None, + (Some(_), None, None) | (None, Some(_), Some(_)) => return Err(unavailable()), + _ => return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)), + }; + // Keep grant requests bounded. Verified requests have a separate, lower + // limit on OAuth exchanges so cache hits do not consume exchange slots. + let dedicated = supervisor_identity.is_some(); + let request_limit = if dedicated { + PER_SANDBOX_VERIFIED_REQUEST_LIMIT + } else { + PER_SANDBOX_EXCHANGE_LIMIT + }; + let _request_admission = REQUEST_ADMISSION.enter(session.sandbox_id.as_str(), request_limit)?; let gateway_id = gateway_jwt.gateway_id.as_str(); let key = &request.get_ref().credential_key; - let configured = grant_configuration(state, session.sandbox_id.as_str(), key).await?; + let configured = grant_configuration(state, &sandbox, key).await?; let grant = &configured.grant; - let ttl_override = grant - .cache_ttl - .as_ref() - .map(openshell_core::time::duration_to_std) - .transpose() - .map_err(|_| token_grant_configuration_status(tonic::Code::InvalidArgument))?; - // Millisecond truncation and final authorization reads would consume tiny - // cache lifetimes before they could be returned. Zero remains no-cache. - if ttl_override.is_some_and(|ttl| !ttl.is_zero() && ttl < Duration::from_secs(1)) { - return Err(token_grant_configuration_status( - tonic::Code::InvalidArgument, - )); - } - let grant_type = ProviderCredentialTokenGrantType::try_from(grant.grant_type) - .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - // Resolve the subject before any cache lookup, so its revocation or - // expiry also denies cached tokens. - let subject = if grant_type == ProviderCredentialTokenGrantType::TokenExchange { - let subject = grant - .subject_token - .as_ref() - .filter(|subject| subject.source == "provider_credential") - .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; - Some(Subject { - expires_at_ms: provider_credential_expiration_ms( - &configured.provider, - &subject.credential, - )?, - value: resolve_subject_token_credential( - &state.credentials, - &configured.provider, - &subject.credential, - ) - .await?, - token_type: subject.subject_token_type.clone(), - }) - } else { - None + // Every dedicated request presents a verified assertion, including cache hits. + let assertion; + let identity = match assertions { + Some((identity, token, launch_proof)) => { + assertion = + validate_workload_assertion(identity, &session, grant, token, launch_proof).await?; + GrantIdentity::Supervisor(&assertion) + } + None => GrantIdentity::Broker(broker.ok_or_else(unavailable)?), }; + let ttl_override = identity.cache_ttl_override(grant)?; + // Resolve the subject before any cache lookup so its value binds the token. + let subject = resolve_subject(state, &configured).await?; let subject_value = subject.as_ref().map(|subject| subject.value.as_str()); let fingerprint = cache_key(&session, &configured, subject_value, gateway_id)?; + let authorization = GrantAuthorization { + state, + bearer: &bearer, + session: &session, + sandbox: &sandbox, + key, + gateway_id, + fingerprint: &fingerprint, + subject: subject.as_ref(), + revalidate_subject: dedicated && subject.is_some(), + }; // A zero override disables caching, and with it shared acquisition. let caching = ttl_override != Some(Duration::ZERO); - let mut refresh = false; + let mut retried_expired_hit = false; loop { let cached = || { - (caching && !refresh) + caching .then(|| ACCESS_TOKENS.get_until(&fingerprint)) .flatten() - .filter(|(_, until)| { - *until > crate::persistence::current_time_ms().saturating_add(1000) - }) }; // A miss holds its fingerprint's turn until its token is cached, so // concurrent misses wait and then find it. A miss is cached only after // the final validation below, which a hit passes as well. let mut turn = None; + let miss_admission; let (response, serve_until_ms, acquired) = if let Some((token, until)) = cached() { + miss_admission = None; (token, until, false) } else { + miss_admission = dedicated + .then(|| MISS_ADMISSION.enter(session.sandbox_id.as_str(), PER_SANDBOX_MISS_LIMIT)) + .transpose()?; let waited = if caching { - Some(ACQUISITIONS.turn(&fingerprint).await?) + let waited = ACQUISITIONS.turn(&fingerprint).await; + if let GrantIdentity::Supervisor(svid) = identity { + require_live_assertion(svid, crate::persistence::current_time_ms())?; + } + Some(waited?) } else { None }; @@ -315,42 +524,39 @@ async fn obtain( (token, until, false) } else { turn = waited; - let (token, until) = acquire( - state, - &bearer, - &session, - identity, - gateway_id, - grant, - subject.as_ref(), - ttl_override, - request_id, - ) - .await - .inspect_err(|status| { - if let Some(turn) = turn.as_mut() { - *turn.failure = Some(status.clone()); - } - })?; + let _exchange_admission = dedicated + .then(|| { + EXCHANGE_ADMISSION + .enter(session.sandbox_id.as_str(), PER_SANDBOX_EXCHANGE_LIMIT) + }) + .transpose()?; + let (token, until) = + acquire(&authorization, identity, grant, ttl_override, request_id) + .await + .inspect_err(|status| { + if let Some(turn) = turn.as_mut() { + turn.record_failure(status); + } + })?; (token, until, true) } }; - // Re-read attachment, provider revision, and profile, then the session, - // before serving or caching any token. - let current = grant_configuration(state, session.sandbox_id.as_str(), key).await?; - if cache_key(&session, ¤t, subject_value, gateway_id)? != fingerprint { - return Err(token_grant_configuration_status( - tonic::Code::FailedPrecondition, - )); - } - authorize(state, &bearer).await?; + let subject_expiry = authorization.revalidate().await?; // The lifetime runs from when the token service answered, so time spent // in the final validation counts against it. - let remaining_ms = serve_until_ms.saturating_sub(crate::persistence::current_time_ms()); - if remaining_ms <= 0 && !acquired { - // A hit can expire during the final asynchronous checks. Refresh once; - // a fresh acquisition still must pass every check before it is served. - refresh = true; + let now_ms = crate::persistence::current_time_ms(); + let serve_until_ms = serve_until_ms.min(subject_expiry.unwrap_or(i64::MAX)); + let request_expires_at_ms = match identity { + GrantIdentity::Broker(_) => serve_until_ms, + GrantIdentity::Supervisor(svid) => { + require_live_assertion(svid, now_ms)?; + serve_until_ms.min(svid.expires_at.saturating_mul(1000)) + } + }; + let remaining_ms = request_expires_at_ms.saturating_sub(now_ms); + if remaining_ms <= 0 && !acquired && !retried_expired_hit { + // Another request may already have refreshed the expired entry. + retried_expired_hit = true; continue; } if remaining_ms <= 0 { @@ -364,70 +570,90 @@ async fn obtain( ACCESS_TOKENS.set(fingerprint, &response, serve_until_ms); } drop(turn); - return Ok(Response::new(GetSandboxProviderAccessTokenResponse { + let response = Response::new(GetSandboxProviderAccessTokenResponse { access_token: response.access_token, token_type: response.token_type, expires_after: openshell_core::time::duration_from_std(Duration::from_millis( u64::try_from(remaining_ms).unwrap_or_default(), )) .ok(), - })); + }); + drop(miss_admission); + return Ok(response); + } +} + +#[allow(clippy::result_large_err)] +fn require_live_assertion(svid: &SandboxJwtSvid, now_ms: i64) -> Result<(), Status> { + if svid.expires_at.saturating_mul(1000) <= now_ms { + return Err(token_grant_identity_rejected(tonic::Code::PermissionDenied)); } + Ok(()) } -/// Acquire a final token, re-authorizing the session between network calls. +/// Acquire a final token, rechecking the grant before each OAuth exchange. /// Returns the token and when to stop serving it. -#[allow(clippy::too_many_arguments)] async fn acquire( - state: &ServerState, - bearer: &str, - session: &AuthenticatedSandboxSession, - identity: &dyn SandboxIdentityProvider, - gateway_id: &str, + authorization: &GrantAuthorization<'_>, + identity: GrantIdentity<'_>, grant: &ProviderCredentialTokenGrant, - subject: Option<&Subject>, ttl_override: Option, request_id: Option<&str>, ) -> Result<(oauth::OAuthTokenResponse, i64), Status> { - authorize(state, bearer).await?; + let GrantAuthorization { + state, + bearer, + session, + gateway_id, + subject, + .. + } = *authorization; let audience = effective_jwt_svid_audience(&grant.token_endpoint, &grant.jwt_svid_audience); - let sandbox = state - .store - .get_message::(session.sandbox_id.as_str()) - .await - .map_err(|_| token_grant_store_status())? - .ok_or_else(|| token_grant_identity_rejected(tonic::Code::Unauthenticated))?; - let runtime_identity = sandbox - .metadata - .as_ref() - .and_then(|metadata| { - metadata - .annotations - .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) - }) - .map_or("", String::as_str); - let svid = identity - .fetch_jwt_svid( - gateway_id, - session.sandbox_id.as_str(), - &audience, - runtime_identity, - ) - .await - .map_err(TokenGrantFailure::to_status)?; - authorize(state, bearer).await?; + let issued; + let svid = match identity { + GrantIdentity::Broker(provider) => { + let (_, sandbox) = authorize(state, bearer).await?; + let runtime_identity = sandbox + .metadata + .as_ref() + .and_then(|metadata| { + metadata + .annotations + .get(crate::compute::COMPUTE_RUNTIME_IDENTITY_ANNOTATION) + }) + .map_or("", String::as_str); + issued = provider + .fetch_jwt_svid( + gateway_id, + session.sandbox_id.as_str(), + &audience, + runtime_identity, + ) + .await + .map_err(TokenGrantFailure::to_status)?; + &issued + } + GrantIdentity::Supervisor(svid) => svid, + }; + let check_expiry = || require_live_assertion(svid, crate::persistence::current_time_ms()); let client = token_exchange_http_client()?; - let subject_expiry = subject.and_then(|subject| subject.expires_at_ms); + let mut subject_expiry = i64::MAX; let token = if let Some(subject) = subject { - let component_svid = fetch_gateway_jwt_svid_from( - &audience, - state - .config - .spiffe_broker - .as_ref() - .map(|broker| broker.workload_api_socket_path.as_str()), - ) - .await?; + let component_socket = state + .config + .spiffe_workload_identity + .as_ref() + .and_then(|identity| identity.workload_api_socket_path.to_str()) + .or_else(|| { + state + .config + .spiffe_broker + .as_ref() + .map(|broker| broker.workload_api_socket_path.as_str()) + }); + let component_svid = fetch_gateway_jwt_svid_from(&audience, component_socket).await?; + subject_expiry = authorization.revalidate().await?.unwrap_or(i64::MAX); + check_expiry()?; let intermediate = perform_intermediate_token_exchange( &grant.token_endpoint, &TokenExchangeParams { @@ -442,7 +668,8 @@ async fn acquire( request_id, ) .await?; - authorize(state, bearer).await?; + subject_expiry = subject_expiry.min(authorization.revalidate().await?.unwrap_or(i64::MAX)); + check_expiry()?; oauth::post_oauth_token_exchange( client, &grant.token_endpoint, @@ -460,6 +687,8 @@ async fn acquire( .await .map_err(TokenGrantFailure::to_status)? } else { + authorization.revalidate().await?; + check_expiry()?; oauth::post_oauth_token_grant( client, &grant.token_endpoint, @@ -475,11 +704,12 @@ async fn acquire( .map_err(TokenGrantFailure::to_status)? }; let obtained_at_ms = crate::persistence::current_time_ms(); + require_live_assertion(svid, obtained_at_ms)?; let identity_expires_at_ms = session .expires_at .saturating_mul(1000) .min(svid.expires_at.saturating_mul(1000)) - .min(subject_expiry.unwrap_or(i64::MAX)); + .min(subject_expiry); let serve_until_ms = serve_until_ms(&token, ttl_override, obtained_at_ms, identity_expires_at_ms).ok_or_else( || { @@ -490,7 +720,6 @@ async fn acquire( .to_status() }, )?; - authorize(state, bearer).await?; Ok((token, serve_until_ms)) } @@ -541,13 +770,14 @@ struct Admission { } impl Admission { - fn enter(&self, sandbox: &str) -> Result, Status> { + fn enter(&self, sandbox: &str, per_sandbox_limit: usize) -> Result, Status> { let mut active = self .active .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); - if active.values().sum::() >= 64 - || active.get(sandbox).copied().unwrap_or_default() >= 4 + // Sixteen sandboxes at their own limit fill the gateway, whatever that limit is. + if active.values().sum::() >= per_sandbox_limit * 16 + || active.get(sandbox).copied().unwrap_or_default() >= per_sandbox_limit { return Err(TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, @@ -587,8 +817,9 @@ impl Drop for AdmissionGuard<'_> { /// Coordinate token acquisition separately for each cache fingerprint. /// /// Concurrent misses share a single acquisition without locking unrelated -/// tokens. Current waiters receive the holder's acquisition failure; a new -/// group can retry after they leave. Entries exist only while held or awaited. +/// tokens. Current waiters share dependency outages. A caller's authorization +/// failure leaves the turn available to its waiters. Entries live only while +/// held or awaited. #[derive(Default)] struct Acquisitions { slots: std::sync::Mutex, @@ -647,6 +878,29 @@ struct AcquisitionTurn<'a> { _registration: Registration<'a>, } +impl AcquisitionTurn<'_> { + fn record_failure(&mut self, status: &Status) { + let failure = TokenGrantFailure::from_status(status); + if matches!( + (failure.kind(), failure.upstream_status()), + ( + TokenGrantFailureKind::Unavailable, + None | Some(429 | 500..=599) + ) | (TokenGrantFailureKind::Timeout, _) + ) && matches!( + failure.stage(), + TokenGrantStage::WorkloadIdentity + | TokenGrantStage::IntermediateExchange + | TokenGrantStage::TokenEndpoint + ) { + *self.failure = Some(status.clone()); + } + } +} + +#[cfg(test)] +mod performance_tests; + #[cfg(test)] mod tests { use super::*; @@ -655,22 +909,30 @@ mod tests { #[test] fn admission_is_bounded_per_sandbox_and_releases_cancelled_work() { let admission = Admission::default(); - let guards: Vec<_> = (0..4).map(|_| admission.enter("busy").unwrap()).collect(); - assert_eq!( - admission.enter("busy").err().unwrap().code(), - tonic::Code::ResourceExhausted - ); - let other = admission.enter("other").unwrap(); - drop(guards); - drop(admission.enter("busy").unwrap()); - drop(other); - assert!(admission.active.lock().unwrap().is_empty()); - let guards: Vec<_> = (0..64) - .map(|i| admission.enter(&i.to_string()).unwrap()) - .collect(); - assert!(admission.enter("overflow").is_err()); - drop(guards); - assert!(admission.active.lock().unwrap().is_empty()); + for limit in [ + PER_SANDBOX_EXCHANGE_LIMIT, + PER_SANDBOX_VERIFIED_REQUEST_LIMIT, + ] { + let guards: Vec<_> = (0..limit) + .map(|_| admission.enter("busy", limit).unwrap()) + .collect(); + assert_eq!( + admission.enter("busy", limit).err().unwrap().code(), + tonic::Code::ResourceExhausted + ); + let other = admission.enter("other", limit).unwrap(); + drop(guards); + drop(admission.enter("busy", limit).unwrap()); + drop(other); + assert!(admission.active.lock().unwrap().is_empty()); + // Sixteen sandboxes at this limit fill the gateway; the next is refused. + let guards: Vec<_> = (0..limit * 16) + .map(|i| admission.enter(&(i / limit).to_string(), limit).unwrap()) + .collect(); + assert!(admission.enter("overflow", limit).is_err()); + drop(guards); + assert!(admission.active.lock().unwrap().is_empty()); + } } #[tokio::test] async fn broker_requires_a_signed_session_even_with_a_sandbox_principal() { @@ -700,6 +962,98 @@ mod tests { } } + #[test] + fn workload_assertion_requires_the_exact_sandbox_and_supervisor_launch() { + use openshell_core::sandbox_generation::SandboxGenerationId; + + let (bundles, header, encoding_key) = performance_tests::workload_trust(); + let now = crate::persistence::current_time_ms() / 1000; + let sign_until = |subject: &str, audiences: &[&str], expires_at| { + openshell_crypto::jwt::encode( + &header, + &serde_json::json!({"sub": subject, "aud": audiences, "exp": expires_at}), + &encoding_key, + ) + .unwrap() + }; + let sign = |subject: &str, audiences: &[&str]| sign_until(subject, audiences, now + 120); + let sandboxes = [ + "spiffe://test.example/gateway/gateway/sandbox/a", + "spiffe://test.example/gateway/gateway/sandbox/b", + ]; + let launches = [ + "spiffe://test.example/gateway/gateway/sandbox/a/launch/current", + "spiffe://test.example/gateway/gateway/sandbox/b/launch/current", + ]; + let launch = SandboxGenerationId::parse("g2") + .unwrap() + .provider_spiffe_audience(); + let older = SandboxGenerationId::parse("g1") + .unwrap() + .provider_spiffe_audience(); + let audience = "https://issuer.test/token"; + let verify = |token: &str, launch_token: &str, expected: &str, expected_launch: &str| { + verify_workload_assertion( + token, + launch_token, + &bundles, + expected.to_owned(), + expected_launch, + audience, + &launch, + ) + }; + for (subject, launch_subject) in sandboxes.into_iter().zip(launches) { + let token = sign(subject, &[audience]); + let launch_proof = sign(launch_subject, &[&launch]); + let verified = verify(&token, &launch_proof, subject, launch_subject).unwrap(); + assert_eq!(verified.spiffe_id, subject); + } + let token = sign(sandboxes[0], &[audience]); + let proof = sign(launches[0], &[&launch]); + // The accepted claims, signed by a key the trust bundle does not hold. + let (_, _, untrusted) = performance_tests::workload_trust(); + let forged = openshell_crypto::jwt::encode( + &header, + &serde_json::json!({"sub": sandboxes[0], "aud": [audience], "exp": now + 120}), + &untrusted, + ) + .unwrap(); + let shorter_provider = sign_until(sandboxes[0], &[audience], now + 60); + let shorter_launch = sign_until(launches[0], &[&launch], now + 60); + for (provider, launch_proof) in [(&shorter_provider, &proof), (&token, &shorter_launch)] { + assert_eq!( + verify(provider, launch_proof, sandboxes[0], launches[0]) + .unwrap() + .expires_at, + now + 60 + ); + } + for (token, proof) in [ + (forged, proof.clone()), + (sign(sandboxes[1], &[audience]), proof.clone()), + (token.clone(), sign(launches[1], &[&launch])), + (token.clone(), sign(launches[0], &[&older])), + ( + token.clone(), + sign( + "spiffe://test.example/gateway/gateway/sandbox/a/launch/outgoing", + &[&launch], + ), + ), + (token.clone(), sign(sandboxes[0], &[&launch])), + (token.clone(), token), + (sign(sandboxes[0], &[audience, &launch]), proof), + ] { + assert_eq!( + verify(&token, &proof, sandboxes[0], launches[0]) + .unwrap_err() + .code(), + tonic::Code::PermissionDenied + ); + } + } + #[test] fn fingerprint_binds_the_runtime_configured_key_and_resolved_subject() { use openshell_core::jwt::{CredentialEpoch, SandboxId}; @@ -718,6 +1072,7 @@ mod tests { provider: Provider::default(), grant: ProviderCredentialTokenGrant::default(), key: key.to_string(), + attachment_epoch: String::new(), }; let owned = "api.example.com\t443\t/v1/**\towner\tprovider:access"; let fingerprint = |session, key, subject| { @@ -733,6 +1088,21 @@ mod tests { assert_eq!(fingerprint(&renewed, owned, Some("subject-a")), base); // A rotated subject, another credential, or another epoch does not. assert_ne!(fingerprint(&session, owned, Some("subject-b")), base); + let mut reattached = configured(owned); + reattached.attachment_epoch = "new-attachment".into(); + assert_ne!( + cache_key(&session, &reattached, Some("subject-a"), "gateway").unwrap(), + base + ); + // Another runtime generation is another launch. + let relaunched = AuthenticatedSandboxSession { + runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( + "g2", + ) + .unwrap(), + ..session.clone() + }; + assert_ne!(fingerprint(&relaunched, owned, Some("subject-a")), base); let spoofed = owned.replace("owner", "other"); assert_ne!(fingerprint(&session, &spoofed, Some("subject-a")), base); let rotated = AuthenticatedSandboxSession { @@ -746,6 +1116,27 @@ mod tests { ); } + #[test] + fn verified_grants_accept_fractional_overrides_without_caching() { + const NOW: i64 = 1_700_000_000_000; + let assertion = SandboxJwtSvid { + spiffe_id: "spiffe://test.example/sandbox".into(), + token: "fixture-assertion".into(), + expires_at: NOW / 1000 + 60, + }; + let grant = ProviderCredentialTokenGrant { + cache_ttl: Some(prost_types::Duration { + seconds: 0, + nanos: 500_000_000, + }), + ..Default::default() + }; + let ttl = GrantIdentity::Supervisor(&assertion) + .cache_ttl_override(&grant) + .unwrap(); + assert_eq!(ttl, Some(Duration::ZERO)); + } + #[test] fn served_lifetime_never_exceeds_the_token_or_identity() { const NOW: i64 = 1_700_000_000_000; @@ -851,11 +1242,32 @@ mod tests { }) .await .expect("all requests should join the in-flight acquisition"); + holder.record_failure(&Status::unauthenticated("superseded bearer")); + assert!(holder.failure.is_none()); + let rejected_assertion = TokenGrantFailure::new( + TokenGrantFailureKind::Unclassified, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(401); + holder.record_failure(&rejected_assertion.to_status()); + assert!(holder.failure.is_none()); + // A token service that stalls after its headers is an outage too. + let stalled_body = TokenGrantFailure::new( + TokenGrantFailureKind::Timeout, + TokenGrantStage::TokenEndpoint, + ) + .with_upstream_status(200); + holder.record_failure(&stalled_body.to_status()); + assert_eq!( + holder.failure.as_ref().map(TokenGrantFailure::from_status), + Some(stalled_body) + ); let expected = TokenGrantFailure::new( TokenGrantFailureKind::Unavailable, TokenGrantStage::TokenEndpoint, - ); - *holder.failure = Some(expected.to_status()); + ) + .with_upstream_status(503); + holder.record_failure(&expected.to_status()); drop(holder); for waiter in waiters { let result = tokio::time::timeout(Duration::from_secs(5), waiter) diff --git a/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs b/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs new file mode 100644 index 0000000000..d63743f068 --- /dev/null +++ b/crates/openshell-server/src/grpc/provider/access_token/performance_tests.rs @@ -0,0 +1,834 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::num::NonZeroU64; +use std::path::PathBuf; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use axum::{Json, Router, extract::Path, extract::State, routing::post}; +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use openshell_bootstrap::jwt::generate_jwt_key; +use openshell_core::config::{GatewayJwtConfig, SpiffeWorkloadIdentityConfig}; +use openshell_core::extension_protocol::COMPUTE_PROVIDER_WORKLOAD_IDENTITY; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriver as _; +use openshell_core::proto::datamodel::v1::ObjectMeta; +use openshell_core::proto::{ + AttachSandboxProviderRequest, DetachSandboxProviderRequest, NetworkAccessPreset, + NetworkEndpoint, ProviderCredentialTokenGrantSubjectToken, ProviderProfile, + ProviderProfileCategory, ProviderProfileCredential, SandboxPhase, SandboxSpec, + workspace_selector, +}; +use rcgen::PublicKeyData as _; +use tokio::sync::Notify; +use tokio::task::JoinHandle; +use uuid::Uuid; + +use super::*; +use crate::auth::principal::{SandboxIdentitySource, SandboxPrincipal}; +use crate::auth::sandbox_jwt::SandboxSessionJwtAuthority; +use crate::auth::sandbox_session::PersistedSandboxIdentity; +use crate::compute::ComputeRuntime; +use crate::grpc::sandbox::{handle_attach_sandbox_provider, handle_detach_sandbox_provider}; +use crate::grpc::test_support::{ + authed_request, test_server_state_with_driver, test_server_state_without_provider_profiles, +}; +use crate::persistence::current_time_ms; +use crate::spiffe_broker::SupervisorWorkloadIdentity; +use crate::test_support::FakeComputeDriver; + +const GATEWAY_ID: &str = "performance-test-gateway"; +const ASSERTION_AUDIENCE: &str = "https://issuer.test/"; +const SUBJECT_KEY: &str = "subject_token"; +// Attaching a provider validates the sandbox name, and the sandbox ID is too long for one. +const SANDBOX_NAME: &str = "grant-sandbox"; + +/// A `test.example` trust bundle with the header and key that sign for it. +pub(super) fn workload_trust() -> ( + spiffe::JwtBundleSet, + jsonwebtoken::Header, + jsonwebtoken::EncodingKey, +) { + let key = openshell_crypto::pki::generate_keypair_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap(); + let public_key = key.der_bytes(); + let jwks = serde_json::json!({ + "keys": [{ + "kty": "EC", "crv": "P-256", "alg": "ES256", "kid": "workload-test", + "x": URL_SAFE_NO_PAD.encode(&public_key[1..33]), + "y": URL_SAFE_NO_PAD.encode(&public_key[33..65]), + }] + }); + let mut bundles = spiffe::JwtBundleSet::new(); + bundles.add_bundle( + spiffe::JwtBundle::from_jwt_authorities( + spiffe::TrustDomain::new("test.example").unwrap(), + &serde_json::to_vec(&jwks).unwrap(), + ) + .unwrap(), + ); + let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::ES256); + header.kid = Some("workload-test".into()); + let signing_key = + jsonwebtoken::EncodingKey::from_ec_pem(key.serialize_pem().unwrap().as_bytes()).unwrap(); + (bundles, header, signing_key) +} + +/// The assertion a Kubernetes identity broker would issue for the sandbox. +#[derive(Debug)] +struct TestSandboxIdentity; + +#[async_trait::async_trait] +impl SandboxIdentityProvider for TestSandboxIdentity { + type Error = TokenGrantFailure; + + async fn fetch_jwt_svid( + &self, + gateway_id: &str, + sandbox_id: &str, + _audience: &str, + _runtime_identity: &str, + ) -> Result { + Ok(SandboxJwtSvid { + spiffe_id: format!("spiffe://test.example/gateway/{gateway_id}/sandbox/{sandbox_id}"), + token: "fixture-assertion".to_string(), + expires_at: current_time_ms() / 1000 + 300, + }) + } +} + +#[derive(Default)] +struct Issuer { + warm_calls: AtomicUsize, + cold_calls: AtomicUsize, + cold_started: Notify, + release_cold: Notify, +} + +async fn issue( + State(issuer): State>, + Path(grant): Path, +) -> Json { + let count = match grant.as_str() { + "warm" => issuer.warm_calls.fetch_add(1, Ordering::Relaxed) + 1, + "cold" => { + let count = issuer.cold_calls.fetch_add(1, Ordering::Relaxed) + 1; + if count == 1 { + issuer.cold_started.notify_one(); + issuer.release_cold.notified().await; + } + count + } + _ => panic!("unexpected grant route"), + }; + Json(serde_json::json!({ + "access_token": format!("{grant}-{count}"), + "token_type": "Bearer", + "expires_in": 300, + })) +} + +struct Fixture { + state: Arc, + issuer: Arc, + issuer_task: JoinHandle<()>, + identity: SupervisorWorkloadIdentity, + bundles: spiffe::JwtBundleSet, + id: String, + spiffe_id: String, + launch_spiffe_id: String, + launch_audience: String, + bearer: String, + assertion_key: jsonwebtoken::EncodingKey, + assertion_header: jsonwebtoken::Header, + warm_key: String, + cold_key: String, +} + +impl Fixture { + /// A verified-grant gateway, or with `brokered` the Kubernetes broker path, + /// where requests carry no assertions. + #[allow( + clippy::literal_string_with_formatting_args, + reason = "Axum routes use braces for path parameters" + )] + async fn new(warm_ttl_seconds: i64, warm_subject: Option<&str>, brokered: bool) -> Self { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let issuer = Arc::new(Issuer::default()); + let app = Router::new() + .route("/{grant}", post(issue)) + .with_state(issuer.clone()); + let issuer_task = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + + let id = Uuid::new_v4().to_string(); + let provider_name = format!("grant-{id}"); + let mut state = if brokered { + test_server_state_with_driver("kubernetes").await + } else { + test_server_state_without_provider_profiles().await + }; + let server = Arc::get_mut(&mut state).unwrap(); + server.config.gateway_jwt = Some(GatewayJwtConfig { + gateway_id: GATEWAY_ID.into(), + ttl_secs: NonZeroU64::new(300), + signing_key_path: PathBuf::default(), + public_key_path: PathBuf::default(), + kid_path: PathBuf::default(), + }); + let workload = SpiffeWorkloadIdentityConfig { + spiffe_id_prefix: "spiffe://test.example".into(), + workload_api_socket_path: "/unused/test/workload.sock".into(), + }; + let identity = SupervisorWorkloadIdentity::from_settings( + Some(&workload), + server.config.gateway_jwt.as_ref(), + false, + ) + .unwrap() + .unwrap(); + let spiffe_id = identity.sandbox_spiffe_id(&id).unwrap(); + if brokered { + server.sandbox_identity = Some(Arc::new(TestSandboxIdentity)); + } else { + server.config.spiffe_workload_identity = Some(workload); + let driver = FakeComputeDriver::new(); + let mut capabilities = driver + .get_capabilities(Request::new(GetCapabilitiesRequest::default())) + .await + .unwrap() + .into_inner(); + capabilities + .extension + .as_mut() + .unwrap() + .supported_capabilities + .push(COMPUTE_PROVIDER_WORKLOAD_IDENTITY.into()); + server.compute = ComputeRuntime::from_driver( + "fake-compute-driver".into(), + Arc::new(driver.with_capabilities(capabilities)), + None, + server.store.clone(), + server.sandbox_index.clone(), + server.sandbox_watch_bus.clone(), + server.tracing_log_bus.clone(), + server.supervisor_sessions.clone(), + ) + .await + .unwrap() + .with_provider_workload_identity(Some(identity.clone())) + .unwrap(); + } + + let persisted = PersistedSandboxIdentity::new().unwrap(); + let launch_spiffe_id = identity + .launch_spiffe_id(&id, &persisted.runtime_generation) + .unwrap(); + let launch_audience = persisted.runtime_generation.provider_spiffe_audience(); + let gateway_key = generate_jwt_key().unwrap(); + let authority = Arc::new( + SandboxSessionJwtAuthority::from_pem( + gateway_key.signing_key_pem.as_bytes(), + gateway_key.public_key_pem.as_bytes(), + gateway_key.kid, + GATEWAY_ID, + Some(Duration::from_mins(5)), + ) + .unwrap(), + ); + let bearer = authority + .mint_persisted_launch(&id, &persisted) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + server.sandbox_session_jwt_authority = Some(authority); + let metadata = |name: &str| ObjectMeta { + id: name.into(), + name: name.into(), + workspace: "default".into(), + ..Default::default() + }; + let mut sandbox_meta = metadata(&id); + sandbox_meta.name = SANDBOX_NAME.into(); + persisted.write(&mut sandbox_meta.annotations); + let mut sandbox = Sandbox { + metadata: Some(sandbox_meta), + spec: Some(SandboxSpec { + providers: vec![provider_name.clone()], + provider_attachment_epoch: "attachment".into(), + ..Default::default() + }), + ..Default::default() + }; + sandbox.set_phase(SandboxPhase::Ready as i32); + server.store.put_message(&sandbox).await.unwrap(); + let credential = |name: &str, header: &str, ttl_seconds| ProviderProfileCredential { + name: name.into(), + auth_style: "header".into(), + header_name: header.into(), + token_grant: Some(ProviderCredentialTokenGrant { + token_endpoint: format!("{base_url}/{name}"), + jwt_svid_audience: ASSERTION_AUDIENCE.into(), + grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, + cache_ttl: Some(prost_types::Duration { + seconds: ttl_seconds, + nanos: 0, + }), + ..Default::default() + }), + ..Default::default() + }; + let mut warm = credential("warm", "X-Warm-Token", warm_ttl_seconds); + let mut provider = Provider { + metadata: Some(metadata(&provider_name)), + r#type: format!("profile-{id}"), + ..Default::default() + }; + let mut subject_credentials = Vec::new(); + if let Some(value) = warm_subject { + let grant = warm.token_grant.as_mut().unwrap(); + grant.grant_type = ProviderCredentialTokenGrantType::TokenExchange.into(); + grant.subject_token = Some(ProviderCredentialTokenGrantSubjectToken { + source: "provider_credential".into(), + credential: SUBJECT_KEY.into(), + subject_token_type: oauth::ACCESS_TOKEN_TYPE.into(), + }); + subject_credentials.push(ProviderProfileCredential { + name: SUBJECT_KEY.into(), + ..Default::default() + }); + provider.credential_handles = server + .credentials + .store_provider_credentials( + &provider_name, + "default", + &provider_name, + &HashMap::from([(SUBJECT_KEY.into(), value.into())]), + &HashMap::new(), + ) + .await + .unwrap(); + } + subject_credentials.extend([warm, credential("cold", "X-Cold-Token", 300)]); + let profile = ProviderProfile { + id: provider.r#type.clone(), + display_name: "Grant performance test profile".into(), + category: ProviderProfileCategory::Other as i32, + endpoints: vec![NetworkEndpoint { + host: "api.example.test".into(), + port: 443, + path: "/**".into(), + protocol: "rest".into(), + access: NetworkAccessPreset::Full as i32, + ..Default::default() + }], + credentials: subject_credentials, + ..Default::default() + }; + let mut credentials = HashMap::new(); + insert_dynamic_credentials_for_profile( + &mut credentials, + &openshell_providers::ProviderTypeProfile::from_proto(&profile), + &provider_name, + &provider_name, + ) + .unwrap(); + let key = |name| { + credentials + .keys() + .find(|key| key.ends_with(name)) + .unwrap() + .clone() + }; + let (warm_key, cold_key) = (key(":warm"), key(":cold")); + server.store.put_message(&provider).await.unwrap(); + server + .store + .put_message(&crate::provider_profile_sources::stored_provider_profile( + profile, + )) + .await + .unwrap(); + + let (bundles, assertion_header, assertion_key) = workload_trust(); + identity.seed_test_jwt_bundles(bundles.clone()).await; + + Self { + state, + issuer, + issuer_task, + identity, + bundles, + id, + spiffe_id, + launch_spiffe_id, + launch_audience, + bearer, + assertion_key, + assertion_header, + warm_key, + cold_key, + } + } + + fn request(&self, key: &str, expires_at: i64) -> Request { + let sign = |subject: &str, audience: &str| { + openshell_crypto::jwt::encode( + &self.assertion_header, + &serde_json::json!({ + "sub": subject, + "aud": [audience], + "exp": expires_at, + }), + &self.assertion_key, + ) + .unwrap() + }; + let verified = self.state.compute.provider_workload_identity().is_some(); + let mut request = Request::new(GetSandboxProviderAccessTokenRequest { + credential_key: key.into(), + jwt_svid: verified.then(|| sign(&self.spiffe_id, ASSERTION_AUDIENCE)), + launch_jwt_svid: verified.then(|| sign(&self.launch_spiffe_id, &self.launch_audience)), + }); + request + .extensions_mut() + .insert(Principal::Sandbox(SandboxPrincipal { + sandbox_id: self.id.clone(), + source: SandboxIdentitySource::BootstrapJwt { + issuer: format!("openshell-gateway:{GATEWAY_ID}"), + auth_epoch: None, + }, + trust_domain: None, + })); + request.metadata_mut().insert( + "authorization", + format!("Bearer {}", self.bearer).parse().unwrap(), + ); + request + } + + async fn fingerprint(&self, key: &str) -> String { + let (session, sandbox) = authorize(&self.state, &self.bearer).await.unwrap(); + let configured = grant_configuration(&self.state, &sandbox, key) + .await + .unwrap(); + let subject = resolve_subject(&self.state, &configured).await.unwrap(); + cache_key( + &session, + &configured, + subject.as_ref().map(|subject| subject.value.as_str()), + GATEWAY_ID, + ) + .unwrap() + } + + fn spawn_request( + &self, + key: &str, + expires_at: i64, + ) -> JoinHandle, Status>> { + let state = self.state.clone(); + let request = self.request(key, expires_at); + tokio::spawn(async move { handle(&state, request).await }) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + self.issuer_task.abort(); + } +} + +fn registered(fingerprint: &str) -> usize { + ACQUISITIONS + .lock() + .get(fingerprint) + .map_or(0, |(_, users)| *users) +} + +/// Cache `token` under `fingerprint` for a minute, as a finished acquisition would. +fn cache(fingerprint: String, token: &str) { + ACCESS_TOKENS.set( + fingerprint, + &oauth::OAuthTokenResponse { + access_token: token.into(), + token_type: "Bearer".into(), + expires_in: 60, + }, + current_time_ms() + 60_000, + ); +} + +async fn wait_until(mut ready: impl FnMut() -> bool) { + tokio::time::timeout(Duration::from_secs(5), async { + while !ready() { + tokio::task::yield_now().await; + } + }) + .await + .expect("requests reached acquisition admission"); +} + +#[tokio::test] +async fn a_one_second_ttl_reuses_a_live_token() { + let fixture = Fixture::new(1, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let first = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + let second = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + + assert_eq!(first.access_token, "warm-1"); + assert_eq!(second.access_token, first.access_token); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn dedicated_cold_waiters_leave_capacity_for_warm_grants() { + let fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let warm = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + let fingerprint = fixture.fingerprint(&fixture.cold_key).await; + let leader = fixture.spawn_request(&fixture.cold_key, expires); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("cold leader started its OAuth request"); + let waiters: Vec<_> = (1..PER_SANDBOX_VERIFIED_REQUEST_LIMIT) + .map(|_| fixture.spawn_request(&fixture.cold_key, expires)) + .collect(); + wait_until(|| { + registered(&fingerprint) + waiters.iter().filter(|task| task.is_finished()).count() + == PER_SANDBOX_VERIFIED_REQUEST_LIMIT + }) + .await; + fixture + .identity + .seed_test_jwt_bundles(fixture.bundles.clone()) + .await; + + let cached = tokio::time::timeout( + Duration::from_secs(5), + handle(&fixture.state, fixture.request(&fixture.warm_key, expires)), + ) + .await + .expect("warm request returned while cold leader was blocked") + .unwrap() + .into_inner(); + assert_eq!(cached.access_token, warm.access_token); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); + + fixture.issuer.release_cold.notify_one(); + assert_eq!( + leader.await.unwrap().unwrap().into_inner().access_token, + "cold-1" + ); + let mut refused = 0; + for waiter in waiters { + match waiter.await.unwrap() { + Ok(response) => assert_eq!(response.into_inner().access_token, "cold-1"), + Err(error) => { + assert_eq!(error.code(), tonic::Code::ResourceExhausted); + refused += 1; + } + } + } + assert!(refused > 0); + assert_eq!(fixture.issuer.cold_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn a_queued_expired_proof_does_not_fail_a_fresh_waiter() { + let fixture = Fixture::new(300, None, false).await; + let fingerprint = fixture.fingerprint(&fixture.warm_key).await; + let occupied = ACQUISITIONS.turn(&fingerprint).await.unwrap(); + let now = current_time_ms(); + let short_expiry = now / 1000 + 3; + let short = fixture.spawn_request(&fixture.warm_key, short_expiry); + wait_until(|| registered(&fingerprint) == 2).await; + let fresh = fixture.spawn_request(&fixture.warm_key, now / 1000 + 60); + wait_until(|| registered(&fingerprint) == 3).await; + let remaining = short_expiry.saturating_mul(1000) - current_time_ms(); + tokio::time::sleep(Duration::from_millis(u64::try_from(remaining).unwrap_or(0))).await; + drop(occupied); + + let error = short.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + let response = fresh.await.unwrap().unwrap().into_inner(); + assert_eq!(response.access_token, "warm-1"); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn queued_token_exchange_rejects_a_subject_rotated_under_the_same_handle() { + let fixture = Fixture::new(300, Some("original-subject"), false).await; + let old_fingerprint = fixture.fingerprint(&fixture.warm_key).await; + let occupied = ACQUISITIONS.turn(&old_fingerprint).await.unwrap(); + let expires_at = current_time_ms() / 1000 + 60; + let waiter = fixture.spawn_request(&fixture.warm_key, expires_at); + wait_until(|| registered(&old_fingerprint) == 2).await; + + let provider_id = format!("grant-{}", fixture.id); + let provider = fixture + .state + .store + .get_message::(&provider_id) + .await + .unwrap() + .unwrap(); + let replacement_handles = fixture + .state + .credentials + .store_provider_credentials( + &provider_id, + "default", + &provider_id, + &HashMap::from([(SUBJECT_KEY.into(), "replacement-subject".into())]), + &provider.credential_handles, + ) + .await + .unwrap(); + assert_eq!(replacement_handles, provider.credential_handles); + let new_fingerprint = fixture.fingerprint(&fixture.warm_key).await; + assert_ne!(new_fingerprint, old_fingerprint); + + // Publish the result for the original subject while the request is still + // waiting for the acquisition that produced it. + cache(old_fingerprint, "old-access-token"); + drop(occupied); + + let error = waiter.await.unwrap().unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + cache(new_fingerprint, "new-access-token"); + let response = handle( + &fixture.state, + fixture.request(&fixture.warm_key, expires_at), + ) + .await + .unwrap() + .into_inner(); + assert_eq!(response.access_token, "new-access-token"); + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 0); +} + +#[tokio::test] +async fn a_cache_hit_is_not_served_past_the_subject_expiry() { + let fixture = Fixture::new(300, Some("subject"), false).await; + let store = &fixture.state.store; + let mut provider = store + .get_message::(&format!("grant-{}", fixture.id)) + .await + .unwrap() + .unwrap(); + provider + .credential_handles + .get_mut(SUBJECT_KEY) + .unwrap() + .metadata + .insert( + "test_expiration_ms".into(), + (current_time_ms() + 10_000).to_string(), + ); + store.put_message(&provider).await.unwrap(); + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let expires = current_time_ms() / 1000 + 60; + let response = handle(&fixture.state, fixture.request(&fixture.warm_key, expires)) + .await + .unwrap() + .into_inner(); + assert_eq!(response.access_token, "cached-access-token"); + let lifetime = openshell_core::time::duration_to_std(&response.expires_after.unwrap()).unwrap(); + assert!( + lifetime <= Duration::from_secs(10), + "served for {lifetime:?}" + ); +} + +#[tokio::test] +async fn brokered_token_exchange_cache_hit_resolves_the_subject_once() { + let fixture = Fixture::new(300, Some("user-token"), true).await; + cache( + fixture.fingerprint(&fixture.warm_key).await, + "cached-access-token", + ); + + let (first_read, release_first_read) = fixture.state.credentials.gate_next_resolve(); + let exchange = handle(&fixture.state, fixture.request(&fixture.warm_key, 0)); + tokio::pin!(exchange); + tokio::select! { + result = &mut exchange => panic!("grant finished before resolving the subject: {result:?}"), + first_read = first_read => first_read.unwrap(), + } + let (second_read, _release_second_read) = fixture.state.credentials.gate_next_resolve(); + release_first_read.send(()).unwrap(); + let response = tokio::select! { + result = exchange => result.unwrap().into_inner(), + _ = second_read => panic!("cache hit resolved the subject again"), + }; + assert_eq!(response.access_token, "cached-access-token"); +} + +#[tokio::test] +async fn reattaching_provider_during_exchange_rejects_the_in_flight_token() { + let fixture = Fixture::new(300, None, true).await; + let exchange = fixture.spawn_request(&fixture.cold_key, 0); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let provider = format!("grant-{}", fixture.id); + let detached = handle_detach_sandbox_provider( + &fixture.state, + authed_request(DetachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider: provider.clone(), + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(detached.detached); + let attached = handle_attach_sandbox_provider( + &fixture.state, + authed_request(AttachSandboxProviderRequest { + sandbox: SANDBOX_NAME.into(), + provider, + workspace_scope: Some(workspace_selector("default")), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + assert!(attached.attached); + fixture.issuer.release_cold.notify_one(); + + let error = exchange + .await + .unwrap() + .expect_err("reject the detached grant"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + let new_token = handle(&fixture.state, fixture.request(&fixture.cold_key, 0)) + .await + .unwrap() + .into_inner(); + assert_eq!(new_token.access_token, "cold-2"); +} + +#[tokio::test] +async fn direct_subject_exchange_is_closed_while_workload_identity_is_configured() { + let fixture = Fixture::new(300, None, false).await; + let (metadata, extensions, _) = fixture.request(&fixture.warm_key, 0).into_parts(); + let request = Request::from_parts( + metadata, + extensions, + openshell_core::proto::ExchangeProviderSubjectTokenRequest { + sandbox_id: fixture.id.clone(), + ..Default::default() + }, + ); + let error = + crate::grpc::provider::handle_exchange_provider_subject_token(&fixture.state, request) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); +} + +#[tokio::test] +async fn verified_grants_require_both_assertions() { + let fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + for (provider, launch, code) in [ + (false, false, tonic::Code::FailedPrecondition), + (true, false, tonic::Code::PermissionDenied), + (false, true, tonic::Code::PermissionDenied), + ] { + let mut request = fixture.request(&fixture.warm_key, expires); + if !provider { + request.get_mut().jwt_svid = None; + } + if !launch { + request.get_mut().launch_jwt_svid = None; + } + let error = handle(&fixture.state, request).await.unwrap_err(); + assert_eq!(error.code(), code); + } + assert_eq!(fixture.issuer.warm_calls.load(Ordering::Relaxed), 0); +} + +#[tokio::test] +async fn stopping_or_restarting_during_exchange_rejects_the_in_flight_token() { + for (restart, code) in [ + (false, tonic::Code::FailedPrecondition), + (true, tonic::Code::Unauthenticated), + ] { + let mut fixture = Fixture::new(300, None, false).await; + let expires = current_time_ms() / 1000 + 60; + let in_flight = fixture.spawn_request(&fixture.cold_key, expires); + tokio::time::timeout( + Duration::from_secs(5), + fixture.issuer.cold_started.notified(), + ) + .await + .expect("the issuer received the first exchange"); + let store = fixture.state.store.clone(); + let mut sandbox = store + .get_message::(&fixture.id) + .await + .unwrap() + .unwrap(); + if restart { + // A restart installs a new identity: a new generation and launch. + let annotations = &mut sandbox.metadata.as_mut().unwrap().annotations; + let launch = PersistedSandboxIdentity::new().unwrap(); + launch.write(annotations); + let authority = fixture.state.sandbox_session_jwt_authority.as_ref(); + fixture.bearer = authority + .unwrap() + .mint_persisted_launch(&fixture.id, &launch) + .unwrap() + .supervisor + .gateway_token + .expose_secret() + .to_owned(); + fixture.launch_spiffe_id = fixture + .identity + .launch_spiffe_id(&fixture.id, &launch.runtime_generation) + .unwrap(); + fixture.launch_audience = launch.runtime_generation.provider_spiffe_audience(); + } else { + sandbox.set_phase(SandboxPhase::Stopping as i32); + } + store.put_message(&sandbox).await.unwrap(); + fixture.issuer.release_cold.notify_one(); + assert_eq!(in_flight.await.unwrap().unwrap_err().code(), code); + + // The rejected token was not cached: the next request exchanges again. + sandbox.set_phase(SandboxPhase::Ready as i32); + store.put_message(&sandbox).await.unwrap(); + let next = handle(&fixture.state, fixture.request(&fixture.cold_key, expires)) + .await + .unwrap() + .into_inner(); + assert_eq!(next.access_token, "cold-2"); + } +} diff --git a/crates/openshell-server/src/spiffe_broker.rs b/crates/openshell-server/src/spiffe_broker.rs index 5498b6f2c1..fd298a5c67 100644 --- a/crates/openshell-server/src/spiffe_broker.rs +++ b/crates/openshell-server/src/spiffe_broker.rs @@ -7,6 +7,7 @@ //! [`SandboxIdentityProvider`]; this module chooses the SPIRE adapter when //! `[openshell.gateway.spiffe_broker]` is configured. use std::sync::Arc; +use std::time::{Duration, Instant}; use openshell_core::config::{ Config, GatewayJwtConfig, SpiffeBrokerConfig, SpiffeWorkloadIdentityConfig, @@ -14,6 +15,8 @@ use openshell_core::config::{ use openshell_core::sandbox_generation::SandboxGenerationId; use openshell_core::token_grant_failure::TokenGrantFailure; use openshell_spiffe::{SandboxIdentityProvider, SandboxSpiffeIdPrefix}; +use spiffe::{JwtBundleSet, WorkloadApiClient, WorkloadApiError}; +use tokio::sync::Mutex; /// Check the broker settings `config` enables without building them. /// @@ -31,6 +34,13 @@ pub fn validate_config(config: &Config) -> Result<(), String> { pub struct SupervisorWorkloadIdentity { prefix: SandboxSpiffeIdPrefix, gateway_id: String, + workload_api_socket_path: std::path::PathBuf, + jwt_bundles: Arc>>, +} + +struct JwtBundleSnapshot { + fetched_at: Instant, + bundles: Arc, } impl SupervisorWorkloadIdentity { @@ -73,6 +83,8 @@ impl SupervisorWorkloadIdentity { Ok(Some(Self { prefix, gateway_id: jwt.gateway_id.clone(), + workload_api_socket_path: workload.workload_api_socket_path.clone(), + jwt_bundles: Arc::default(), })) } @@ -90,6 +102,34 @@ impl SupervisorWorkloadIdentity { self.prefix .supervisor_launch_spiffe_id(&self.gateway_id, sandbox_id, generation.as_str()) } + + #[cfg(test)] + pub(crate) async fn seed_test_jwt_bundles(&self, bundles: JwtBundleSet) { + *self.jwt_bundles.lock().await = Some(JwtBundleSnapshot { + fetched_at: Instant::now(), + bundles: Arc::new(bundles), + }); + } + + pub(crate) async fn jwt_bundles(&self) -> Result, WorkloadApiError> { + // Share a very recent bundle across grants. An expired snapshot never + // authorizes a request if the Workload API fails during refresh. + let mut snapshot = self.jwt_bundles.lock().await; + if let Some(snapshot) = snapshot.as_ref() + && snapshot.fetched_at.elapsed() < Duration::from_secs(5) + { + return Ok(snapshot.bundles.clone()); + } + + let endpoint = openshell_spiffe::workload_api_endpoint(&self.workload_api_socket_path); + let client = WorkloadApiClient::connect_to(&endpoint).await?; + let bundles = Arc::new(client.fetch_jwt_bundles().await?); + *snapshot = Some(JwtBundleSnapshot { + fetched_at: Instant::now(), + bundles: bundles.clone(), + }); + Ok(bundles) + } } /// The sandbox identity provider `config` enables, if any. @@ -122,3 +162,43 @@ fn enabled(config: &Config) -> Result, String> { } Ok(Some(broker)) } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn jwt_bundles_serves_a_fresh_snapshot_and_never_a_stale_one() { + let identity = SupervisorWorkloadIdentity::from_settings( + Some(&SpiffeWorkloadIdentityConfig { + spiffe_id_prefix: "spiffe://test.example".into(), + workload_api_socket_path: "/nonexistent/workload.sock".into(), + }), + Some(&GatewayJwtConfig { + gateway_id: "bundle-test".into(), + ttl_secs: std::num::NonZeroU64::new(300), + signing_key_path: std::path::PathBuf::default(), + public_key_path: std::path::PathBuf::default(), + kid_path: std::path::PathBuf::default(), + }), + false, + ) + .unwrap() + .unwrap(); + let bundles = Arc::new(JwtBundleSet::new()); + let aged = |age| { + Some(JwtBundleSnapshot { + fetched_at: Instant::now().checked_sub(age).unwrap(), + bundles: bundles.clone(), + }) + }; + // The Workload API socket does not exist, so every refresh fails. + *identity.jwt_bundles.lock().await = aged(Duration::from_secs(6)); + assert!(identity.jwt_bundles().await.is_err()); + *identity.jwt_bundles.lock().await = aged(Duration::ZERO); + assert!(Arc::ptr_eq( + &identity.jwt_bundles().await.unwrap(), + &bundles + )); + } +}