diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 6e97f2dd1f..d87d6c7c3e 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -68,6 +68,7 @@ pub mod shell; pub mod telemetry; pub mod time; pub mod token_endpoint; +pub mod token_grant_config; pub mod token_grant_failure; pub mod transport_errors; pub mod upload; diff --git a/crates/openshell-core/src/oauth.rs b/crates/openshell-core/src/oauth.rs index 8e31239d97..3461edcc07 100644 --- a/crates/openshell-core/src/oauth.rs +++ b/crates/openshell-core/src/oauth.rs @@ -22,6 +22,7 @@ use crate::token_grant_failure::{ pub const DEFAULT_CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token"; +pub use crate::token_grant_config::JWT_TOKEN_TYPE; const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange"; const ERROR_CONTRACT: &str = "openshell.token-grant.v1"; const MAX_TOKEN_RESPONSE_BYTES: usize = 64 * 1024; @@ -204,11 +205,37 @@ pub async fn post_oauth_token_grant( .await } +/// Authentication to the external token endpoint, independent of the subject. +#[derive(Clone, Copy)] +pub enum ClientAuthentication<'a> { + None, + ClientAssertion { + assertion: &'a str, + assertion_type: &'a str, + }, +} + +impl<'a> ClientAuthentication<'a> { + /// Resolve a validated profile's authentication using the acquired SVID. + pub fn from_config( + config: Option<&crate::proto::ProviderCredentialTokenGrantClientAuthentication>, + svid: &'a str, + assertion_type: &'a str, + ) -> Self { + if config.is_some_and(|auth| auth.mechanism == "none") { + Self::None + } else { + Self::ClientAssertion { + assertion: svid, + assertion_type, + } + } + } +} + /// RFC 8693 token-exchange form fields. pub struct TokenExchangeParams<'a> { - /// Secret JWT client assertion sent only to the configured endpoint. - pub client_assertion: &'a str, - pub client_assertion_type: &'a str, + pub client_authentication: ClientAuthentication<'a>, /// Secret subject credential to exchange for a resource token. pub subject_token: &'a str, pub subject_token_type: &'a str, @@ -229,17 +256,25 @@ pub async fn post_oauth_token_exchange( params: &TokenExchangeParams<'_>, request_id: Option<&str>, ) -> Result { - let client_assertion_type = effective_client_assertion_type(params.client_assertion_type); let subject_token_type = effective_token_type(params.subject_token_type); let requested_token_type = effective_token_type(params.requested_token_type); - let form_params = vec![ + let mut form_params = vec![ ("grant_type", TOKEN_EXCHANGE_GRANT_TYPE), - ("client_assertion_type", client_assertion_type), - ("client_assertion", params.client_assertion), ("subject_token", params.subject_token), ("subject_token_type", subject_token_type), ("requested_token_type", requested_token_type), ]; + if let ClientAuthentication::ClientAssertion { + assertion, + assertion_type, + } = params.client_authentication + { + form_params.push(("client_assertion", assertion)); + form_params.push(( + "client_assertion_type", + effective_client_assertion_type(assertion_type), + )); + } post_oauth_token_request( client, token_endpoint, @@ -459,6 +494,7 @@ mod tests { #[derive(Debug)] struct CapturedRequest { + authorization: Option, form: HashMap, request_id: Option, } @@ -508,6 +544,11 @@ mod tests { }); let form_body = String::from_utf8_lossy(&buf[header_end..]); CapturedRequest { + authorization: headers.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("authorization") + .then(|| value.trim().to_string()) + }), form: parse_form_body(&form_body), request_id, } @@ -790,6 +831,36 @@ mod tests { server.await.expect("bound fixture"); } + #[tokio::test] + async fn jwt_subject_exchange_without_client_authentication() { + let (endpoint, request) = token_endpoint_once( + "200 OK", + r#"{"access_token":"google-token","expires_in":3600}"#, + ) + .await; + post_oauth_token_exchange(&test_client(), &endpoint, &TokenExchangeParams { + client_authentication: ClientAuthentication::None, + subject_token: "sandbox-jwt-svid", + subject_token_type: JWT_TOKEN_TYPE, + audience: "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/pool/providers/spire", + scopes: &["https://www.googleapis.com/auth/cloud-platform".into()], + requested_token_type: "", + }, None).await.expect("exchange"); + let request = request.await.unwrap(); + assert!(request.authorization.is_none()); + assert_eq!(request.form.len(), 6); + assert_eq!(request.form["grant_type"], TOKEN_EXCHANGE_GRANT_TYPE); + assert_eq!(request.form["subject_token"], "sandbox-jwt-svid"); + assert_eq!(request.form["subject_token_type"], JWT_TOKEN_TYPE); + assert_eq!(request.form["requested_token_type"], ACCESS_TOKEN_TYPE); + assert_eq!( + request.form["scope"], + "https://www.googleapis.com/auth/cloud-platform" + ); + assert!(!request.form.contains_key("client_assertion")); + assert!(!request.form.contains_key("client_assertion_type")); + } + #[tokio::test] async fn posts_form_params_and_parses_success_response() { let (endpoint, request) = token_endpoint_once( @@ -885,8 +956,10 @@ mod tests { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", - client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe", + client_authentication: ClientAuthentication::ClientAssertion { + assertion: "jwt-svid-token", + assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe", + }, subject_token: "subject-access-token", subject_token_type: ACCESS_TOKEN_TYPE, audience: "api://resource", @@ -952,8 +1025,10 @@ mod tests { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", - client_assertion_type: "", + client_authentication: ClientAuthentication::ClientAssertion { + assertion: "jwt-svid-token", + assertion_type: "", + }, subject_token: "subject-token", subject_token_type: "", audience: "", diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 2aa1efdbf7..6defa53404 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -701,15 +701,42 @@ impl ProviderCredentialState { /// Searches `google_cloud::TOKEN_ENV_KEYS` in priority order (SA before /// ADC) atomically to avoid inconsistency during credential /// refresh. Returns `None` if no GCP token is configured or all are - /// expired. The `expires_in` defaults to 3600 when expiry is unknown. + /// expired. Dynamic grants return a placeholder with a 3600-second SDK + /// refresh interval; their real token expiry is managed by the grant cache. + /// Static credentials also default to 3600 when expiry is unknown. pub fn gcp_token_response(&self) -> Option<(String, i64)> { const DEFAULT_EXPIRES_IN: i64 = 3600; let inner = self .inner .read() .expect("provider credential state poisoned"); - let resolver = inner.current_resolver.as_ref()?; for key in crate::google_cloud::TOKEN_ENV_KEYS { + // A dynamic grant has no static secret to unwrap. Its placeholder + // is replaced only after endpoint admission by token-grant injection. + if inner + .current + .dynamic_credentials + .values() + .any(|credential| { + credential.env_vars.iter().any(|env| env == key) + && credential.auth_style == "bearer" + && !credential.token_grant_owners.is_empty() + && credential.token_grant.as_ref().is_some_and(|grant| { + crate::token_grant_config::validate_token_grant_identity(grant).is_ok() + }) + }) + { + return Some(( + crate::secrets::placeholder_for_env_key_for_revision( + key, + inner.current.revision, + ), + DEFAULT_EXPIRES_IN, + )); + } + let Some(resolver) = inner.current_resolver.as_ref() else { + continue; + }; let Some(placeholder) = inner.current.child_env.get(*key).cloned() else { continue; }; @@ -3511,6 +3538,33 @@ mod tests { ); } + #[test] + fn gcp_token_response_serves_dynamic_placeholder_and_revokes_on_detach() { + let declaration = crate::proto::ProviderProfileCredential { + name: "access_token".into(), + env_vars: vec!["GCP_ADC_ACCESS_TOKEN".into()], + auth_style: "bearer".into(), + token_grant_owners: vec!["owner".into()], + token_grant: Some(crate::proto::ProviderCredentialTokenGrant { + token_endpoint: "https://sts.googleapis.com/v1/token".into(), + ..Default::default() + }), + ..Default::default() + }; + let state = ProviderCredentialState::from_environment( + 7, + HashMap::new(), + HashMap::new(), + HashMap::from([("gcp:access_token".into(), declaration)]), + ); + let (placeholder, lifetime) = state.gcp_token_response().expect("dynamic metadata"); + assert_eq!(placeholder, "openshell:resolve:env:v7_GCP_ADC_ACCESS_TOKEN"); + assert_eq!(lifetime, 3600); + assert!(state.snapshot().child_env.is_empty()); + state.install_environment(8, HashMap::new(), HashMap::new(), HashMap::new()); + assert!(state.gcp_token_response().is_none()); + } + #[test] fn gcp_token_response_returns_sa_over_adc() { let state = ProviderCredentialState::from_environment( diff --git a/crates/openshell-core/src/token_grant_config.rs b/crates/openshell-core/src/token_grant_config.rs new file mode 100644 index 0000000000..7bcb15af63 --- /dev/null +++ b/crates/openshell-core/src/token_grant_config.rs @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Pure validation for token-grant identity configuration. + +pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt"; + +/// A profile field and a credential-free validation diagnostic. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TokenGrantIdentityError { + pub field: &'static str, + pub message: &'static str, +} + +const fn invalid(field: &'static str, message: &'static str) -> TokenGrantIdentityError { + TokenGrantIdentityError { field, message } +} + +/// Validate identity choices before acquiring credentials or serving cached tokens. +pub fn validate_token_grant_identity( + grant: &crate::proto::ProviderCredentialTokenGrant, +) -> Result<(), TokenGrantIdentityError> { + use crate::proto::ProviderCredentialTokenGrantType as Grant; + let kind = Grant::try_from(grant.grant_type) + .map_err(|_| invalid("grant_type", "unsupported grant_type"))?; + if let Some(auth) = &grant.client_authentication { + match auth.mechanism.as_str() { + "none" => { + if auth.credential.is_some() { + return Err(invalid( + "client_authentication.credential", + "client_authentication none forbids credential", + )); + } + if !grant.client_assertion_type.is_empty() { + return Err(invalid( + "client_assertion_type", + "client_assertion_type requires client_assertion authentication", + )); + } + if kind != Grant::TokenExchange { + return Err(invalid( + "client_authentication.mechanism", + "client_credentials requires client_assertion authentication", + )); + } + } + "client_assertion" => { + if auth + .credential + .as_ref() + .is_none_or(|credential| credential.source != "jwt_svid") + { + return Err(invalid( + "client_authentication.credential.source", + "client_assertion requires credential.source: jwt_svid", + )); + } + } + _ => { + return Err(invalid( + "client_authentication.mechanism", + "unsupported client_authentication.mechanism", + )); + } + } + } + if kind != Grant::TokenExchange { + return if grant.subject_token.is_some() { + Err(invalid( + "subject_token", + "subject_token is only valid for token_exchange grants", + )) + } else { + Ok(()) + }; + } + let subject = grant.subject_token.as_ref().ok_or(invalid( + "subject_token", + "token_exchange grants require subject_token", + ))?; + match subject.source.as_str() { + "provider_credential" => { + if subject.credential.trim().is_empty() { + return Err(invalid( + "subject_token.credential", + "subject_token.credential is required", + )); + } + } + "jwt_svid" => { + if !subject.credential.is_empty() { + return Err(invalid( + "subject_token.credential", + "jwt_svid subject forbids subject_token.credential", + )); + } + if !subject.subject_token_type.is_empty() + && subject.subject_token_type != JWT_TOKEN_TYPE + { + return Err(invalid( + "subject_token.subject_token_type", + "jwt_svid subject requires the JWT subject_token_type", + )); + } + } + _ => { + return Err(invalid( + "subject_token.source", + "subject_token.source must be provider_credential or jwt_svid", + )); + } + } + Ok(()) +} diff --git a/crates/openshell-core/tests/oauth_error_logging.rs b/crates/openshell-core/tests/oauth_error_logging.rs index a8f5cd4951..5c98021b06 100644 --- a/crates/openshell-core/tests/oauth_error_logging.rs +++ b/crates/openshell-core/tests/oauth_error_logging.rs @@ -92,8 +92,11 @@ async fn rejected_grant_log_omits_token_service_error_text() { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", - client_assertion_type: "", + client_authentication: + openshell_core::oauth::ClientAuthentication::ClientAssertion { + assertion: "jwt-svid-token", + assertion_type: "", + }, subject_token: CANARY, subject_token_type: "", audience: "", diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index b5aac1a5ec..d47988f4bc 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -180,6 +180,8 @@ pub struct TokenGrantProfile { )] pub grant_type: ProviderCredentialTokenGrantType, pub token_endpoint: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_authentication: Option, #[serde(default, skip_serializing_if = "String::is_empty")] pub audience: String, #[serde(default, skip_serializing_if = "String::is_empty")] @@ -208,7 +210,8 @@ pub struct TokenGrantProfile { impl PartialEq for TokenGrantProfile { fn eq(&self, other: &Self) -> bool { - self.grant_type == other.grant_type + self.client_authentication == other.client_authentication + && self.grant_type == other.grant_type && self.token_endpoint == other.token_endpoint && self.audience == other.audience && self.jwt_svid_audience == other.jwt_svid_audience @@ -223,9 +226,24 @@ impl PartialEq for TokenGrantProfile { impl Eq for TokenGrantProfile {} +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TokenGrantClientAuthenticationProfile { + pub mechanism: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct TokenGrantClientCredentialProfile { + pub source: String, +} + #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] pub struct TokenGrantSubjectTokenProfile { pub source: String, + #[serde(default, skip_serializing_if = "String::is_empty")] pub credential: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub subject_token_type: String, @@ -1549,6 +1567,16 @@ fn token_grant_from_proto( .unwrap_or(ProviderCredentialTokenGrantType::ClientCredentials), ), token_endpoint: token_grant.token_endpoint.clone(), + client_authentication: token_grant.client_authentication.as_ref().map(|auth| { + TokenGrantClientAuthenticationProfile { + mechanism: auth.mechanism.clone(), + credential: auth.credential.as_ref().map(|credential| { + TokenGrantClientCredentialProfile { + source: credential.source.clone(), + } + }), + } + }), audience: token_grant.audience.clone(), jwt_svid_audience: token_grant.jwt_svid_audience.clone(), client_assertion_type: token_grant.client_assertion_type.clone(), @@ -1574,6 +1602,16 @@ fn token_grant_to_proto( openshell_core::proto::ProviderCredentialTokenGrant { grant_type: token_grant.grant_type as i32, token_endpoint: token_grant.token_endpoint.clone(), + client_authentication: token_grant.client_authentication.as_ref().map(|auth| { + openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication { + mechanism: auth.mechanism.clone(), + credential: auth.credential.as_ref().map(|credential| { + openshell_core::proto::ProviderCredentialTokenGrantClientCredential { + source: credential.source.clone(), + } + }), + } + }), audience: token_grant.audience.clone(), jwt_svid_audience: token_grant.jwt_svid_audience.clone(), client_assertion_type: token_grant.client_assertion_type.clone(), @@ -3332,61 +3370,28 @@ fn validate_token_grant_subject_token( let Some(token_grant) = credential.token_grant.as_ref() else { return Vec::new(); }; - let grant_type = effective_token_grant_type(token_grant.grant_type); let mut diagnostics = Vec::new(); - - match grant_type { - ProviderCredentialTokenGrantType::ClientCredentials => { - if token_grant.subject_token.is_some() { - diagnostics.push(ProfileValidationDiagnostic::error( - source, - profile_id, - "credentials.token_grant.subject_token", - "subject_token is only valid for token_exchange grants", - )); - } - } - ProviderCredentialTokenGrantType::TokenExchange => { - let Some(subject_token) = token_grant.subject_token.as_ref() else { - diagnostics.push(ProfileValidationDiagnostic::error( - source, - profile_id, - "credentials.token_grant.subject_token", - "token_exchange grants require subject_token", - )); - return diagnostics; - }; - - let source_value = subject_token.source.trim(); - if source_value != "provider_credential" { - diagnostics.push(ProfileValidationDiagnostic::error( - source, - profile_id, - "credentials.token_grant.subject_token.source", - "subject_token.source must be provider_credential", - )); - } - - let subject_credential = subject_token.credential.trim(); - if subject_credential.is_empty() { - diagnostics.push(ProfileValidationDiagnostic::error( - source, - profile_id, - "credentials.token_grant.subject_token.credential", - "subject_token.credential is required", - )); - } else if !credential_names.contains(subject_credential) { - diagnostics.push(ProfileValidationDiagnostic::error( - source, - profile_id, - "credentials.token_grant.subject_token.credential", - format!("unknown subject token credential: {subject_credential}"), - )); - } - } - ProviderCredentialTokenGrantType::Unspecified => { - unreachable!("effective_token_grant_type must normalize unspecified token grant type") - } + if let Err(error) = openshell_core::token_grant_config::validate_token_grant_identity( + &token_grant_to_proto(token_grant), + ) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + format!("credentials.token_grant.{}", error.field), + error.message, + )); + } + if let Some(subject) = token_grant.subject_token.as_ref() + && subject.source == "provider_credential" + && !subject.credential.is_empty() + && !credential_names.contains(subject.credential.trim()) + { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.token_grant.subject_token.credential", + format!("unknown subject token credential: {}", subject.credential), + )); } diagnostics @@ -3785,11 +3790,11 @@ mod tests { use super::{ DiscoveryProfile, EndpointProfile, L7AllowProfile, L7QueryMatcherProfile, - ProfileDurationWkt, ProfileError, ProviderTypeProfile, is_mcp_diagnostic_field, - normalize_profile_id, parse_profile_catalog_yamls, parse_profile_json, parse_profile_yaml, - profile_duration_to_proto, profile_to_json, profile_to_yaml, profiles_to_json, - profiles_to_yaml, token_grant_from_proto, token_grant_to_proto, validate_profile_duration, - validate_profile_set, + ProfileDurationWkt, ProfileError, ProviderTypeProfile, TokenGrantClientCredentialProfile, + is_mcp_diagnostic_field, normalize_profile_id, parse_profile_catalog_yamls, + parse_profile_json, parse_profile_yaml, profile_duration_to_proto, profile_to_json, + profile_to_yaml, profiles_to_json, profiles_to_yaml, token_grant_from_proto, + token_grant_to_proto, validate_profile_duration, validate_profile_set, }; /// The example profiles in `providers/`, parsed once per test binary. @@ -5534,6 +5539,110 @@ credentials: ); } + #[test] + fn jwt_subject_authentication_combinations_validate_and_round_trip() { + for mechanism in ["none", "client_assertion"] { + for source in ["jwt_svid", "provider_credential"] { + let client_credential = if mechanism == "client_assertion" { + "\n credential:\n source: jwt_svid" + } else { + "" + }; + let subject_credential = if source == "provider_credential" { + "\n credential: stored_token" + } else { + "" + }; + let yaml = format!( + r" +id: federation +display_name: Federation +credentials: + - name: stored_token + - name: access_token + auth_style: bearer + header_name: authorization + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + client_authentication: + mechanism: {mechanism}{client_credential} + subject_token: + source: {source}{subject_credential} +" + ); + let profile = parse_profile_yaml(&yaml).unwrap(); + let diagnostics = + validate_profile_set(&[("federation.yaml".into(), profile.clone())]); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + let restored = ProviderTypeProfile::from_proto(&profile.to_proto()); + let reparsed = parse_profile_yaml(&profile_to_yaml(&restored).unwrap()).unwrap(); + assert_eq!( + profile.credentials[1].token_grant, + reparsed.credentials[1].token_grant + ); + + let mut invalid = profile.clone(); + let grant = invalid.credentials[1].token_grant.as_mut().unwrap(); + if mechanism == "none" { + grant.client_assertion_type = "assertion-type".into(); + } else { + grant.client_authentication.as_mut().unwrap().credential = None; + } + assert!(!validate_profile_set(&[("invalid.yaml".into(), invalid)]).is_empty()); + } + } + } + + #[test] + fn jwt_subject_rejects_incompatible_identity_configuration() { + let yaml = r" +id: federation +display_name: Federation +credentials: + - name: access_token + auth_style: bearer + header_name: authorization + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + client_authentication: + mechanism: none + subject_token: + source: jwt_svid +"; + let profile = parse_profile_yaml(yaml).unwrap(); + for case in 0..7 { + let mut invalid = profile.clone(); + let grant = invalid.credentials[0].token_grant.as_mut().unwrap(); + match case { + 0 => grant.subject_token.as_mut().unwrap().credential = "stored".into(), + 1 => { + grant.subject_token.as_mut().unwrap().subject_token_type = + "urn:ietf:params:oauth:token-type:access_token".into(); + } + 2 => grant.subject_token.as_mut().unwrap().source = "unknown".into(), + 3 => grant.client_authentication.as_mut().unwrap().mechanism = "bearer".into(), + 4 => { + grant.client_authentication.as_mut().unwrap().credential = + Some(TokenGrantClientCredentialProfile { + source: "jwt_svid".into(), + }); + } + 5 => { + grant.grant_type = ProviderCredentialTokenGrantType::ClientCredentials; + grant.subject_token = None; + } + 6 => grant.subject_token = None, + _ => unreachable!(), + } + assert!( + !validate_profile_set(&[("invalid.yaml".into(), invalid)]).is_empty(), + "case {case}" + ); + } + } + #[test] fn validate_profile_set_rejects_token_exchange_without_subject_token() { let profile = parse_profile_yaml( diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 5ed71fa701..1b17c1ec2c 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -4885,6 +4885,8 @@ async fn exchange_provider_subject_token_inner( .token_grant .as_ref() .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + openshell_core::token_grant_config::validate_token_grant_identity(token_grant) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; let grant_type = ProviderCredentialTokenGrantType::try_from(token_grant.grant_type) .unwrap_or(ProviderCredentialTokenGrantType::ClientCredentials); if grant_type != ProviderCredentialTokenGrantType::TokenExchange { @@ -4934,6 +4936,7 @@ async fn exchange_provider_subject_token_inner( .await?; let intermediate_cache_key = intermediate_token_cache_key(IntermediateTokenCacheKeyInput { + client_authentication: token_grant.client_authentication.as_ref(), provider: &provider, dynamic_credential: &req.credential_key, subject_credential: &subject_token.credential, @@ -4959,8 +4962,11 @@ async fn exchange_provider_subject_token_inner( let token_response = perform_intermediate_token_exchange( &token_grant.token_endpoint, &TokenExchangeParams { - client_assertion: &gateway_jwt_svid, - client_assertion_type: &token_grant.client_assertion_type, + client_authentication: oauth::ClientAuthentication::from_config( + token_grant.client_authentication.as_ref(), + &gateway_jwt_svid, + &token_grant.client_assertion_type, + ), subject_token: &stored_subject_token, subject_token_type: &subject_token.subject_token_type, audience: &supervisor_claims.sub, @@ -5073,6 +5079,8 @@ fn provider_credential_expiration_ms( } struct IntermediateTokenCacheKeyInput<'a> { + client_authentication: + Option<&'a openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication>, provider: &'a Provider, dynamic_credential: &'a str, subject_credential: &'a str, @@ -5099,7 +5107,7 @@ fn intermediate_token_cache_key(input: IntermediateTokenCacheKeyInput<'_>) -> St .as_ref() .map_or(0, |metadata| metadata.resource_version); format!( - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", + "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:?}", provider_id, provider_resource_version, input.dynamic_credential, @@ -5110,7 +5118,8 @@ fn intermediate_token_cache_key(input: IntermediateTokenCacheKeyInput<'_>) -> St input.audience, input.requested_token_type, input.supervisor_subject, - input.gateway_subject + input.gateway_subject, + input.client_authentication ) } @@ -6772,8 +6781,10 @@ pub(super) mod tests { String::from_utf8_lossy(&request).to_ascii_lowercase() }); let params = TokenExchangeParams { - client_assertion: SECRET, - client_assertion_type: "", + client_authentication: oauth::ClientAuthentication::ClientAssertion { + assertion: SECRET, + assertion_type: "", + }, subject_token: SECRET, subject_token_type: "", audience: SECRET, @@ -6904,6 +6915,7 @@ pub(super) mod tests { path_template: String::new(), token_grant_owners: vec!["untrusted-profile-owner".to_string()], token_grant: Some(ProviderCredentialTokenGrant { + client_authentication: None, grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, token_endpoint: "http://keycloak.default.svc.cluster.local/realms/openshell/protocol/openid-connect/token".to_string(), audience: "api://default".to_string(), @@ -8142,6 +8154,7 @@ pub(super) mod tests { refresh: None, path_template: String::new(), token_grant: Some(ProviderCredentialTokenGrant { + client_authentication: None, grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, token_endpoint: "https://auth.example.com/token".to_string(), audience: "api://default".to_string(), diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index 2936803b0a..67f8ca7dbb 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -246,6 +246,8 @@ async fn obtain( let key = &request.get_ref().credential_key; let configured = grant_configuration(state, session.sandbox_id.as_str(), key).await?; let grant = &configured.grant; + openshell_core::token_grant_config::validate_token_grant_identity(grant) + .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; let ttl_override = grant .cache_ttl .as_ref() @@ -263,7 +265,12 @@ async fn obtain( .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 = if grant_type == ProviderCredentialTokenGrantType::TokenExchange + && grant + .subject_token + .as_ref() + .is_some_and(|subject| subject.source == "provider_credential") + { let subject = grant .subject_token .as_ref() @@ -418,7 +425,32 @@ async fn acquire( authorize(state, bearer).await?; let client = token_exchange_http_client()?; let subject_expiry = subject.and_then(|subject| subject.expires_at_ms); - let token = if let Some(subject) = subject { + let authentication = oauth::ClientAuthentication::from_config( + grant.client_authentication.as_ref(), + &svid.token, + &grant.client_assertion_type, + ); + let token = if grant + .subject_token + .as_ref() + .is_some_and(|subject| subject.source == "jwt_svid") + { + oauth::post_oauth_token_exchange( + client, + &grant.token_endpoint, + &TokenExchangeParams { + client_authentication: authentication, + subject_token: &svid.token, + subject_token_type: oauth::JWT_TOKEN_TYPE, + audience: &grant.audience, + scopes: &grant.scopes, + requested_token_type: &grant.requested_token_type, + }, + request_id, + ) + .await + .map_err(TokenGrantFailure::to_status)? + } else if let Some(subject) = subject { let component_svid = fetch_gateway_jwt_svid_from( &audience, state @@ -431,8 +463,11 @@ async fn acquire( let intermediate = perform_intermediate_token_exchange( &grant.token_endpoint, &TokenExchangeParams { - client_assertion: &component_svid, - client_assertion_type: &grant.client_assertion_type, + client_authentication: oauth::ClientAuthentication::from_config( + grant.client_authentication.as_ref(), + &component_svid, + &grant.client_assertion_type, + ), subject_token: &subject.value, subject_token_type: &subject.token_type, audience: &svid.spiffe_id, @@ -447,8 +482,7 @@ async fn acquire( client, &grant.token_endpoint, &TokenExchangeParams { - client_assertion: &svid.token, - client_assertion_type: &grant.client_assertion_type, + client_authentication: authentication, subject_token: &intermediate.access_token, subject_token_type: oauth::ACCESS_TOKEN_TYPE, audience: &grant.audience, @@ -742,6 +776,26 @@ mod tests { fingerprint(&session, owned, None), fingerprint(&session, owned, Some("")) ); + let mut configured = configured("provider:access"); + let before = cache_key(&session, &configured, None, "gateway").unwrap(); + configured.grant.client_authentication = Some( + openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication { + mechanism: "none".into(), + credential: None, + }, + ); + let unauthenticated = cache_key(&session, &configured, None, "gateway").unwrap(); + assert_ne!(before, unauthenticated); + configured.grant.subject_token = Some( + openshell_core::proto::ProviderCredentialTokenGrantSubjectToken { + source: "jwt_svid".into(), + ..Default::default() + }, + ); + assert_ne!( + unauthenticated, + cache_key(&session, &configured, None, "gateway").unwrap() + ); } #[test] diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 74e6f3acc4..a1671a54e5 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -241,14 +241,16 @@ mod tests { // Discovery RPCs move to ServiceDiscovery. Application URL maps add two // public-only messages alongside main's public APIs; durable schemas // and the public/durable overlap remain unchanged. + // Token grants add optional client authentication and its credential source + // to both public and durable profiles. Existing wire fields are unchanged. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "3f6f958d6907255c148c366a45bd998beddd39432f2165bebe6c060eb28ef10c"; + "9be8314fb55595d3ff1dc3811214f86ea92aa63713c71ea53638d74ad2c87991"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "e956b54b3f121eaae7d492437a3fa8f56fb3c8bbe8d3366a46dd730caed63203"; + "3a4171e5f9cca9deff42abf16e51ac4b16b794da5c5831f53bc432ec00d4a280"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "c0c3ea17f105aaa6d843c466fd4240451c2105dce7675384935d4aaecdac8abf"; + "8ffd459160acba633386f26b8141151f0f61deae2ac6562327b56526d75cc557"; // Encoded with the schema that omitted stable_placeholder. Keep these // bytes fixed so the current encoder cannot hide a compatibility change. const LEGACY_STATIC_PROFILE: &str = "0a240a116c65676163792d70726f66696c652d6964120d6c65676163792d737461746963280712510a0d6c65676163792d73746174696312184c6567616379207374617469632063726564656e7469616c2a260a076170695f6b65791a1153594e5448455449435f4150495f4b455920012a06626561726572"; @@ -792,9 +794,9 @@ mod tests { overlap_hash.as_str(), ), ( - (367, 31), - (102, 22), - (86, 22), + (369, 31), + (104, 22), + (88, 22), PUBLIC_RPC_SCHEMA_SHA256, DURABLE_SCHEMA_SHA256, PUBLIC_DURABLE_OVERLAP_SHA256 diff --git a/crates/openshell-supervisor-network/README.md b/crates/openshell-supervisor-network/README.md index 591b7274fb..dcf0409954 100644 --- a/crates/openshell-supervisor-network/README.md +++ b/crates/openshell-supervisor-network/README.md @@ -31,7 +31,8 @@ never served to another. A dedicated supervisor uses `SpiffeTokenGrantResolver` with its SPIFFE Workload API socket. That resolver owns the instance's token cache and HTTP client and -uses the gateway only for the intermediate exchange of RFC 8693 grants. +uses the gateway only for intermediate exchanges with stored subject credentials. +JWT-SVID subjects are exchanged directly, with the configured client authentication. Without a socket, its grants fail closed. Shared sandbox instances use `GatewayTokenGrantResolver`, which holds only the instance's authenticated gateway channel, connected on the first grant and reused. Each admitted diff --git a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs index 2b76265970..89e4aba8a4 100644 --- a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs +++ b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs @@ -32,6 +32,9 @@ use crate::l7::relay::L7EvalContext; /// Borrowed grant configuration for one endpoint-bound provider credential. pub struct TokenGrantRequest<'a> { + pub client_authentication: + Option<&'a openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication>, + pub subject_token: Option<&'a openshell_core::proto::ProviderCredentialTokenGrantSubjectToken>, pub provider_key: &'a str, pub token_endpoint: &'a str, pub jwt_svid_audience: &'a str, @@ -556,6 +559,8 @@ fn token_grant_request<'a>( token_grant: &'a ProviderCredentialTokenGrant, request_id: &'a str, ) -> Result, TokenGrantFailure> { + openshell_core::token_grant_config::validate_token_grant_identity(token_grant) + .map_err(|_| injection_configuration_failure())?; let cache_ttl = token_grant .cache_ttl .as_ref() @@ -568,6 +573,8 @@ fn token_grant_request<'a>( ) })?; Ok(TokenGrantRequest { + client_authentication: token_grant.client_authentication.as_ref(), + subject_token: token_grant.subject_token.as_ref(), provider_key, token_endpoint: &token_grant.token_endpoint, jwt_svid_audience: &token_grant.jwt_svid_audience, @@ -1032,6 +1039,7 @@ pub mod test_support { fn token_grant() -> ProviderCredentialTokenGrant { ProviderCredentialTokenGrant { + client_authentication: None, token_endpoint: "https://auth.example.com/token".to_string(), audience: "api://example".to_string(), jwt_svid_audience: "https://auth.example.com".to_string(), diff --git a/crates/openshell-supervisor-network/src/token_grant.rs b/crates/openshell-supervisor-network/src/token_grant.rs index df2a25a559..8224d9b261 100644 --- a/crates/openshell-supervisor-network/src/token_grant.rs +++ b/crates/openshell-supervisor-network/src/token_grant.rs @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! `OAuth2` JWT client assertion token grant using SPIFFE JWT-SVID. +//! `OAuth2` token grants using SPIFFE JWT-SVIDs as assertions or subjects. //! //! When a provider profile includes a `token_grant` configuration, the //! supervisor obtains `OAuth2` access tokens on-demand by authenticating to the -//! token service using the sandbox's SPIFFE JWT-SVID as the client assertion. +//! token service using the sandbox's SPIFFE JWT-SVID as a client assertion or +//! token-exchange subject, according to the profile's identity configuration. //! //! ## Flow //! @@ -128,7 +129,7 @@ impl Default for ProviderIdentitySource { /// The cache, HTTP connection pool, gateway credentials, sandbox ID, and /// Workload API socket all belong to one sandbox instance, so a token /// acquired for one sandbox is never served to another. The gateway is used -/// only for the intermediate exchange of RFC 8693 token exchange grants. +/// only for intermediate exchanges with stored subject credentials. pub struct SpiffeTokenGrantResolver { cache: TokenCache, // Initialization failures stay bounded and typed; acquisition must not panic. @@ -164,12 +165,12 @@ impl SpiffeTokenGrantResolver { fetch_jwt_svid_from_socket(socket_path, audience).await } - /// Obtain an `OAuth2` access token for a provider using JWT client assertion grant. + /// Obtain an `OAuth2` access token using the configured grant and identity roles. /// /// This fetches the sandbox's SPIFFE JWT-SVID from the instance's Workload /// API socket, then exchanges it for an access token with a POST request to - /// the provider's token endpoint with the JWT client assertion grant flow - /// (RFC 7523). + /// the provider's token endpoint as an assertion (RFC 7523), subject (RFC 8693), + /// or both. Stored subjects use the gateway's intermediate exchange. /// /// Tokens are cached per provider name with TTL in this instance's cache. /// Subsequent calls return the cached token if it has not expired. @@ -190,6 +191,8 @@ impl SpiffeTokenGrantResolver { .map_err(|_| configuration_failure())?; let token = obtain_provider_token_with_grant( ObtainProviderTokenInput { + client_authentication: request.client_authentication, + subject_token: request.subject_token, cache: &self.cache, provider_name: request.provider_key, token_endpoint: request.token_endpoint, @@ -206,6 +209,13 @@ impl SpiffeTokenGrantResolver { let exchange_context = match grant_type { ProviderCredentialTokenGrantType::ClientCredentials | ProviderCredentialTokenGrantType::Unspecified => None, + ProviderCredentialTokenGrantType::TokenExchange + if request + .subject_token + .is_some_and(|subject| subject.source == "jwt_svid") => + { + None + } ProviderCredentialTokenGrantType::TokenExchange => { let (provider, credential_key) = parse_provider_credential_key(request.provider_key)?; @@ -223,7 +233,28 @@ impl SpiffeTokenGrantResolver { // For RFC 7523, the JWT assertion's aud claim identifies the issuer/realm let jwt_svid = self.fetch_jwt_svid(&jwt_audience).await?; + let authentication = oauth::ClientAuthentication::from_config( + request.client_authentication, + &jwt_svid, + request.client_assertion_type, + ); let response = match exchange_context { + None if grant_type == ProviderCredentialTokenGrantType::TokenExchange => { + perform_token_exchange( + http_client, + request.token_endpoint, + &TokenExchangeParams { + client_authentication: authentication, + subject_token: &jwt_svid, + subject_token_type: oauth::JWT_TOKEN_TYPE, + audience: request.audience, + scopes: request.scopes, + requested_token_type: request.requested_token_type, + }, + request.request_id, + ) + .await + } None => { // Perform OAuth2 JWT client assertion grant. The audience // parameter in the token request specifies the resource server. @@ -256,8 +287,7 @@ impl SpiffeTokenGrantResolver { http_client, request.token_endpoint, &TokenExchangeParams { - client_assertion: &jwt_svid, - client_assertion_type: request.client_assertion_type, + client_authentication: authentication, subject_token: &intermediate.access_token, subject_token_type: ACCESS_TOKEN_TYPE, audience: request.audience, @@ -323,6 +353,9 @@ impl TokenGrantResolver for GatewayTokenGrantResolver { } struct ObtainProviderTokenInput<'a> { + client_authentication: + Option<&'a openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication>, + subject_token: Option<&'a openshell_core::proto::ProviderCredentialTokenGrantSubjectToken>, cache: &'a TokenCache, provider_name: &'a str, token_endpoint: &'a str, @@ -345,6 +378,8 @@ where { let jwt_audience = effective_jwt_svid_audience(input.token_endpoint, input.jwt_svid_audience); let cache_key = token_cache_key(TokenCacheKeyInput { + client_authentication: input.client_authentication, + subject_token: input.subject_token, provider_name: input.provider_name, token_endpoint: input.token_endpoint, jwt_svid_audience: &jwt_audience, @@ -513,6 +548,9 @@ fn parse_provider_credential_key(key: &str) -> Result<(&str, &str), TokenGrantFa } struct TokenCacheKeyInput<'a> { + client_authentication: + Option<&'a openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication>, + subject_token: Option<&'a openshell_core::proto::ProviderCredentialTokenGrantSubjectToken>, provider_name: &'a str, token_endpoint: &'a str, jwt_svid_audience: &'a str, @@ -525,7 +563,7 @@ struct TokenCacheKeyInput<'a> { fn token_cache_key(input: TokenCacheKeyInput<'_>) -> String { format!( - "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", + "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:?}\t{:?}", input.provider_name, input.token_endpoint, input.jwt_svid_audience, @@ -533,7 +571,9 @@ fn token_cache_key(input: TokenCacheKeyInput<'_>) -> String { input.audience, input.scopes.join(" "), input.grant_type as i32, - input.requested_token_type + input.requested_token_type, + input.client_authentication, + input.subject_token ) } @@ -639,6 +679,8 @@ pub mod test_support { .map_err(|_| configuration_failure())?; obtain_provider_token_with_grant( ObtainProviderTokenInput { + client_authentication: request.client_authentication, + subject_token: request.subject_token, cache: &self.cache, provider_name: request.provider_key, token_endpoint: request.token_endpoint, @@ -652,6 +694,8 @@ pub mod test_support { }, |jwt_audience| async move { let cache_key = token_cache_key(TokenCacheKeyInput { + client_authentication: request.client_authentication, + subject_token: request.subject_token, provider_name: request.provider_key, token_endpoint: request.token_endpoint, jwt_svid_audience: &jwt_audience, @@ -911,6 +955,8 @@ mod tests { ) -> Result { obtain_provider_token_with_grant( ObtainProviderTokenInput { + client_authentication: None, + subject_token: None, cache: input.cache, provider_name: input.provider_name, token_endpoint: input.token_endpoint, @@ -948,6 +994,8 @@ mod tests { ) -> Result { obtain_provider_token_with_grant( ObtainProviderTokenInput { + client_authentication: None, + subject_token: None, cache, provider_name, token_endpoint, @@ -1036,6 +1084,44 @@ mod tests { assert_eq!(issuer, "https://oauth.example.com/token"); } + #[test] + fn cache_separates_client_authentication_and_subject_sources() { + use openshell_core::proto::{ + ProviderCredentialTokenGrantClientAuthentication, + ProviderCredentialTokenGrantSubjectToken, + }; + let none = ProviderCredentialTokenGrantClientAuthentication { + mechanism: "none".into(), + credential: None, + }; + let svid = ProviderCredentialTokenGrantSubjectToken { + source: "jwt_svid".into(), + ..Default::default() + }; + let stored = ProviderCredentialTokenGrantSubjectToken { + source: "provider_credential".into(), + credential: "user".into(), + ..Default::default() + }; + let key = |client_authentication, subject_token| { + token_cache_key(TokenCacheKeyInput { + client_authentication, + subject_token, + provider_name: "provider:access", + token_endpoint: "https://sts.googleapis.com/v1/token", + jwt_svid_audience: "google-provider", + client_assertion_type: DEFAULT_CLIENT_ASSERTION_TYPE, + audience: "google-provider", + scopes: &[], + grant_type: ProviderCredentialTokenGrantType::TokenExchange, + requested_token_type: ACCESS_TOKEN_TYPE, + }) + }; + let direct = key(Some(&none), Some(&svid)); + assert_ne!(direct, key(None, Some(&svid))); + assert_ne!(direct, key(Some(&none), Some(&stored))); + } + #[test] fn effective_jwt_svid_audience_prefers_explicit_override() { let audience = effective_jwt_svid_audience( @@ -1055,6 +1141,8 @@ mod tests { let alpha_scopes = ["alpha".to_string()]; let delta_scopes = ["delta".to_string()]; let base = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name, token_endpoint, jwt_svid_audience, @@ -1065,6 +1153,8 @@ mod tests { requested_token_type: ACCESS_TOKEN_TYPE, }); let different_audience = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name, token_endpoint, jwt_svid_audience, @@ -1075,6 +1165,8 @@ mod tests { requested_token_type: ACCESS_TOKEN_TYPE, }); let different_scopes = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name, token_endpoint, jwt_svid_audience, @@ -1085,6 +1177,8 @@ mod tests { requested_token_type: ACCESS_TOKEN_TYPE, }); let different_assertion_type = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name, token_endpoint, jwt_svid_audience, @@ -1107,6 +1201,8 @@ mod tests { let jwt_svid_audience = "https://auth.example.com/realms/openshell"; let scopes = ["alpha".to_string()]; let revision_one = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name: "api.example.test\t443\t/v1/**\trev:1\tprovider:access_token", token_endpoint, jwt_svid_audience, @@ -1117,6 +1213,8 @@ mod tests { requested_token_type: ACCESS_TOKEN_TYPE, }); let revision_two = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name: "api.example.test\t443\t/v1/**\trev:2\tprovider:access_token", token_endpoint, jwt_svid_audience, @@ -1216,6 +1314,8 @@ mod tests { assert_eq!(token, expected); } let identity_cache_key = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name: identity, token_endpoint: "https://auth.example.com/token", jwt_svid_audience: "https://auth.example.com", @@ -1355,6 +1455,8 @@ mod tests { let audience = "api://resource"; let cache_key = token_cache_key(TokenCacheKeyInput { + client_authentication: None, + subject_token: None, provider_name, token_endpoint, jwt_svid_audience, diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..84c7c36605 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -819,7 +819,7 @@ OpenShell supports two dynamic grant types: | Grant type | Behavior | |---|---| | `client_credentials` | The supervisor requests a SPIFFE JWT-SVID from the local Workload API and sends it directly to `token_endpoint` as the OAuth2 client assertion. This is the default when `grant_type` is omitted. | -| `token_exchange` | The supervisor first asks the gateway for an intermediate token. The request includes the supervisor JWT-SVID; the gateway verifies it, uses the SVID subject as the intermediate token audience, and exchanges the stored subject credential at the same `token_endpoint` using the gateway's own JWT-SVID as the client assertion. The supervisor then exchanges that intermediate token for the final upstream token using its own JWT-SVID as the client assertion. | +| `token_exchange` | With `subject_token.source: jwt_svid`, OpenShell exchanges the sandbox JWT-SVID directly. With `source: provider_credential`, the gateway verifies the supervisor's identity and exchanges the stored credential for an intermediate token addressed to that identity. The supervisor then exchanges the intermediate token for the final upstream token. Both exchanges use the same `token_endpoint` and configured client authentication; assertion authentication uses the gateway SVID for the intermediate exchange and the sandbox SVID for the final exchange. | Create provider instances for token-grant-only profiles with `--runtime-credentials`. This records an empty provider instance and makes the runtime-resolved credential source explicit: @@ -830,7 +830,7 @@ openshell provider create \ --runtime-credentials ``` -For `token_exchange` profiles, the provider also stores the user subject token referenced by `token_grant.subject_token.credential`. That credential is gateway-only: the sandbox does not receive it as environment material, static credential binding metadata, or workload placeholder ownership. Create or update that provider credential from the current gateway OIDC login with `--from-oidc-token`. This requires an active named gateway that was registered for OIDC. The CLI copies the current OIDC access token and its expiry into the provider. If the stored gateway access token is expired and a refresh token is available, the CLI refreshes it first. OpenShell does not store the OIDC refresh token in the provider. When the stored subject-token credential expires, the gateway rejects intermediate token exchange until the provider is updated with a fresh token. +For `token_exchange` profiles with `subject_token.source: provider_credential`, the provider also stores the user subject token referenced by `token_grant.subject_token.credential`. That credential is gateway-only: the sandbox does not receive it as environment material, static credential binding metadata, or workload placeholder ownership. Create or update that provider credential from the current gateway OIDC login with `--from-oidc-token`. This requires an active named gateway that was registered for OIDC. The CLI copies the current OIDC access token and its expiry into the provider. If the stored gateway access token is expired and a refresh token is available, the CLI refreshes it first. OpenShell does not store the OIDC refresh token in the provider. When the stored subject-token credential expires, the gateway rejects intermediate token exchange until the provider is updated with a fresh token. ```shell openshell provider create \ @@ -849,18 +849,58 @@ Token grant fields: | Field | Required | Behavior | |---|---|---| | `grant_type` | No | `client_credentials` or `token_exchange`. Defaults to `client_credentials` for backward compatibility. | -| `token_endpoint` | Yes | OAuth2 token endpoint that accepts a SPIFFE JWT-SVID client assertion. Use `https://` unless the endpoint is loopback or a Kubernetes service DNS name such as `token-issuer.default.svc.cluster.local`. | +| `token_endpoint` | Yes | OAuth2 token endpoint for the configured grant and authentication mechanism. Use `https://` unless the endpoint is loopback or a Kubernetes service DNS name such as `token-issuer.default.svc.cluster.local`. | | `audience` | No | Resource audience requested from the token service. For `token_exchange`, this is the final exchange audience; the gateway intermediate exchange always uses the verified supervisor SVID subject as its audience. | | `jwt_svid_audience` | No | Audience used when requesting the JWT-SVID. When omitted, OpenShell derives an issuer-style audience from Keycloak token endpoint paths or falls back to the full token endpoint URL. | +| `client_authentication` | No | Omission uses `mechanism: client_assertion` with `credential.source: jwt_svid`. An explicit `client_assertion` requires that credential source. `mechanism: none` is supported for token exchange and forbids `credential` and `client_assertion_type`. It changes authentication to the token endpoint only. | | `client_assertion_type` | No | OAuth2 `client_assertion_type` form value. Defaults to RFC 7523 `urn:ietf:params:oauth:client-assertion-type:jwt-bearer`. Set `urn:ietf:params:oauth:client-assertion-type:jwt-spiffe` when the token issuer expects the SPIFFE assertion type. | | `scopes` | No | OAuth2 scopes sent as a space-separated `scope` parameter. | | `cache_ttl` | No | Protobuf-duration cache override, such as `300s`. Omission uses the token response expiry; `0s` disables caching. Shared supervisor grants require a positive override to be at least `1s` and cap it at the issuer and identity expiries. The legacy `cache_ttl_seconds` input remains accepted. | | `requested_token_type` | No | RFC 8693 `requested_token_type` sent during token exchange. Defaults to `urn:ietf:params:oauth:token-type:access_token`. | -| `subject_token` | Required for `token_exchange` | Subject-token source used for the gateway-brokered intermediate exchange. Phase one supports `source: provider_credential`, where `credential` names another credential declared in the same profile. That referenced credential is broker-only and cannot declare workload injection metadata such as env vars, static placement, refresh, or token grant metadata. | -| `subject_token.subject_token_type` | No | RFC 8693 `subject_token_type` for the stored subject token. Defaults to `urn:ietf:params:oauth:token-type:access_token`. | +| `subject_token` | Required for `token_exchange` | `source: jwt_svid` exchanges the sandbox identity directly and forbids `credential`. `source: provider_credential` uses the gateway-brokered intermediate exchange, where `credential` names another credential declared in the same profile. That referenced credential is broker-only and cannot declare workload injection metadata such as env vars, static placement, refresh, or token grant metadata. | +| `subject_token.subject_token_type` | No | RFC 8693 subject type. For `jwt_svid`, defaults to and must equal `urn:ietf:params:oauth:token-type:jwt`. For stored credentials, defaults to `urn:ietf:params:oauth:token-type:access_token`. | | `audience_overrides` | No | Endpoint-specific final-exchange `audience` and `scopes` overrides selected by host, port, and path. These overrides do not affect the gateway intermediate exchange. | -Dedicated supervisors use a local SPIFFE Workload API socket for the exchanges above. Shared supervisors use the gateway's [SPIFFE Broker API integration](/how-it-works/gateways/configuration#sandbox-identity-through-the-spiffe-broker-api): the gateway obtains the stable sandbox JWT-SVID and performs both exchanges, then returns only the final access token. The intermediate audience is the stable sandbox SPIFFE ID. Only the gateway mounts the Workload API socket, including for its own JWT-SVID in `token_exchange`. +Dedicated supervisors use a local SPIFFE Workload API socket for the exchanges above. Shared supervisors use the gateway's [SPIFFE Broker API integration](/how-it-works/gateways/configuration#sandbox-identity-through-the-spiffe-broker-api): the gateway obtains the stable sandbox JWT-SVID and performs the configured exchange flow, then returns only the final access token. The intermediate audience is the stable sandbox SPIFFE ID. Only the gateway mounts the Workload API socket, including for its own JWT-SVID when exchanging a stored subject credential. + +When both client authentication and the subject use `jwt_svid`, the direct exchange +uses the same sandbox SVID for both, with the configured `jwt_svid_audience`. + +For Google Workload Identity Federation, replace the static credentials in your +`google-cloud` profile with a dynamic credential like this: + +```yaml +credentials: + - name: federated_token + env_vars: [GCP_ADC_ACCESS_TOKEN] + auth_style: bearer + header_name: authorization + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + audience: //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL/providers/PROVIDER + jwt_svid_audience: https://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL/providers/PROVIDER + scopes: [https://www.googleapis.com/auth/cloud-platform] + client_authentication: + mechanism: none + subject_token: + source: jwt_svid +``` + +Configure Google's federation provider to trust your SPIRE issuer and signing +keys, accept the configured `jwt_svid_audience`, and map the SVID subject to +`google.subject`. Grant that federated principal access to the required resources. +The token request's `audience` identifies the Google federation provider; it is +separate from the SVID's audience. See Google's +[Workload Identity Federation configuration](https://docs.cloud.google.com/iam/docs/workload-identity-federation-with-other-providers). + +Keep the profile ID `google-cloud` to enable metadata discovery, declare the +Google API endpoints and workload binaries that need access, and create the +provider with `--runtime-credentials`. SDKs using ADC receive a placeholder from +the metadata emulator. OpenShell acquires and caches the Google token when an +allowed API request needs it; neither the SVID nor the Google token enters the +workload. Metadata placeholder expiry is independent of the cached Google token's +expiry. This flow uses direct federation, without service-account impersonation. Token grants apply to HTTP traffic that the proxy can inspect. Token-grant profiles reject endpoints with `protocol: sql` or `tls: skip`, including when `allow_uninspected_credentials` is enabled, because those modes cannot inject the required HTTP credential. The token service must return a token value that is safe for HTTP header placement; malformed values are rejected before caching or header injection. diff --git a/e2e/rust/tests/provider_token_exchange.rs b/e2e/rust/tests/provider_token_exchange.rs index 9105be98bc..01126f4da8 100644 --- a/e2e/rust/tests/provider_token_exchange.rs +++ b/e2e/rust/tests/provider_token_exchange.rs @@ -489,6 +489,7 @@ async fn start_gateway_token_endpoint( // signature and audience. No new production grant type or sandbox-visible // credential is needed to exercise custom-header injection. async fn start_identity_token_endpoint( + jwt_subject: bool, port: u16, observations: Arc, ) -> FixtureHandle { @@ -508,15 +509,32 @@ async fn start_identity_token_endpoint( let form = token_form(&request); let field = |name: &str| form.get(name).map_or("", String::as_str); let mut access_token = None; + let (identity, valid_authentication) = if jwt_subject { + ( + field("subject_token"), + field("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange" + && field("subject_token_type") + == "urn:ietf:params:oauth:token-type:jwt" + && field("requested_token_type") == TOKEN_TYPE_ACCESS_TOKEN + && !form.contains_key("client_assertion") + && !form.contains_key("client_assertion_type") + && !request.to_ascii_lowercase().contains("\r\nauthorization:"), + ) + } else { + ( + field("client_assertion"), + field("grant_type") == "client_credentials" + && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE, + ) + }; for (index, instance) in ["a", "b"].into_iter().enumerate() { let valid = request.starts_with("POST /identity-token ") - && field("grant_type") == "client_credentials" - && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE + && valid_authentication && field("scope") == "identity.read" - && verifies_jwt_svid(field("client_assertion"), instance); + && verifies_jwt_svid(identity, instance); if valid && field("audience") == format!("{IDENTITY_AUDIENCE}-{instance}") { observations.identity_issued[index].fetch_add(1, Ordering::SeqCst); - access_token = Some(field("client_assertion")); + access_token = Some(identity); } else if valid && field("audience") == format!("denied-identity-{instance}") { observations.identity_denied.fetch_add(1, Ordering::SeqCst); } @@ -528,7 +546,11 @@ async fn start_identity_token_endpoint( FixtureHandle { task } } -async fn start_protected_target(port: u16, observations: Arc) -> FixtureHandle { +async fn start_protected_target( + jwt_subject: bool, + port: u16, + observations: Arc, +) -> FixtureHandle { let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port))) .await .expect("bind protected target"); @@ -561,14 +583,33 @@ async fn start_protected_target(port: u16, observations: Arc) .map(|(_, value)| value.trim()) .collect::>() }; - let bearer = header_values("authorization"); - let identity = header_values("x-workload-jwt"); + let bearer = header_values(if jwt_subject { + "x-service-token" + } else { + "authorization" + }); + let identity = header_values(if jwt_subject { + "authorization" + } else { + "x-workload-jwt" + }); let ok = ["a", "b"].into_iter().any(|instance| { request.starts_with(&format!("GET /resource/{instance} ")) && bearer.len() == 1 - && bearer[0] == format!("Bearer {FINAL_ACCESS_TOKEN}-{instance}") + && bearer[0] + == format!( + "{}{FINAL_ACCESS_TOKEN}-{instance}", + if jwt_subject { "" } else { "Bearer " } + ) && identity.len() == 1 - && verifies_jwt_svid(identity[0], instance) + && verifies_jwt_svid( + if jwt_subject { + identity[0].strip_prefix("Bearer ").unwrap_or("") + } else { + identity[0] + }, + instance, + ) }); let (status, body) = if ok { ("HTTP/1.1 200 OK", "independent-grants-ok") @@ -615,6 +656,7 @@ async fn run_cli_ignore_error(args: &[&str]) { } fn write_profile( + jwt_subject: bool, profile_type: &str, token_port: u16, identity_port: u16, @@ -688,6 +730,15 @@ binaries: - /** " ); + let profile = if jwt_subject { + profile.replace("grant_type: client_credentials", "grant_type: token_exchange") + .replace("auth_style: bearer\n header_name: Authorization", "auth_style: header\n header_name: X-Service-Token") + .replace("auth_style: header\n header_name: X-Workload-Jwt", "env_vars: [GCP_ADC_ACCESS_TOKEN]\n auth_style: bearer\n header_name: Authorization") + .replace(&format!("client_assertion_type: {IDENTITY_ASSERTION_TYPE}"), + "client_authentication:\n mechanism: none\n subject_token:\n source: jwt_svid") + } else { + profile + }; file.write_all(profile.as_bytes()) .expect("write provider profile"); file.flush().expect("flush provider profile"); @@ -855,15 +906,24 @@ except urllib.error.HTTPError as error: } async fn create_provider_instance( + jwt_subject: bool, token_port: u16, identity_port: u16, target_port: u16, instance: &str, ) -> String { - let name = format!("podman-grants-{instance}-{}", std::process::id()); + let flow = if jwt_subject { "direct" } else { "stored" }; + let name = format!("podman-grants-{flow}-{instance}-{}", std::process::id()); run_cli_ignore_error(&["provider", "delete", &name, "--yes"]).await; run_cli_ignore_error(&["profile", "delete", &name, "--yes"]).await; - let profile = write_profile(&name, token_port, identity_port, target_port, instance); + let profile = write_profile( + jwt_subject, + &name, + token_port, + identity_port, + target_port, + instance, + ); let profile_path = profile .path() .to_str() @@ -888,6 +948,15 @@ async fn create_provider_instance( #[tokio::test] async fn podman_provider_token_exchange_injects_independent_grants_across_sandboxes() { + independent_grants_across_sandboxes(false).await; +} + +#[tokio::test] +async fn podman_jwt_svid_subject_without_client_authentication() { + independent_grants_across_sandboxes(true).await; +} + +async fn independent_grants_across_sandboxes(jwt_subject: bool) { let _fixture_guard = SPIFFE_FIXTURE_LOCK.lock().await; let gateway_socket = PathBuf::from( std::env::var("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET") @@ -909,13 +978,21 @@ async fn podman_provider_token_exchange_injects_independent_grants_across_sandbo let _provider_spiffe = start_spiffe_workload_api(&provider_socket, &supervisor_subject).await; let _gateway_token = start_gateway_token_endpoint(token_port, Arc::clone(&observations)).await; let _identity_token = - start_identity_token_endpoint(identity_port, Arc::clone(&observations)).await; - let _target = start_protected_target(target_port, Arc::clone(&observations)).await; + start_identity_token_endpoint(jwt_subject, identity_port, Arc::clone(&observations)).await; + let _target = start_protected_target(jwt_subject, target_port, Arc::clone(&observations)).await; let mut provider_names = Vec::new(); for instance in ["a", "b"] { - provider_names - .push(create_provider_instance(token_port, identity_port, target_port, instance).await); + provider_names.push( + create_provider_instance( + jwt_subject, + token_port, + identity_port, + target_port, + instance, + ) + .await, + ); } let script = sandbox_script(); @@ -946,6 +1023,50 @@ async fn podman_provider_token_exchange_injects_independent_grants_across_sandbo sandbox_exec_http(&sandbox_b.name, target_port, "/resource/b", false), ); let after_cache = observations.issued(); + if jwt_subject { + // The SDK is installed in the standard E2E workload. Point ADC at the + // reserved metadata emulator; no SDK code or credential files are changed. + let script = format!( + r#"import os +os.environ["GCE_METADATA_HOST"] = "127.0.0.1:8174" +os.environ["GCE_METADATA_IP"] = "127.0.0.1:8174" +os.environ["GOOGLE_CLOUD_PROJECT"] = "e2e-project" +os.environ.pop("GOOGLE_APPLICATION_CREDENTIALS", None) +import google.auth +from google.auth.transport.requests import AuthorizedSession, Request +credentials, project = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"]) +credentials.refresh(Request()) +assert credentials.token.startswith("openshell:resolve:"), "ADC received a real credential" +response = AuthorizedSession(credentials).get("http://host.openshell.internal:{target_port}/resource/a", timeout=10) +assert response.status_code == 200, "ADC request failed" +assert response.text == "independent-grants-ok" +assert credentials.token.startswith("openshell:resolve:"), "ADC credential changed" +print("adc-placeholder-ok") +"# + ); + let output = openshell_cmd() + .args([ + "sandbox", + "exec", + &sandbox_a.name, + "--", + "python3", + "-c", + &script, + ]) + .output() + .await + .expect("ADC probe"); + assert!( + output.status.success(), + "ADC probe failed; exit={:?}", + output.status.code() + ); + assert_eq!( + String::from_utf8_lossy(&output.stdout).trim(), + "adc-placeholder-ok" + ); + } let target_requests = observations.target_requests.load(Ordering::SeqCst); // An audience override forces acquisition of only the failing credential; // the other credential remains cached from the successful request. diff --git a/proto/openshell.proto b/proto/openshell.proto index 56a58e17f0..8587309980 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -2508,18 +2508,30 @@ enum ProviderCredentialTokenGrantType { } message ProviderCredentialTokenGrantSubjectToken { - // Source for the token exchange subject token. Phase one supports - // "provider_credential". + // Source for the token exchange subject: "provider_credential" or "jwt_svid". string source = 1; - // Provider credential key that stores the subject token. + // Provider credential key. Required only for provider_credential subjects. string credential = 2; // OAuth2 subject_token_type. If omitted, OpenShell uses + // urn:ietf:params:oauth:token-type:jwt for jwt_svid subjects, otherwise // urn:ietf:params:oauth:token-type:access_token. string subject_token_type = 3; } +message ProviderCredentialTokenGrantClientCredential { + // Credential source. Currently supports "jwt_svid". + string source = 1; +} + +message ProviderCredentialTokenGrantClientAuthentication { + // External token endpoint authentication: "client_assertion" or "none". + string mechanism = 1; + // Required for client_assertion; forbidden for none. + ProviderCredentialTokenGrantClientCredential credential = 2; +} + message ProviderCredentialTokenGrant { reserved 4; reserved "cache_ttl_seconds"; @@ -2556,6 +2568,10 @@ message ProviderCredentialTokenGrant { // OAuth2 requested_token_type. If omitted for token_exchange, OpenShell uses // urn:ietf:params:oauth:token-type:access_token. string requested_token_type = 10; + + // Omission preserves client_assertion authentication using a JWT-SVID. + // This controls the external token endpoint, not OpenShell RPC authentication. + ProviderCredentialTokenGrantClientAuthentication client_authentication = 11; } // Provider credential declaration. diff --git a/skills/openshell-cli/SKILL.md b/skills/openshell-cli/SKILL.md index b4d72fbe9f..ab7f084707 100644 --- a/skills/openshell-cli/SKILL.md +++ b/skills/openshell-cli/SKILL.md @@ -233,6 +233,8 @@ openshell provider delete my-github For an external updater whose workload must retain its original environment reference, use a credential profile with `stable_placeholder: true` and a gateway and supervisor that support that mode. The CLI checks gateway support before importing or updating the opt-in. The default remains `false`, preserving existing revision-scoped behavior and ordinary legacy gateway operation. Preserve the supervisor-issued value; never manufacture a placeholder. After the supervisor installs a value-only update, the retained reference resolves the current credential only at its effective host, port, and path binding. Replacement, expiry, changed binding, or an activated detach prevents old authority from resolving. Remove the opt-in and activate that change before downgrading the gateway. See the provider profiles documentation for the lifecycle contract and its separation from gateway-managed refresh and `token_grant`. +For Google federation using the sandbox's SPIFFE identity, use a `google-cloud` profile with a `token_exchange` grant, `subject_token.source: jwt_svid`, and `client_authentication.mechanism: none`, then create the provider with `--runtime-credentials`. Configure `jwt_svid_audience` to match Google's allowed audiences, separately from the exchange `audience`. Declare the required API endpoints and binaries. ADC receives a metadata placeholder; OpenShell keeps the real token outside the workload. Consult the published provider profiles documentation for the complete configuration. Existing profiles that omit `client_authentication` retain JWT-SVID client assertions and the top-level `client_assertion_type`. + ### Configure credential refresh Use refresh commands only when the provider profile and gateway support refreshable credentials: