diff --git a/crates/openshell-core/src/google_cloud.rs b/crates/openshell-core/src/google_cloud.rs index efc15a6527..50cbe41c04 100644 --- a/crates/openshell-core/src/google_cloud.rs +++ b/crates/openshell-core/src/google_cloud.rs @@ -52,6 +52,21 @@ pub const GCP_SERVICE_ACCOUNT_EMAIL_CONFIG_KEY: &str = "service_account_email"; /// credential precedence. pub const TOKEN_ENV_KEYS: &[&str] = &["GCP_SA_ACCESS_TOKEN", "GCP_ADC_ACCESS_TOKEN"]; +/// Reserved key of the placeholder served for `gce_metadata_token` credentials. +/// +/// No credential is stored under this key, so the placeholder never resolves: +/// a token grant replaces it on the credential's endpoints, and anywhere else +/// placeholder resolution refuses the request. +pub const TOKEN_GRANT_PLACEHOLDER_ENV_KEY: &str = "OPENSHELL_GCE_METADATA_TOKEN_GRANT"; + +/// `expires_in` reported for the token grant placeholder. +/// +/// Equal to the longest lifetime of a cached grant token (3600 s cap minus the +/// 30 s refresh skew), so an SDK never holds the placeholder longer than the +/// supervisor would hold the token it stands for. The supervisor obtains the +/// real token independently on each request, so the value only paces refresh. +pub const TOKEN_GRANT_PLACEHOLDER_EXPIRES_IN_SECONDS: i64 = 3570; + // ── Vertex-specific env vars ──────────────────────────────────────────────── /// Env var injected to signal Vertex AI usage to Goose. diff --git a/crates/openshell-core/src/oauth.rs b/crates/openshell-core/src/oauth.rs index 8e31239d97..38c643dc62 100644 --- a/crates/openshell-core/src/oauth.rs +++ b/crates/openshell-core/src/oauth.rs @@ -22,6 +22,8 @@ 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"; +/// RFC 8693 token type for a JWT, such as a SPIFFE JWT-SVID subject token. +pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt"; 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; @@ -207,7 +209,9 @@ pub async fn post_oauth_token_grant( /// 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, + /// `None` sends no client authentication: neither `client_assertion` nor + /// `client_assertion_type` is included in the form. + pub client_assertion: Option<&'a str>, pub client_assertion_type: &'a str, /// Secret subject credential to exchange for a resource token. pub subject_token: &'a str, @@ -221,25 +225,29 @@ pub struct TokenExchangeParams<'a> { /// /// Assembles the standard token-exchange form fields, applies defaults for /// `client_assertion_type`, `subject_token_type`, and `requested_token_type`, -/// and conditionally includes `audience` and `scope`. A `request_id` is sent -/// as the `x-openshell-request-id` header. +/// and conditionally includes the client assertion, `audience` and `scope`. +/// A `request_id` is sent as the `x-openshell-request-id` header. pub async fn post_oauth_token_exchange( client: &TokenGrantClient, token_endpoint: &str, 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![ - ("grant_type", TOKEN_EXCHANGE_GRANT_TYPE), - ("client_assertion_type", client_assertion_type), - ("client_assertion", params.client_assertion), + let mut form_params = vec![("grant_type", TOKEN_EXCHANGE_GRANT_TYPE)]; + if let Some(client_assertion) = params.client_assertion { + form_params.push(( + "client_assertion_type", + effective_client_assertion_type(params.client_assertion_type), + )); + form_params.push(("client_assertion", client_assertion)); + } + form_params.extend([ ("subject_token", params.subject_token), ("subject_token_type", subject_token_type), ("requested_token_type", requested_token_type), - ]; + ]); post_oauth_token_request( client, token_endpoint, @@ -267,6 +275,75 @@ pub fn effective_token_type(token_type: &str) -> &str { } } +/// Subject token source resolved from a stored provider credential. +pub const SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL: &str = "provider_credential"; +/// Subject token source that is the sandbox's own JWT-SVID. +pub const SUBJECT_TOKEN_SOURCE_JWT_SVID: &str = "jwt_svid"; + +/// How a token grant uses the sandbox JWT-SVID, decided before any I/O. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TokenGrantFlow { + /// RFC 7523 client credentials with the SVID as client assertion. + ClientCredentials, + /// RFC 8693 exchange of a stored provider credential, with the SVID as + /// client assertion. + ProviderCredentialSubjectExchange, + /// RFC 8693 exchange of the SVID itself. + JwtSvidSubjectExchange { client_assertion: bool }, +} + +impl TokenGrantFlow { + /// Resolve the flow, failing closed on unknown or inconsistent settings. + /// + /// An empty subject source keeps the provider credential exchange, which + /// predates the field. + pub fn resolve( + grant_type: crate::proto::ProviderCredentialTokenGrantType, + subject_token_source: &str, + client_authentication: i32, + ) -> Result { + use crate::proto::{ + ProviderCredentialTokenGrantClientAuthentication as ClientAuthentication, + ProviderCredentialTokenGrantType as GrantType, + }; + let configuration = || { + TokenGrantFailure::new( + TokenGrantFailureKind::Configuration, + TokenGrantStage::Configuration, + ) + }; + let client_assertion = match ClientAuthentication::try_from(client_authentication) + .map_err(|_| configuration())? + { + ClientAuthentication::Unspecified | ClientAuthentication::ClientAssertion => true, + ClientAuthentication::None => false, + }; + match (grant_type, subject_token_source.trim()) { + (GrantType::ClientCredentials | GrantType::Unspecified, _) if client_assertion => { + Ok(Self::ClientCredentials) + } + (GrantType::TokenExchange, "" | SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL) + if client_assertion => + { + Ok(Self::ProviderCredentialSubjectExchange) + } + (GrantType::TokenExchange, SUBJECT_TOKEN_SOURCE_JWT_SVID) => { + Ok(Self::JwtSvidSubjectExchange { client_assertion }) + } + _ => Err(configuration()), + } + } +} + +/// Subject token type for a JWT-SVID subject; defaults to [`JWT_TOKEN_TYPE`]. +pub fn effective_jwt_svid_subject_token_type(subject_token_type: &str) -> &str { + if subject_token_type.trim().is_empty() { + JWT_TOKEN_TYPE + } else { + subject_token_type + } +} + /// Cache lifetime for a granted access token. /// /// A configured override is used exactly, including zero to disable caching. @@ -885,7 +962,7 @@ mod tests { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", + client_assertion: Some("jwt-svid-token"), client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe", subject_token: "subject-access-token", subject_token_type: ACCESS_TOKEN_TYPE, @@ -942,6 +1019,56 @@ mod tests { ); } + #[tokio::test] + async fn token_exchange_without_client_authentication_omits_client_assertion() { + let (endpoint, request) = token_endpoint_once( + "200 OK", + r#"{"access_token":"federated-token","token_type":"Bearer","expires_in":3599}"#, + ) + .await; + let scopes = vec!["https://www.googleapis.com/auth/cloud-platform".to_string()]; + let audience = "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/p/providers/spire"; + + let response = post_oauth_token_exchange( + &test_client(), + &endpoint, + &TokenExchangeParams { + client_assertion: None, + // Ignored without a client assertion. + client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + subject_token: "header.svid.signature", + subject_token_type: JWT_TOKEN_TYPE, + audience, + scopes: &scopes, + requested_token_type: ACCESS_TOKEN_TYPE, + }, + None, + ) + .await + .expect("token exchange should succeed"); + let request = request.await.expect("endpoint task"); + + assert_eq!(response.access_token, "federated-token"); + assert!(!request.form.contains_key("client_assertion")); + assert!(!request.form.contains_key("client_assertion_type")); + let expected = HashMap::from([ + ("grant_type", TOKEN_EXCHANGE_GRANT_TYPE), + ("audience", audience), + ("scope", "https://www.googleapis.com/auth/cloud-platform"), + ("requested_token_type", ACCESS_TOKEN_TYPE), + ("subject_token_type", JWT_TOKEN_TYPE), + ("subject_token", "header.svid.signature"), + ]); + assert_eq!( + request + .form + .iter() + .map(|(name, value)| (name.as_str(), value.as_str())) + .collect::>(), + expected + ); + } + #[tokio::test] async fn token_exchange_applies_defaults_for_empty_type_fields() { let (endpoint, request) = @@ -952,7 +1079,7 @@ mod tests { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", + client_assertion: Some("jwt-svid-token"), client_assertion_type: "", subject_token: "subject-token", subject_token_type: "", diff --git a/crates/openshell-core/src/provider_credentials.rs b/crates/openshell-core/src/provider_credentials.rs index 2aa1efdbf7..d6754af9d1 100644 --- a/crates/openshell-core/src/provider_credentials.rs +++ b/crates/openshell-core/src/provider_credentials.rs @@ -119,6 +119,15 @@ fn split_static_credential_metadata( (metadata, grants) } +/// Whether a token-grant credential opts in to the metadata emulator placeholder. +fn has_gce_metadata_token_grant( + credentials: &HashMap, +) -> bool { + credentials + .values() + .any(|credential| credential.gce_metadata_token && credential.token_grant.is_some()) +} + impl ProviderCredentialState { pub fn from_environment( revision: u64, @@ -592,6 +601,15 @@ impl ProviderCredentialState { && inner .non_secret_environment_keys .contains("GCE_METADATA_HOST"); + // A gce_metadata_token credential has no gateway-projected config, so + // the supervisor points SDKs at its metadata emulator itself. A key the + // provider already sets, or one suppressed after an emulator failure, + // is left alone. + let has_grant_metadata = !has_gcp_metadata + && !env.contains_key("GCE_METADATA_HOST") + && !inner.suppressed_keys.contains("GCE_METADATA_HOST") + && has_gce_metadata_token_grant(&inner.current.dynamic_credentials); + let has_gcp_metadata = has_gcp_metadata || has_grant_metadata; if !has_gcp_metadata && inner.non_secret_environment_keys.is_empty() { return (inner.current.revision, env); } @@ -700,7 +718,9 @@ 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 + /// refresh. Without a stored token, a `gce_metadata_token` token-grant + /// credential yields the reserved grant placeholder, which never resolves + /// to a value. Returns `None` if no GCP token is configured or all are /// expired. The `expires_in` defaults to 3600 when expiry is unknown. pub fn gcp_token_response(&self) -> Option<(String, i64)> { const DEFAULT_EXPIRES_IN: i64 = 3600; @@ -708,31 +728,47 @@ impl ProviderCredentialState { .inner .read() .expect("provider credential state poisoned"); - let resolver = inner.current_resolver.as_ref()?; - for key in crate::google_cloud::TOKEN_ENV_KEYS { - let Some(placeholder) = inner.current.child_env.get(*key).cloned() else { - continue; - }; - if resolver.resolve_placeholder(&placeholder).is_none() { - continue; - } - let expires_in = resolver.expires_at_ms_for_placeholder(&placeholder).map_or( - DEFAULT_EXPIRES_IN, - |expires_at_ms| { - if expires_at_ms <= 0 { - DEFAULT_EXPIRES_IN - } else { - let now = crate::time::now_ms(); - expires_at_ms.saturating_sub(now) / 1000 - } - }, - ); - if expires_in <= 0 { - continue; + if let Some(resolver) = inner.current_resolver.as_ref() { + for key in crate::google_cloud::TOKEN_ENV_KEYS { + let Some(placeholder) = inner.current.child_env.get(*key).cloned() else { + continue; + }; + if resolver.resolve_placeholder(&placeholder).is_none() { + continue; + } + let expires_in = resolver.expires_at_ms_for_placeholder(&placeholder).map_or( + DEFAULT_EXPIRES_IN, + |expires_at_ms| { + if expires_at_ms <= 0 { + DEFAULT_EXPIRES_IN + } else { + let now = crate::time::now_ms(); + expires_at_ms.saturating_sub(now) / 1000 + } + }, + ); + if expires_in <= 0 { + continue; + } + return Some((placeholder, expires_in)); } - return Some((placeholder, expires_in)); } - None + if !has_gce_metadata_token_grant(&inner.current.dynamic_credentials) { + return None; + } + let placeholder = crate::secrets::placeholder_for_env_key( + crate::google_cloud::TOKEN_GRANT_PLACEHOLDER_ENV_KEY, + ); + // The placeholder must be worthless outside the grant: refuse to serve + // it if any installed value could resolve it. + let resolvable = [&inner.current_resolver, &inner.combined_resolver] + .into_iter() + .flatten() + .any(|resolver| resolver.resolve_placeholder(&placeholder).is_some()); + (!resolvable).then_some(( + placeholder, + crate::google_cloud::TOKEN_GRANT_PLACEHOLDER_EXPIRES_IN_SECONDS, + )) } pub fn install_environment( @@ -3555,6 +3591,128 @@ mod tests { assert!(state.gcp_token_response().is_none()); } + fn gce_metadata_grant( + opt_in: bool, + ) -> HashMap { + HashMap::from([( + "storage.googleapis.com:443:/**:owner:google:wif_token".to_string(), + crate::proto::ProviderProfileCredential { + name: "wif_token".to_string(), + auth_style: "bearer".to_string(), + gce_metadata_token: opt_in, + token_grant: Some(crate::proto::ProviderCredentialTokenGrant { + token_endpoint: "https://sts.googleapis.com/v1/token".to_string(), + ..Default::default() + }), + ..Default::default() + }, + )]) + } + + #[test] + fn gcp_token_response_serves_unresolvable_grant_placeholder() { + let state = ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + gce_metadata_grant(true), + ); + let (placeholder, expires_in) = state + .gcp_token_response() + .expect("grant placeholder should be served"); + assert_eq!( + placeholder, + crate::secrets::placeholder_for_env_key(google_cloud::TOKEN_GRANT_PLACEHOLDER_ENV_KEY) + ); + assert_eq!( + expires_in, + google_cloud::TOKEN_GRANT_PLACEHOLDER_EXPIRES_IN_SECONDS + ); + assert!( + state + .resolver() + .is_none_or(|resolver| resolver.resolve_placeholder(&placeholder).is_none()), + "the grant placeholder must never resolve to a value" + ); + + // Without the opt-in a grant-only installation serves no token. + let state = ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + gce_metadata_grant(false), + ); + assert!(state.gcp_token_response().is_none()); + } + + #[test] + fn gcp_token_response_prefers_stored_token_over_grant_placeholder() { + let state = ProviderCredentialState::from_environment( + 1, + HashMap::from([("GCP_ADC_ACCESS_TOKEN".to_string(), "adc-tok".to_string())]), + HashMap::new(), + gce_metadata_grant(true), + ); + let (placeholder, _) = state.gcp_token_response().unwrap(); + assert_eq!(placeholder, "openshell:resolve:env:v1_GCP_ADC_ACCESS_TOKEN"); + } + + #[test] + fn gcp_token_response_refuses_grant_placeholder_that_resolves() { + let state = ProviderCredentialState::from_environment( + 0, + HashMap::from([( + google_cloud::TOKEN_GRANT_PLACEHOLDER_ENV_KEY.to_string(), + "secret".to_string(), + )]), + HashMap::new(), + gce_metadata_grant(true), + ); + assert!(state.gcp_token_response().is_none()); + } + + #[test] + fn child_env_points_sdks_at_metadata_emulator_for_gce_metadata_grant() { + let state = ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + gce_metadata_grant(true), + ); + let env = state.child_env_with_gcp_resolved(); + for key in ["GCE_METADATA_HOST", "GCE_METADATA_IP"] { + assert_eq!( + env.get(key).map(String::as_str), + Some(google_cloud::METADATA_LOOPBACK_ADDR), + "{key}" + ); + } + assert_eq!( + env.get("METADATA_SERVER_DETECTION").map(String::as_str), + Some("assume-present") + ); + + // Suppression after an emulator failure wins over the opt-in. + state.remove_env_key("GCE_METADATA_HOST"); + assert!( + !state + .child_env_with_gcp_resolved() + .contains_key("GCE_METADATA_HOST") + ); + + let state = ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + gce_metadata_grant(false), + ); + assert!( + !state + .child_env_with_gcp_resolved() + .contains_key("GCE_METADATA_HOST") + ); + } + #[test] fn gcp_token_response_defaults_expires_in_to_3600() { let state = ProviderCredentialState::from_environment( diff --git a/crates/openshell-core/tests/oauth_error_logging.rs b/crates/openshell-core/tests/oauth_error_logging.rs index a8f5cd4951..b7ef1affd6 100644 --- a/crates/openshell-core/tests/oauth_error_logging.rs +++ b/crates/openshell-core/tests/oauth_error_logging.rs @@ -92,7 +92,7 @@ async fn rejected_grant_log_omits_token_service_error_text() { &client, &endpoint, &TokenExchangeParams { - client_assertion: "jwt-svid-token", + client_assertion: Some("jwt-svid-token"), client_assertion_type: "", subject_token: CANARY, subject_token_type: "", diff --git a/crates/openshell-providers/src/discovery.rs b/crates/openshell-providers/src/discovery.rs index 7a4fcdfd69..90bbd2cf69 100644 --- a/crates/openshell-providers/src/discovery.rs +++ b/crates/openshell-providers/src/discovery.rs @@ -112,6 +112,7 @@ mod tests { refresh: None, path_template: String::new(), token_grant: None, + gce_metadata_token: false, }, CredentialProfile { name: "secondary".to_string(), @@ -125,6 +126,7 @@ mod tests { refresh: None, path_template: String::new(), token_grant: None, + gce_metadata_token: false, }, ], endpoints: Vec::new(), diff --git a/crates/openshell-providers/src/profiles.rs b/crates/openshell-providers/src/profiles.rs index b5aac1a5ec..405dd15d2b 100644 --- a/crates/openshell-providers/src/profiles.rs +++ b/crates/openshell-providers/src/profiles.rs @@ -11,9 +11,10 @@ use openshell_core::proto::{ GraphqlOperation, L7Allow, L7DenyRule, L7QueryMatcher, L7Rule, McpOptions, NetworkBinary, NetworkEndpoint, NetworkPolicyRule, ProviderCredentialRefresh, ProviderCredentialRefreshMaterial, ProviderCredentialRefreshOutput, - ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrantSubjectToken, - ProviderCredentialTokenGrantType, ProviderProfile, ProviderProfileCategory, - ProviderProfileCredential, ProviderProfileDiscovery, ProviderProfileFile, + ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrantClientAuthentication, + ProviderCredentialTokenGrantSubjectToken, ProviderCredentialTokenGrantType, ProviderProfile, + ProviderProfileCategory, ProviderProfileCredential, ProviderProfileDiscovery, + ProviderProfileFile, }; use openshell_core::secrets::uses_reserved_revision_namespace; use openshell_policy::{ @@ -27,6 +28,10 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::net::IpAddr; const PATH_TEMPLATE_CREDENTIAL_PLACEHOLDER: &str = "{credential}"; +/// Token exchange subject token stored as a provider credential and exchanged by the gateway. +pub const SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL: &str = "provider_credential"; +/// Token exchange subject token that is the sandbox's own SPIFFE JWT-SVID. +pub const SUBJECT_TOKEN_SOURCE_JWT_SVID: &str = "jwt_svid"; const MCP_VERSION_REMEDIATION: &str = "omit mcp.versions to use the pinned default revision; use an exact supported revision; or omit protocol and mcp for deliberate uninspected L4 passthrough only when that weaker boundary is acceptable"; #[derive(Debug, thiserror::Error)] @@ -109,6 +114,10 @@ pub struct CredentialProfile { pub path_template: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub token_grant: Option, + /// Serve a placeholder access token for this token-grant credential from + /// the sandbox GCE metadata emulator. The grant replaces it on its endpoints. + #[serde(default, skip_serializing_if = "is_false")] + pub gce_metadata_token: bool, } /// Origin-aware protobuf duration presence retained across profile conversion. @@ -204,6 +213,13 @@ pub struct TokenGrantProfile { pub subject_token: Option, #[serde(default, skip_serializing_if = "String::is_empty")] pub requested_token_type: String, + #[serde( + default = "default_token_grant_client_authentication", + deserialize_with = "deserialize_token_grant_client_authentication", + serialize_with = "serialize_token_grant_client_authentication", + skip_serializing_if = "is_client_assertion_authentication" + )] + pub client_authentication: ProviderCredentialTokenGrantClientAuthentication, } impl PartialEq for TokenGrantProfile { @@ -218,6 +234,8 @@ impl PartialEq for TokenGrantProfile { && self.audience_overrides == other.audience_overrides && self.subject_token == other.subject_token && self.requested_token_type == other.requested_token_type + && effective_token_grant_client_authentication(self.client_authentication) + == effective_token_grant_client_authentication(other.client_authentication) } } @@ -226,6 +244,8 @@ impl Eq for TokenGrantProfile {} #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] pub struct TokenGrantSubjectTokenProfile { pub source: String, + /// Required for `provider_credential`; must be empty for `jwt_svid`. + #[serde(default, skip_serializing_if = "String::is_empty")] pub credential: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub subject_token_type: String, @@ -827,6 +847,7 @@ impl ProviderTypeProfile { .map(credential_refresh_from_proto), path_template: credential.path_template.clone(), token_grant: credential.token_grant.as_ref().map(token_grant_from_proto), + gce_metadata_token: credential.gce_metadata_token, }) .collect(), files: profile @@ -1015,6 +1036,7 @@ impl ProviderTypeProfile { path_template: credential.path_template.clone(), token_grant: credential.token_grant.as_ref().map(token_grant_to_proto), token_grant_owners: Vec::new(), + gce_metadata_token: credential.gce_metadata_token, }) .collect(), files: self @@ -1316,6 +1338,29 @@ fn is_client_credentials_grant(value: &ProviderCredentialTokenGrantType) -> bool effective_token_grant_type(*value) == ProviderCredentialTokenGrantType::ClientCredentials } +fn default_token_grant_client_authentication() -> ProviderCredentialTokenGrantClientAuthentication { + ProviderCredentialTokenGrantClientAuthentication::Unspecified +} + +fn effective_token_grant_client_authentication( + client_authentication: ProviderCredentialTokenGrantClientAuthentication, +) -> ProviderCredentialTokenGrantClientAuthentication { + match client_authentication { + ProviderCredentialTokenGrantClientAuthentication::Unspecified => { + ProviderCredentialTokenGrantClientAuthentication::ClientAssertion + } + other => other, + } +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +fn is_client_assertion_authentication( + value: &ProviderCredentialTokenGrantClientAuthentication, +) -> bool { + effective_token_grant_client_authentication(*value) + == ProviderCredentialTokenGrantClientAuthentication::ClientAssertion +} + fn deserialize_category<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -1380,6 +1425,58 @@ where serializer.serialize_str(provider_token_grant_type_to_yaml(*grant_type)) } +fn deserialize_token_grant_client_authentication<'de, D>( + deserializer: D, +) -> Result +where + D: Deserializer<'de>, +{ + let raw = String::deserialize(deserializer)?; + provider_token_grant_client_authentication_from_yaml(&raw).ok_or_else(|| { + de::Error::custom(format!( + "unsupported provider token grant client_authentication: {raw}" + )) + }) +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +fn serialize_token_grant_client_authentication( + client_authentication: &ProviderCredentialTokenGrantClientAuthentication, + serializer: S, +) -> Result +where + S: Serializer, +{ + serializer.serialize_str(provider_token_grant_client_authentication_to_yaml( + *client_authentication, + )) +} + +/// Parse the YAML `client_authentication` value. Unknown values return `None`. +#[must_use] +pub fn provider_token_grant_client_authentication_from_yaml( + raw: &str, +) -> Option { + match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() { + "" | "client_assertion" => { + Some(ProviderCredentialTokenGrantClientAuthentication::ClientAssertion) + } + "none" => Some(ProviderCredentialTokenGrantClientAuthentication::None), + _ => None, + } +} + +#[must_use] +pub fn provider_token_grant_client_authentication_to_yaml( + client_authentication: ProviderCredentialTokenGrantClientAuthentication, +) -> &'static str { + match client_authentication { + ProviderCredentialTokenGrantClientAuthentication::None => "none", + ProviderCredentialTokenGrantClientAuthentication::ClientAssertion + | ProviderCredentialTokenGrantClientAuthentication::Unspecified => "client_assertion", + } +} + #[must_use] pub fn provider_profile_category_from_yaml(raw: &str) -> Option { match raw.trim().to_ascii_lowercase().replace('-', "_").as_str() { @@ -1565,6 +1662,13 @@ fn token_grant_from_proto( .as_ref() .map(token_grant_subject_token_from_proto), requested_token_type: token_grant.requested_token_type.clone(), + // An unknown wire value falls back to the default. Unspecified stays + // unspecified so profiles that omit the field keep their wire form. The + // supervisor rejects unknown values it receives directly. + client_authentication: ProviderCredentialTokenGrantClientAuthentication::try_from( + token_grant.client_authentication, + ) + .unwrap_or(ProviderCredentialTokenGrantClientAuthentication::Unspecified), } } @@ -1592,6 +1696,7 @@ fn token_grant_to_proto( .as_ref() .map(token_grant_subject_token_to_proto), requested_token_type: token_grant.requested_token_type.clone(), + client_authentication: token_grant.client_authentication as i32, } } @@ -2740,6 +2845,10 @@ pub fn validate_profile_set( credential, &credential_names, )); + diagnostics.extend(validate_token_grant_client_authentication( + source, profile_id, credential, + )); + diagnostics.extend(validate_gce_metadata_token(source, profile_id, credential)); diagnostics.extend(validate_token_grant_audience_overrides( source, profile_id, @@ -3357,31 +3466,41 @@ fn validate_token_grant_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( + match subject_token.source.trim() { + SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL => { + 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}"), + )); + } + } + SUBJECT_TOKEN_SOURCE_JWT_SVID => { + if !subject_credential.is_empty() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.token_grant.subject_token.credential", + "subject_token.credential must be empty when subject_token.source is jwt_svid", + )); + } + } + _ => diagnostics.push(ProfileValidationDiagnostic::error( source, profile_id, - "credentials.token_grant.subject_token.credential", - format!("unknown subject token credential: {subject_credential}"), - )); + "credentials.token_grant.subject_token.source", + "subject_token.source must be provider_credential or jwt_svid", + )), } } ProviderCredentialTokenGrantType::Unspecified => { @@ -3392,6 +3511,90 @@ fn validate_token_grant_subject_token( diagnostics } +/// Validate the client authentication sent to the token endpoint. +/// +/// Omitting client authentication is only safe when the subject token is the +/// sandbox's own JWT-SVID: that token alone proves the workload identity. +fn validate_token_grant_client_authentication( + source: &str, + profile_id: &str, + credential: &CredentialProfile, +) -> Vec { + let Some(token_grant) = credential.token_grant.as_ref() else { + return Vec::new(); + }; + if effective_token_grant_client_authentication(token_grant.client_authentication) + != ProviderCredentialTokenGrantClientAuthentication::None + { + return Vec::new(); + } + let mut diagnostics = Vec::new(); + if !token_grant_subject_is_jwt_svid(token_grant) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.token_grant.client_authentication", + "client_authentication none requires a token_exchange grant with subject_token.source jwt_svid", + )); + } + if !token_grant.client_assertion_type.trim().is_empty() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.token_grant.client_assertion_type", + "client_assertion_type cannot be set when client_authentication is none", + )); + } + diagnostics +} + +fn token_grant_subject_is_jwt_svid(token_grant: &TokenGrantProfile) -> bool { + effective_token_grant_type(token_grant.grant_type) + == ProviderCredentialTokenGrantType::TokenExchange + && token_grant + .subject_token + .as_ref() + .is_some_and(|subject| subject.source.trim() == SUBJECT_TOKEN_SOURCE_JWT_SVID) +} + +/// Validate `gce_metadata_token`. +/// +/// The placeholder served by the metadata emulator is sent by Google SDKs as +/// `Authorization: Bearer`. Only a token grant that replaces that header can +/// turn it into a credential, so the opt-in requires one. +fn validate_gce_metadata_token( + source: &str, + profile_id: &str, + credential: &CredentialProfile, +) -> Vec { + if !credential.gce_metadata_token { + return Vec::new(); + } + let mut diagnostics = Vec::new(); + if credential.token_grant.is_none() { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.gce_metadata_token", + "gce_metadata_token is only valid on token_grant credentials", + )); + } + let bearer = matches!( + credential.auth_style.trim().to_ascii_lowercase().as_str(), + "" | "bearer" + ); + let header = credential.header_name.trim(); + if !bearer || !(header.is_empty() || header.eq_ignore_ascii_case("authorization")) { + diagnostics.push(ProfileValidationDiagnostic::error( + source, + profile_id, + "credentials.gce_metadata_token", + "gce_metadata_token requires auth_style bearer on the Authorization header", + )); + } + diagnostics +} + fn validate_broker_only_subject_credentials( source: &str, profile_id: &str, @@ -3432,7 +3635,9 @@ fn token_exchange_subject_credential_names(profile: &ProviderTypeProfile) -> Has == ProviderCredentialTokenGrantType::TokenExchange }) .filter_map(|token_grant| token_grant.subject_token.as_ref()) - .filter(|subject_token| subject_token.source.trim() == "provider_credential") + .filter(|subject_token| { + subject_token.source.trim() == SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL + }) .filter_map(|subject_token| { let credential = subject_token.credential.trim(); (!credential.is_empty()).then_some(credential) @@ -3781,12 +3986,16 @@ mod tests { use std::collections::HashMap; use openshell_core::mcp::{DEFAULT_MCP_PROTOCOL_VERSION, McpProtocolVersion}; - use openshell_core::proto::{ProviderCredentialTokenGrantType, ProviderProfileCategory}; + use openshell_core::proto::{ + ProviderCredentialTokenGrantClientAuthentication, ProviderCredentialTokenGrantType, + ProviderProfileCategory, + }; 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, + ProfileDurationWkt, ProfileError, ProfileValidationDiagnostic, ProviderTypeProfile, + SUBJECT_TOKEN_SOURCE_JWT_SVID, 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, @@ -5534,6 +5743,188 @@ credentials: ); } + // The design target plus display_name and header_name, which every + // profile YAML and bearer credential require. + const SPIFFE_STS_PROFILE: &str = r#" +id: google-cloud +display_name: Google Cloud (SPIFFE) +credentials: + - name: wif_token + auth_style: bearer + header_name: Authorization + gce_metadata_token: true + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + jwt_svid_audience: //iam.googleapis.com/projects/N/locations/global/workloadIdentityPools/onix-spire/providers/spire + audience: //iam.googleapis.com/projects/N/locations/global/workloadIdentityPools/onix-spire/providers/spire + scopes: [https://www.googleapis.com/auth/cloud-platform] + requested_token_type: urn:ietf:params:oauth:token-type:access_token + client_authentication: none + subject_token: + source: jwt_svid + subject_token_type: urn:ietf:params:oauth:token-type:jwt +endpoints: + - { host: "*.googleapis.com", port: 443, protocol: rest, access: full } +"#; + + fn spiffe_sts_diagnostics(yaml: &str) -> Vec { + let profile = parse_profile_yaml(yaml).expect("profile should parse"); + validate_profile_set(&[("google-cloud.yaml".to_string(), profile)]) + } + + #[test] + fn jwt_svid_sts_profile_validates_and_round_trips() { + let profile = parse_profile_yaml(SPIFFE_STS_PROFILE).expect("profile should parse"); + let diagnostics = + validate_profile_set(&[("google-cloud.yaml".to_string(), profile.clone())]); + assert!( + diagnostics.is_empty(), + "unexpected diagnostics: {diagnostics:?}" + ); + + let credential = &profile.credentials[0]; + assert!(credential.gce_metadata_token); + let token_grant = credential.token_grant.as_ref().unwrap(); + assert_eq!( + token_grant.client_authentication, + ProviderCredentialTokenGrantClientAuthentication::None + ); + let subject = token_grant.subject_token.as_ref().unwrap(); + assert_eq!(subject.source, SUBJECT_TOKEN_SOURCE_JWT_SVID); + assert!(subject.credential.is_empty()); + + let proto = profile.to_proto(); + assert!(proto.credentials[0].gce_metadata_token); + assert_eq!( + proto.credentials[0] + .token_grant + .as_ref() + .unwrap() + .client_authentication, + ProviderCredentialTokenGrantClientAuthentication::None as i32 + ); + let from_proto = ProviderTypeProfile::from_proto(&proto); + assert_eq!(from_proto.credentials, profile.credentials); + + let exported = profile_to_yaml(&from_proto).expect("yaml"); + assert!(exported.contains("client_authentication: none")); + assert!(exported.contains("gce_metadata_token: true")); + assert!(!exported.contains("credential: ''")); + let reparsed = parse_profile_yaml(&exported).expect("re-parse"); + assert_eq!(reparsed.credentials, profile.credentials); + } + + #[test] + fn spiffe_gcp_sts_example_profile_validates() { + let yaml = include_str!("../../../examples/spiffe-gcp-sts-demo/provider-profile.yaml"); + let diagnostics = spiffe_sts_diagnostics(yaml); + assert!(diagnostics.is_empty(), "{diagnostics:?}"); + } + + #[test] + fn unknown_client_authentication_fails_to_parse() { + let yaml = SPIFFE_STS_PROFILE.replace( + "client_authentication: none", + "client_authentication: private_key_jwt", + ); + let error = parse_profile_yaml(&yaml).expect_err("unknown value must not be ignored"); + assert!( + error.to_string().contains("client_authentication"), + "{error}" + ); + } + + #[test] + fn jwt_svid_sts_profile_rejects_invalid_combinations() { + let cases: &[(&str, &str, &str, &str)] = &[ + // Unknown sources fail closed. + ( + "source: jwt_svid", + "source: kubernetes_token", + "credentials.token_grant.subject_token.source", + "must be provider_credential or jwt_svid", + ), + // The SVID is the subject; no stored credential may be named. + ( + "source: jwt_svid\n", + "source: jwt_svid\n credential: wif_token\n", + "credentials.token_grant.subject_token.credential", + "must be empty when subject_token.source is jwt_svid", + ), + // jwt_svid is only a token_exchange subject. + ( + "grant_type: token_exchange", + "grant_type: client_credentials", + "credentials.token_grant.subject_token", + "only valid for token_exchange grants", + ), + ( + "grant_type: token_exchange", + "grant_type: client_credentials", + "credentials.token_grant.client_authentication", + "requires a token_exchange grant with subject_token.source jwt_svid", + ), + // No client authentication without a self-proving subject. + ( + "source: jwt_svid\n", + "source: provider_credential\n credential: wif_token\n", + "credentials.token_grant.client_authentication", + "requires a token_exchange grant with subject_token.source jwt_svid", + ), + ( + "client_authentication: none", + "client_authentication: none\n client_assertion_type: urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + "credentials.token_grant.client_assertion_type", + "cannot be set when client_authentication is none", + ), + // The placeholder needs a grant replacing the Authorization header. + ( + " header_name: Authorization\n", + " header_name: X-Goog-Token\n", + "credentials.gce_metadata_token", + "requires auth_style bearer on the Authorization header", + ), + ]; + for (from, to, field, message) in cases { + let yaml = SPIFFE_STS_PROFILE.replace(from, to); + assert_ne!(yaml, SPIFFE_STS_PROFILE, "fixture did not change: {to}"); + let diagnostics = spiffe_sts_diagnostics(&yaml); + assert!( + diagnostics + .iter() + .any(|diagnostic| diagnostic.field == *field + && diagnostic.message.contains(message)), + "expected {field}: {message}; got {diagnostics:?}" + ); + } + } + + #[test] + fn gce_metadata_token_requires_token_grant() { + let diagnostics = spiffe_sts_diagnostics( + r" +id: plain +display_name: Plain +credentials: + - name: api_key + env_vars: [API_KEY] + auth_style: bearer + header_name: Authorization + gce_metadata_token: true +endpoints: + - { host: api.example.com, port: 443, protocol: rest, access: full } +", + ); + assert!( + diagnostics.iter().any(|diagnostic| diagnostic.field + == "credentials.gce_metadata_token" + && diagnostic.message + == "gce_metadata_token is only valid on token_grant credentials"), + "{diagnostics:?}" + ); + } + #[test] fn validate_profile_set_rejects_token_exchange_without_subject_token() { let profile = parse_profile_yaml( diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 61e458a23f..122248ed02 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -292,11 +292,13 @@ verified, currently authorized session JWT. The key must equal one of the gateway's configured keys, including its endpoint owner, once the supervisor's revision and installation are removed. Provider attachment and profile configuration determine the endpoint, audience, and scopes. The gateway performs -RFC 7523 or both RFC 8693 exchanges and returns only the final access token. +an RFC 7523 grant, both RFC 8693 exchanges for a stored subject token, or a +single RFC 8693 exchange whose `jwt_svid` subject is the sandbox JWT-SVID, and +returns only the final access token. Its bounded cache is isolated by sandbox generation, credential epoch, provider -revision, the matched configured key and grant, and the subject token, which is -resolved before every lookup so its revocation or rotation also applies to -cached tokens. Concurrent misses for one cache key wait for a single +revision, the matched configured key and grant, and any stored subject token, +which is resolved before every lookup so its revocation or rotation also applies +to cached tokens. Concurrent misses for one cache key wait for a single acquisition, then use its cached token. A token is served until the usual skew before the earliest of its `expires_in`, its JWT `exp`, and the session, SVID, and subject expiries, and no longer than the default cache lifetime; a diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index fb14346234..30e0d3dcb9 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -4962,7 +4962,7 @@ 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: Some(&gateway_jwt_svid), client_assertion_type: &token_grant.client_assertion_type, subject_token: &stored_subject_token, subject_token_type: &subject_token.subject_token_type, @@ -6775,7 +6775,7 @@ pub(super) mod tests { String::from_utf8_lossy(&request).to_ascii_lowercase() }); let params = TokenExchangeParams { - client_assertion: SECRET, + client_assertion: Some(SECRET), client_assertion_type: "", subject_token: SECRET, subject_token_type: "", @@ -6900,6 +6900,7 @@ pub(super) mod tests { env_vars: Vec::new(), required: false, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "Authorization".to_string(), query_param: String::new(), @@ -6917,6 +6918,7 @@ pub(super) mod tests { subject_token: None, scopes: vec!["openid".to_string()], requested_token_type: String::new(), + client_authentication: 0, cache_ttl: Some(prost_types::Duration { seconds: 300, nanos: 0 }), audience_overrides: service_audiences .iter() @@ -8102,6 +8104,7 @@ pub(super) mod tests { env_vars: vec![env_var.to_string()], required: true, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "authorization".to_string(), query_param: String::new(), @@ -8173,6 +8176,7 @@ pub(super) mod tests { env_vars: vec![env_var.to_string()], required, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "authorization".to_string(), query_param: String::new(), @@ -8190,6 +8194,7 @@ pub(super) mod tests { env_vars: Vec::new(), required: true, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "authorization".to_string(), query_param: String::new(), @@ -8205,6 +8210,7 @@ pub(super) mod tests { subject_token: None, scopes: vec!["read".to_string()], requested_token_type: String::new(), + client_authentication: 0, cache_ttl: Some(prost_types::Duration { seconds: 300, nanos: 0, @@ -13468,6 +13474,7 @@ pub(super) mod tests { token_grant_owners: Vec::new(), required: true, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "authorization".to_string(), query_param: String::new(), diff --git a/crates/openshell-server/src/grpc/provider/access_token.rs b/crates/openshell-server/src/grpc/provider/access_token.rs index 2936803b0a..c9956bca58 100644 --- a/crates/openshell-server/src/grpc/provider/access_token.rs +++ b/crates/openshell-server/src/grpc/provider/access_token.rs @@ -261,13 +261,22 @@ async fn obtain( } let grant_type = ProviderCredentialTokenGrantType::try_from(grant.grant_type) .map_err(|_| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; + let flow = oauth::TokenGrantFlow::resolve( + grant_type, + grant + .subject_token + .as_ref() + .map_or("", |subject| subject.source.as_str()), + grant.client_authentication, + ) + .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 flow == oauth::TokenGrantFlow::ProviderCredentialSubjectExchange { let subject = grant .subject_token .as_ref() - .filter(|subject| subject.source == "provider_credential") + .filter(|subject| subject.source == oauth::SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL) .ok_or_else(|| token_grant_configuration_status(tonic::Code::FailedPrecondition))?; Some(Subject { expires_at_ms: provider_credential_expiration_ms( @@ -322,6 +331,7 @@ async fn obtain( identity, gateway_id, grant, + flow, subject.as_ref(), ttl_override, request_id, @@ -385,6 +395,7 @@ async fn acquire( identity: &dyn SandboxIdentityProvider, gateway_id: &str, grant: &ProviderCredentialTokenGrant, + flow: oauth::TokenGrantFlow, subject: Option<&Subject>, ttl_override: Option, request_id: Option<&str>, @@ -431,7 +442,7 @@ async fn acquire( let intermediate = perform_intermediate_token_exchange( &grant.token_endpoint, &TokenExchangeParams { - client_assertion: &component_svid, + client_assertion: Some(&component_svid), client_assertion_type: &grant.client_assertion_type, subject_token: &subject.value, subject_token_type: &subject.token_type, @@ -447,7 +458,7 @@ async fn acquire( client, &grant.token_endpoint, &TokenExchangeParams { - client_assertion: &svid.token, + client_assertion: Some(&svid.token), client_assertion_type: &grant.client_assertion_type, subject_token: &intermediate.access_token, subject_token_type: oauth::ACCESS_TOKEN_TYPE, @@ -459,6 +470,31 @@ async fn acquire( ) .await .map_err(TokenGrantFailure::to_status)? + } else if let oauth::TokenGrantFlow::JwtSvidSubjectExchange { client_assertion } = flow { + // The sandbox's stable SVID is the subject; the endpoint trusts its + // issuer directly, so there is no intermediate exchange. + let subject_token_type = grant + .subject_token + .as_ref() + .map_or("", |subject| subject.subject_token_type.as_str()); + oauth::post_oauth_token_exchange( + client, + &grant.token_endpoint, + &TokenExchangeParams { + client_assertion: client_assertion.then_some(svid.token.as_str()), + client_assertion_type: &grant.client_assertion_type, + subject_token: &svid.token, + subject_token_type: oauth::effective_jwt_svid_subject_token_type( + subject_token_type, + ), + audience: &grant.audience, + scopes: &grant.scopes, + requested_token_type: &grant.requested_token_type, + }, + request_id, + ) + .await + .map_err(TokenGrantFailure::to_status)? } else { oauth::post_oauth_token_grant( client, diff --git a/crates/openshell-server/src/grpc/secret_refresh_tests.rs b/crates/openshell-server/src/grpc/secret_refresh_tests.rs index 72efe36d3e..998489cbeb 100644 --- a/crates/openshell-server/src/grpc/secret_refresh_tests.rs +++ b/crates/openshell-server/src/grpc/secret_refresh_tests.rs @@ -79,6 +79,7 @@ async fn import_profile_with_material( env_vars: vec![KEY.to_string()], required: true, stable_placeholder: false, + gce_metadata_token: false, auth_style: "bearer".to_string(), header_name: "authorization".to_string(), query_param: String::new(), diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index f20bbbd3cb..50b975875d 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -249,14 +249,17 @@ 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. + // Provider token grants add a client_authentication enum and credentials + // add gce_metadata_token. Both are new tags whose zero values keep the + // prior behavior, so earlier profile payloads decode unchanged. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "dc96b55350209d252c8eb22a697fede2abf26d6bcb80223774c5fa093dca885b"; + "6ac69c2d118c12299b930587266e967b464ef0463a10b97aaad562a752733b83"; // 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 = - "1005cf2557d49ea54a302cc76d837cc1a6c637adb0db73ec9444569e8d39fd71"; + "a40c73fe735e43836125901b109db85252121b01388bbfa3494c576981335581"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = - "c7a66485b85999c0227d1eef52b159b3be5c05d68c0a900f5f6303021a46d75f"; + "a4302e325b2397902e114c7255d64ac9ce0b40001087440b5c91bcdb20a8ca38"; // 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"; @@ -800,9 +803,9 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 31), - (104, 22), - (88, 22), + (369, 32), + (104, 23), + (88, 23), 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 8d4905e9e7..e02cf9c591 100644 --- a/crates/openshell-supervisor-network/README.md +++ b/crates/openshell-supervisor-network/README.md @@ -31,7 +31,9 @@ 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 the intermediate exchange of RFC 8693 grants whose +subject is a stored provider credential. A `jwt_svid` subject sends the +instance's JWT-SVID directly and needs no gateway call. 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/google_cloud_metadata.rs b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs index ea5d0c16bd..f203fcea0f 100644 --- a/crates/openshell-supervisor-network/src/google_cloud_metadata.rs +++ b/crates/openshell-supervisor-network/src/google_cloud_metadata.rs @@ -6,7 +6,9 @@ //! Implements a subset of the GCE instance metadata API so that GCP client //! libraries (Go, Python, Node.js) can obtain `OAuth2` tokens natively inside //! sandboxes. Tokens are served from the existing `ProviderCredentialState` -//! store — no separate refresh mechanism is needed. +//! store — no separate refresh mechanism is needed. A token-grant credential +//! with `gce_metadata_token` gets a reserved placeholder that never resolves; +//! the grant replaces it in the `Authorization` header on its endpoints. //! //! The sandbox broker relays the reserved loopback metadata destination to //! this supervisor-owned handler. SDKs discover it through `GCE_METADATA_HOST`; @@ -690,6 +692,59 @@ mod tests { assert_eq!(json["expires_in"], 3600); } + #[test] + fn gce_metadata_token_grant_serves_unresolvable_placeholder() { + let credential = openshell_core::proto::ProviderProfileCredential { + name: "wif_token".into(), + auth_style: "bearer".into(), + gce_metadata_token: true, + token_grant: Some(openshell_core::proto::ProviderCredentialTokenGrant { + token_endpoint: "https://sts.googleapis.com/v1/token".into(), + ..Default::default() + }), + ..Default::default() + }; + let ctx = MetadataContext::new(ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + HashMap::from([("*.googleapis.com:443:/**".to_string(), credential.clone())]), + )); + let (status, _, body) = route_request(&ctx, "GET", PATH_TOKEN, &flavor_headers()); + assert_eq!(status, 200); + let json: serde_json::Value = serde_json::from_str(&body).unwrap(); + let token = json["access_token"].as_str().unwrap(); + assert_eq!( + token, + openshell_core::secrets::placeholder_for_env_key( + openshell_core::google_cloud::TOKEN_GRANT_PLACEHOLDER_ENV_KEY + ) + ); + assert_eq!( + json["expires_in"], + openshell_core::google_cloud::TOKEN_GRANT_PLACEHOLDER_EXPIRES_IN_SECONDS + ); + assert_eq!(json["token_type"], "Bearer"); + + // A grant-only installation without the opt-in still has no token. + let ctx = MetadataContext::new(ProviderCredentialState::from_environment( + 1, + HashMap::new(), + HashMap::new(), + HashMap::from([( + "*.googleapis.com:443:/**".to_string(), + openshell_core::proto::ProviderProfileCredential { + gce_metadata_token: false, + ..credential + }, + )]), + )); + assert_eq!( + route_request(&ctx, "GET", PATH_TOKEN, &flavor_headers()).0, + 503 + ); + } + #[test] fn missing_metadata_flavor_header_403() { let ctx = make_context(HashMap::new()); 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..8eb27d3bf7 100644 --- a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs +++ b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs @@ -31,6 +31,7 @@ use crate::l7::provider::L7Request; use crate::l7::relay::L7EvalContext; /// Borrowed grant configuration for one endpoint-bound provider credential. +#[derive(Clone, Copy)] pub struct TokenGrantRequest<'a> { pub provider_key: &'a str, pub token_endpoint: &'a str, @@ -41,6 +42,12 @@ pub struct TokenGrantRequest<'a> { pub cache_ttl: Option, pub grant_type: i32, pub requested_token_type: &'a str, + /// `subject_token.source`; empty for grants without a subject token. + pub subject_token_source: &'a str, + /// `subject_token.subject_token_type`; empty selects the source default. + pub subject_token_type: &'a str, + /// Raw `ProviderCredentialTokenGrantClientAuthentication`. + pub client_authentication: i32, /// Supervisor-minted ID of the HTTP exchange that needs the token. pub request_id: &'a str, } @@ -577,6 +584,15 @@ fn token_grant_request<'a>( cache_ttl, grant_type: token_grant.grant_type, requested_token_type: &token_grant.requested_token_type, + subject_token_source: token_grant + .subject_token + .as_ref() + .map_or("", |subject| subject.source.as_str()), + subject_token_type: token_grant + .subject_token + .as_ref() + .map_or("", |subject| subject.subject_token_type.as_str()), + client_authentication: token_grant.client_authentication, request_id, }) } @@ -1046,6 +1062,7 @@ pub mod test_support { grant_type: ProviderCredentialTokenGrantType::ClientCredentials as i32, subject_token: None, requested_token_type: String::new(), + client_authentication: 0, } } @@ -1064,6 +1081,52 @@ pub mod test_support { } } + #[test] + fn token_grant_request_carries_subject_source_and_client_authentication() { + use openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication; + let grant = ProviderCredentialTokenGrant { + client_assertion_type: String::new(), + subject_token: Some(ProviderCredentialTokenGrantSubjectToken { + source: "jwt_svid".to_string(), + credential: String::new(), + subject_token_type: "urn:ietf:params:oauth:token-type:jwt".to_string(), + }), + client_authentication: ProviderCredentialTokenGrantClientAuthentication::None as i32, + ..token_exchange_grant() + }; + let request = token_grant_request("key", &grant, "request-1").expect("request"); + assert_eq!(request.subject_token_source, "jwt_svid"); + assert_eq!( + request.subject_token_type, + "urn:ietf:params:oauth:token-type:jwt" + ); + assert_eq!( + request.client_authentication, + ProviderCredentialTokenGrantClientAuthentication::None as i32 + ); + + let plain = token_grant(); + let request = token_grant_request("key", &plain, "request-1").expect("request"); + assert_eq!(request.subject_token_source, ""); + assert_eq!(request.subject_token_type, ""); + assert_eq!(request.client_authentication, 0); + } + + #[test] + fn grant_header_replaces_gce_metadata_placeholder() { + let placeholder = openshell_core::secrets::placeholder_for_env_key( + openshell_core::google_cloud::TOKEN_GRANT_PLACEHOLDER_ENV_KEY, + ); + let raw = format!( + "GET /storage/v1/b HTTP/1.1\r\nHost: storage.googleapis.com\r\nAuthorization: Bearer {placeholder}\r\n\r\n" + ); + let rewritten = inject_header(raw.as_bytes(), "Authorization", "Bearer ya29.real") + .expect("header injection"); + let rewritten = String::from_utf8(rewritten).unwrap(); + assert!(rewritten.contains("Authorization: Bearer ya29.real\r\n")); + assert!(!openshell_core::secrets::contains_reserved_credential_marker(&rewritten)); + } + impl TokenGrantResolver for FakeTokenGrantResolver { fn obtain<'a>( &'a self, diff --git a/crates/openshell-supervisor-network/src/token_grant.rs b/crates/openshell-supervisor-network/src/token_grant.rs index df2a25a559..ae8cb3b159 100644 --- a/crates/openshell-supervisor-network/src/token_grant.rs +++ b/crates/openshell-supervisor-network/src/token_grant.rs @@ -13,7 +13,11 @@ //! 2. Check token cache for unexpired access token //! 3. On cache miss or expiry: //! a. Fetch JWT-SVID from SPIRE agent (via Workload API) -//! b. POST to token service with JWT client assertion grant +//! b. POST to token service with JWT client assertion grant, or with an +//! RFC 8693 token exchange whose subject is a gateway-exchanged provider +//! credential (`subject_token.source: provider_credential`) or the +//! JWT-SVID itself (`subject_token.source: jwt_svid`, no gateway call, +//! optionally with `client_authentication: none`) //! c. Cache the returned access token with TTL //! 4. Inject `Authorization: Bearer ` header //! @@ -50,7 +54,8 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use openshell_core::grpc_client::{GatewayEndpoint, SandboxProviderTokenClient}; use openshell_core::oauth::{ self, ACCESS_TOKEN_TYPE, OAuthTokenResponse, TokenExchangeParams, TokenGrantClient, - TokenGrantParams, effective_client_assertion_type, effective_token_type, token_cache_ttl, + TokenGrantFlow as GrantFlow, TokenGrantParams, effective_client_assertion_type, + effective_jwt_svid_subject_token_type, effective_token_type, token_cache_ttl, }; use openshell_core::proto::ProviderCredentialTokenGrantType; use openshell_core::token_grant_failure::{ @@ -164,12 +169,17 @@ 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 for a provider using its token grant. /// /// 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). + /// API socket, then POSTs to the provider's token endpoint with one of: + /// - the JWT client assertion grant (RFC 7523), for `client_credentials`; + /// - an RFC 8693 token exchange whose subject token the gateway exchanges + /// from a stored provider credential (`subject_token.source: + /// provider_credential`), authenticated with the SVID as client assertion; + /// - an RFC 8693 token exchange whose subject token is the SVID itself + /// (`subject_token.source: jwt_svid`), sent directly to the token + /// endpoint with or without a client assertion and no gateway call. /// /// Tokens are cached per provider name with TTL in this instance's cache. /// Subsequent calls return the cached token if it has not expired. @@ -177,6 +187,7 @@ impl SpiffeTokenGrantResolver { /// # Errors /// /// Returns an error if: + /// - The grant configuration is unknown or inconsistent /// - SPIFFE Workload API socket is not configured /// - SPIRE agent is unreachable /// - JWT-SVID fetch fails @@ -188,7 +199,12 @@ impl SpiffeTokenGrantResolver { ) -> Result { let grant_type = ProviderCredentialTokenGrantType::try_from(request.grant_type) .map_err(|_| configuration_failure())?; - let token = obtain_provider_token_with_grant( + let flow = GrantFlow::resolve( + grant_type, + request.subject_token_source, + request.client_authentication, + )?; + obtain_provider_token_with_grant( ObtainProviderTokenInput { cache: &self.cache, provider_name: request.provider_key, @@ -200,80 +216,70 @@ impl SpiffeTokenGrantResolver { cache_ttl_override: request.cache_ttl, grant_type, requested_token_type: request.requested_token_type, + flow, + subject_token_type: request.subject_token_type, }, - |jwt_audience| async move { - // Resolve local exchange prerequisites before fetching any workload credential. - let exchange_context = match grant_type { - ProviderCredentialTokenGrantType::ClientCredentials - | ProviderCredentialTokenGrantType::Unspecified => None, - ProviderCredentialTokenGrantType::TokenExchange => { - let (provider, credential_key) = - parse_provider_credential_key(request.provider_key)?; - let gateway = self.gateway.as_ref().ok_or_else(configuration_failure)?; - openshell_core::grpc_client::token_grant_gateway_endpoint(gateway.url())?; - let sandbox_id = self - .sandbox_id - .as_deref() - .ok_or_else(configuration_failure)?; - Some((provider, credential_key, gateway, sandbox_id)) - } - }; - let http_client = self.http_client.as_ref().map_err(|failure| *failure)?; - // Fetch JWT-SVID with authorization server as audience - // For RFC 7523, the JWT assertion's aud claim identifies the issuer/realm - let jwt_svid = self.fetch_jwt_svid(&jwt_audience).await?; - - let response = match exchange_context { - None => { - // Perform OAuth2 JWT client assertion grant. The audience - // parameter in the token request specifies the resource server. - perform_token_grant( - http_client, - request.token_endpoint, - &jwt_svid, - request.client_assertion_type, - request.audience, - request.scopes, - request.request_id, - ) - .await - } - Some((provider, credential_key, gateway, sandbox_id)) => { - let intermediate = - openshell_core::grpc_client::exchange_provider_subject_token( - gateway, - sandbox_id, - provider, - credential_key, - &jwt_svid, - Some(request.request_id), - ) - .await?; - validate_access_token(&intermediate.access_token).map_err(|failure| { - failure.at_stage(TokenGrantStage::IntermediateExchange) - })?; - perform_token_exchange( - http_client, - request.token_endpoint, - &TokenExchangeParams { - client_assertion: &jwt_svid, - client_assertion_type: request.client_assertion_type, - subject_token: &intermediate.access_token, - subject_token_type: ACCESS_TOKEN_TYPE, - audience: request.audience, - scopes: request.scopes, - requested_token_type: request.requested_token_type, - }, - request.request_id, - ) - .await - } - }?; - Ok(response) - }, + move |jwt_audience| self.acquire(request, flow, jwt_audience), + ) + .await + } + + async fn acquire( + &self, + request: TokenGrantRequest<'_>, + flow: GrantFlow, + jwt_audience: String, + ) -> Result { + // Resolve local exchange prerequisites before fetching any workload credential. + let gateway_context = match flow { + GrantFlow::ProviderCredentialSubjectExchange => { + let (provider, credential_key) = + parse_provider_credential_key(request.provider_key)?; + let gateway = self.gateway.as_ref().ok_or_else(configuration_failure)?; + openshell_core::grpc_client::token_grant_gateway_endpoint(gateway.url())?; + let sandbox_id = self + .sandbox_id + .as_deref() + .ok_or_else(configuration_failure)?; + Some((provider, credential_key, gateway, sandbox_id)) + } + GrantFlow::ClientCredentials | GrantFlow::JwtSvidSubjectExchange { .. } => None, + }; + let http_client = self.http_client.as_ref().map_err(|failure| *failure)?; + // Fetch the JWT-SVID with the configured audience. For RFC 7523 the + // assertion's aud identifies the issuer/realm; for a jwt_svid subject it + // is the audience the token service expects in the subject token. + let jwt_svid = self.fetch_jwt_svid(&jwt_audience).await?; + + let Some((provider, credential_key, gateway, sandbox_id)) = gateway_context else { + return perform_svid_grant(http_client, &request, flow, &jwt_svid).await; + }; + let intermediate = openshell_core::grpc_client::exchange_provider_subject_token( + gateway, + sandbox_id, + provider, + credential_key, + &jwt_svid, + Some(request.request_id), ) .await?; - Ok(token) + validate_access_token(&intermediate.access_token) + .map_err(|failure| failure.at_stage(TokenGrantStage::IntermediateExchange))?; + perform_token_exchange( + http_client, + request.token_endpoint, + &TokenExchangeParams { + client_assertion: Some(&jwt_svid), + client_assertion_type: request.client_assertion_type, + subject_token: &intermediate.access_token, + subject_token_type: ACCESS_TOKEN_TYPE, + audience: request.audience, + scopes: request.scopes, + requested_token_type: request.requested_token_type, + }, + request.request_id, + ) + .await } } @@ -322,6 +328,51 @@ impl TokenGrantResolver for GatewayTokenGrantResolver { } } +/// Grant flows that need nothing beyond the SVID: no gateway hop. +async fn perform_svid_grant( + http_client: &TokenGrantClient, + request: &TokenGrantRequest<'_>, + flow: GrantFlow, + jwt_svid: &str, +) -> Result { + match flow { + GrantFlow::JwtSvidSubjectExchange { client_assertion } => { + perform_token_exchange( + http_client, + request.token_endpoint, + &TokenExchangeParams { + client_assertion: client_assertion.then_some(jwt_svid), + client_assertion_type: request.client_assertion_type, + subject_token: jwt_svid, + subject_token_type: effective_jwt_svid_subject_token_type( + request.subject_token_type, + ), + audience: request.audience, + scopes: request.scopes, + requested_token_type: request.requested_token_type, + }, + request.request_id, + ) + .await + } + // Perform OAuth2 JWT client assertion grant. The audience parameter + // in the token request specifies the resource server. + GrantFlow::ClientCredentials => { + perform_token_grant( + http_client, + request.token_endpoint, + jwt_svid, + request.client_assertion_type, + request.audience, + request.scopes, + request.request_id, + ) + .await + } + GrantFlow::ProviderCredentialSubjectExchange => Err(configuration_failure()), + } +} + struct ObtainProviderTokenInput<'a> { cache: &'a TokenCache, provider_name: &'a str, @@ -333,6 +384,8 @@ struct ObtainProviderTokenInput<'a> { cache_ttl_override: Option, grant_type: ProviderCredentialTokenGrantType, requested_token_type: &'a str, + flow: GrantFlow, + subject_token_type: &'a str, } async fn obtain_provider_token_with_grant( @@ -353,6 +406,8 @@ where scopes: input.scopes, grant_type: input.grant_type, requested_token_type: effective_token_type(input.requested_token_type), + flow: input.flow, + subject_token_type: input.subject_token_type, }); if input.cache_ttl_override != Some(Duration::ZERO) @@ -521,11 +576,13 @@ struct TokenCacheKeyInput<'a> { scopes: &'a [String], grant_type: ProviderCredentialTokenGrantType, requested_token_type: &'a str, + flow: GrantFlow, + subject_token_type: &'a str, } 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 +590,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.flow, + input.subject_token_type ) } @@ -637,6 +696,11 @@ pub mod test_support { Box::pin(async move { let grant_type = ProviderCredentialTokenGrantType::try_from(request.grant_type) .map_err(|_| configuration_failure())?; + let flow = GrantFlow::resolve( + grant_type, + request.subject_token_source, + request.client_authentication, + )?; obtain_provider_token_with_grant( ObtainProviderTokenInput { cache: &self.cache, @@ -649,6 +713,8 @@ pub mod test_support { cache_ttl_override: request.cache_ttl, grant_type, requested_token_type: request.requested_token_type, + flow, + subject_token_type: request.subject_token_type, }, |jwt_audience| async move { let cache_key = token_cache_key(TokenCacheKeyInput { @@ -664,6 +730,8 @@ pub mod test_support { requested_token_type: effective_token_type( request.requested_token_type, ), + flow, + subject_token_type: request.subject_token_type, }); let mut acquisitions = self .acquisitions @@ -695,8 +763,9 @@ mod tests { use super::*; use openshell_core::oauth::{ ACCESS_TOKEN_TYPE, DEFAULT_CLIENT_ASSERTION_TYPE, DEFAULT_TOKEN_CACHE_TTL_SECONDS, - MAX_TOKEN_EXPIRES_IN_SECONDS, TOKEN_CACHE_EXPIRY_SKEW_SECONDS, + JWT_TOKEN_TYPE, MAX_TOKEN_EXPIRES_IN_SECONDS, TOKEN_CACHE_EXPIRY_SKEW_SECONDS, }; + use openshell_core::proto::ProviderCredentialTokenGrantClientAuthentication; use std::collections::HashMap; use std::sync::{ Arc, @@ -921,6 +990,8 @@ mod tests { cache_ttl_override: input.cache_ttl_override, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: "", + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }, move |_| { let grant_calls = input.grant_calls.clone(); @@ -958,6 +1029,8 @@ mod tests { cache_ttl_override, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: "", + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }, |_| async { panic!("grant should not be called on cache hit") }, ) @@ -1063,6 +1136,8 @@ mod tests { scopes: &alpha_scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); let different_audience = token_cache_key(TokenCacheKeyInput { provider_name, @@ -1073,6 +1148,8 @@ mod tests { scopes: &alpha_scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); let different_scopes = token_cache_key(TokenCacheKeyInput { provider_name, @@ -1083,6 +1160,8 @@ mod tests { scopes: &delta_scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); let different_assertion_type = token_cache_key(TokenCacheKeyInput { provider_name, @@ -1093,6 +1172,8 @@ mod tests { scopes: &alpha_scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); assert_ne!(base, different_audience); @@ -1115,6 +1196,8 @@ mod tests { scopes: &scopes, grant_type: ProviderCredentialTokenGrantType::TokenExchange, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ProviderCredentialSubjectExchange, + subject_token_type: "", }); let revision_two = token_cache_key(TokenCacheKeyInput { provider_name: "api.example.test\t443\t/v1/**\trev:2\tprovider:access_token", @@ -1125,6 +1208,8 @@ mod tests { scopes: &scopes, grant_type: ProviderCredentialTokenGrantType::TokenExchange, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ProviderCredentialSubjectExchange, + subject_token_type: "", }); assert_ne!(revision_one, revision_two); @@ -1224,6 +1309,8 @@ mod tests { scopes: &scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); cache.set(identity_cache_key, "expired".into(), current_time_ms() - 1); let service_token = obtain_token_without_grant_call( @@ -1363,6 +1450,8 @@ mod tests { scopes: &scopes, grant_type: ProviderCredentialTokenGrantType::ClientCredentials, requested_token_type: ACCESS_TOKEN_TYPE, + flow: GrantFlow::ClientCredentials, + subject_token_type: "", }); cache.set( cache_key, @@ -1687,4 +1776,263 @@ mod tests { assert_eq!(err.upstream_status(), Some(200)); } + + const STS_AUDIENCE: &str = "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/onix-spire/providers/spire"; + const CLOUD_PLATFORM: &str = "https://www.googleapis.com/auth/cloud-platform"; + const NONE_AUTH: i32 = ProviderCredentialTokenGrantClientAuthentication::None as i32; + + #[test] + fn grant_flow_resolves_sources_and_fails_closed() { + use ProviderCredentialTokenGrantType::{ClientCredentials, TokenExchange, Unspecified}; + let assertion = ProviderCredentialTokenGrantClientAuthentication::ClientAssertion as i32; + for (grant_type, source, auth, expected) in [ + (ClientCredentials, "", 0, Some(GrantFlow::ClientCredentials)), + ( + Unspecified, + "", + assertion, + Some(GrantFlow::ClientCredentials), + ), + ( + TokenExchange, + "", + 0, + Some(GrantFlow::ProviderCredentialSubjectExchange), + ), + ( + TokenExchange, + "provider_credential", + assertion, + Some(GrantFlow::ProviderCredentialSubjectExchange), + ), + ( + TokenExchange, + " jwt_svid ", + 0, + Some(GrantFlow::JwtSvidSubjectExchange { + client_assertion: true, + }), + ), + ( + TokenExchange, + "jwt_svid", + NONE_AUTH, + Some(GrantFlow::JwtSvidSubjectExchange { + client_assertion: false, + }), + ), + // No client authentication without a self-proving subject token. + (ClientCredentials, "", NONE_AUTH, None), + (TokenExchange, "provider_credential", NONE_AUTH, None), + // Unknown values from a newer gateway fail closed. + (TokenExchange, "kubernetes_token", 0, None), + (TokenExchange, "jwt_svid", 99, None), + ] { + let resolved = GrantFlow::resolve(grant_type, source, auth); + match expected { + Some(flow) => assert_eq!(resolved, Ok(flow), "{grant_type:?} {source} {auth}"), + None => assert_eq!( + resolved, + Err(configuration_failure()), + "{grant_type:?} {source} {auth}" + ), + } + } + } + + fn jwt_svid_request<'a>( + token_endpoint: &'a str, + scopes: &'a [String], + ) -> TokenGrantRequest<'a> { + TokenGrantRequest { + provider_key: "*.googleapis.com\t443\t/**\tgoogle:wif_token", + token_endpoint, + jwt_svid_audience: STS_AUDIENCE, + client_assertion_type: "", + audience: STS_AUDIENCE, + scopes, + cache_ttl: None, + grant_type: ProviderCredentialTokenGrantType::TokenExchange as i32, + requested_token_type: ACCESS_TOKEN_TYPE, + subject_token_source: "jwt_svid", + subject_token_type: "", + client_authentication: NONE_AUTH, + request_id: TEST_REQUEST_ID, + } + } + + async fn obtain_with_fixed_svid( + cache: &TokenCache, + request: TokenGrantRequest<'_>, + svid_audiences: &std::sync::Mutex>, + ) -> Result { + let grant_type = ProviderCredentialTokenGrantType::try_from(request.grant_type).unwrap(); + let flow = GrantFlow::resolve( + grant_type, + request.subject_token_source, + request.client_authentication, + )?; + obtain_provider_token_with_grant( + ObtainProviderTokenInput { + cache, + provider_name: request.provider_key, + token_endpoint: request.token_endpoint, + jwt_svid_audience: request.jwt_svid_audience, + client_assertion_type: request.client_assertion_type, + audience: request.audience, + scopes: request.scopes, + cache_ttl_override: request.cache_ttl, + grant_type, + requested_token_type: request.requested_token_type, + flow, + subject_token_type: request.subject_token_type, + }, + |jwt_audience| async move { + // Stand-in for the Workload API: the SVID is the only workload input. + svid_audiences.lock().unwrap().push(jwt_audience); + perform_svid_grant( + &test_http_client(), + &request, + flow, + "header.jwt-svid.signature", + ) + .await + }, + ) + .await + } + + #[tokio::test] + async fn jwt_svid_subject_is_exchanged_directly_without_client_assertion_and_cached() { + let (endpoint, request) = token_endpoint_once( + "200 OK", + r#"{"access_token":"ya29.federated","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"Bearer","expires_in":3599}"#, + ) + .await; + let scopes = vec![CLOUD_PLATFORM.to_string()]; + let cache = TokenCache::new(); + let audiences = std::sync::Mutex::new(Vec::new()); + + let token = + obtain_with_fixed_svid(&cache, jwt_svid_request(&endpoint, &scopes), &audiences) + .await + .expect("STS exchange should succeed"); + let request = request.await.expect("token endpoint task should finish"); + + assert_eq!(token, "ya29.federated"); + assert_eq!(*audiences.lock().unwrap(), [STS_AUDIENCE]); + let expected = HashMap::from([ + ( + "grant_type".to_string(), + "urn:ietf:params:oauth:grant-type:token-exchange".to_string(), + ), + ("audience".to_string(), STS_AUDIENCE.to_string()), + ("scope".to_string(), CLOUD_PLATFORM.to_string()), + ( + "requested_token_type".to_string(), + ACCESS_TOKEN_TYPE.to_string(), + ), + ("subject_token_type".to_string(), JWT_TOKEN_TYPE.to_string()), + ( + "subject_token".to_string(), + "header.jwt-svid.signature".to_string(), + ), + ]); + assert_eq!(request.form, expected); + + // The endpoint accepted one request; a second call must be a cache hit. + let cached = + obtain_with_fixed_svid(&cache, jwt_svid_request(&endpoint, &scopes), &audiences) + .await + .expect("cached token"); + assert_eq!(cached, "ya29.federated"); + assert_eq!(audiences.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn jwt_svid_subject_can_also_authenticate_as_client_assertion() { + let (endpoint, request) = + token_endpoint_once("200 OK", r#"{"access_token":"exchanged"}"#).await; + let scopes = Vec::new(); + let mut grant = jwt_svid_request(&endpoint, &scopes); + grant.client_authentication = 0; + grant.subject_token_type = "urn:ietf:params:oauth:token-type:id_token"; + let audiences = std::sync::Mutex::new(Vec::new()); + + obtain_with_fixed_svid(&TokenCache::new(), grant, &audiences) + .await + .expect("exchange should succeed"); + let request = request.await.expect("token endpoint task should finish"); + + assert_eq!( + request.form.get("client_assertion").map(String::as_str), + Some("header.jwt-svid.signature") + ); + assert_eq!( + request + .form + .get("client_assertion_type") + .map(String::as_str), + Some(DEFAULT_CLIENT_ASSERTION_TYPE) + ); + assert_eq!( + request.form.get("subject_token_type").map(String::as_str), + Some("urn:ietf:params:oauth:token-type:id_token") + ); + } + + #[tokio::test] + async fn jwt_svid_exchange_failure_is_not_cached() { + let scopes = vec![CLOUD_PLATFORM.to_string()]; + let cache = TokenCache::new(); + let audiences = std::sync::Mutex::new(Vec::new()); + let (endpoint, request) = token_endpoint_once( + "403 Forbidden", + r#"{"error":"unauthorized_client","error_description":"header.jwt-svid.signature"}"#, + ) + .await; + let failure = + obtain_with_fixed_svid(&cache, jwt_svid_request(&endpoint, &scopes), &audiences) + .await + .expect_err("rejected exchange fails closed"); + request.await.expect("token endpoint task should finish"); + assert_eq!(failure.upstream_status(), Some(403)); + assert_eq!(failure.stage(), TokenGrantStage::TokenEndpoint); + assert!(!failure.to_string().contains("jwt-svid")); + + let (endpoint_ok, request) = + token_endpoint_once("200 OK", r#"{"access_token":"recovered"}"#).await; + // Same cache, new endpoint: a failure never leaves an entry behind. + let token = + obtain_with_fixed_svid(&cache, jwt_svid_request(&endpoint_ok, &scopes), &audiences) + .await + .expect("retry succeeds"); + request.await.expect("token endpoint task should finish"); + assert_eq!(token, "recovered"); + assert_eq!(audiences.lock().unwrap().len(), 2); + } + + #[tokio::test] + async fn jwt_svid_grant_needs_no_gateway_or_sandbox_id() { + // Without a gateway the jwt_svid flow proceeds to the Workload API; + // here no socket is configured, so it fails at that local step only. + let grants = SpiffeTokenGrantResolver::new(None, None, None); + let scopes = vec![CLOUD_PLATFORM.to_string()]; + let failure = grants + .obtain_provider_token(jwt_svid_request( + "https://sts.googleapis.com/v1/token", + &scopes, + )) + .await + .expect_err("no workload socket"); + assert_eq!(failure, configuration_failure()); + + let mut inconsistent = jwt_svid_request("https://sts.googleapis.com/v1/token", &scopes); + inconsistent.subject_token_source = "provider_credential"; + let failure = grants + .obtain_provider_token(inconsistent) + .await + .expect_err("none requires jwt_svid"); + assert_eq!(failure, configuration_failure()); + } } diff --git a/docs/how-it-works/providers/profiles.mdx b/docs/how-it-works/providers/profiles.mdx index 9b083fe05e..3e9ac65208 100644 --- a/docs/how-it-works/providers/profiles.mdx +++ b/docs/how-it-works/providers/profiles.mdx @@ -819,7 +819,8 @@ 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` | The sandbox JWT-SVID, requested with `jwt_svid_audience`, is sent as the RFC 8693 `subject_token` directly to `token_endpoint`. There is no intermediate exchange and no stored credential. A dedicated supervisor sends it without a gateway call; for shared supervisors the gateway sends the stable sandbox JWT-SVID. With `client_authentication: none` the request carries no `client_assertion`, which is what Google Security Token Service expects for Workload Identity Federation. | +| `token_exchange` with `subject_token.source: provider_credential` | 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. | 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: @@ -856,8 +857,9 @@ Token grant fields: | `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` | Subject-token source. `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. `source: jwt_svid` uses the sandbox JWT-SVID as the subject token and requires `credential` to be empty. Other sources are rejected. | +| `subject_token.subject_token_type` | No | RFC 8693 `subject_token_type`. Defaults to `urn:ietf:params:oauth:token-type:access_token` for `provider_credential` and `urn:ietf:params:oauth:token-type:jwt` for `jwt_svid`. | +| `client_authentication` | No | `client_assertion` (default) sends the JWT-SVID as `client_assertion`. `none` omits `client_assertion` and `client_assertion_type`; it is only valid with `subject_token.source: jwt_svid` and cannot be combined with `client_assertion_type`. | | `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`. @@ -866,6 +868,35 @@ Token grants apply to HTTP traffic that the proxy can inspect. Token-grant profi The gateway authorizes the sandbox session and provider attachment on every request. In the dedicated path it also verifies the supervisor JWT-SVID issuer, audience, signature, and SPIFFE trust domain. In the shared path it resolves the configured credential itself and rechecks authorization before returning even a cached token. +### Google Cloud Through SPIFFE + +A credential can set `gce_metadata_token: true` next to its `token_grant` so unmodified Google SDKs using Application Default Credentials work without a stored key. The supervisor sets `GCE_METADATA_HOST` for the workload and its GCE metadata emulator returns a fixed placeholder access token. The SDK sends it as `Authorization: Bearer `, and the token grant replaces that header on the credential's endpoints. The placeholder never resolves to a value, so a request that carries it anywhere else is refused. `gce_metadata_token` requires a `token_grant` and `auth_style: bearer` on the `Authorization` header. A stored Google access token (`GCP_SA_ACCESS_TOKEN` or `GCP_ADC_ACCESS_TOKEN`) takes precedence over the placeholder. + +```yaml +id: google-cloud-spiffe +display_name: Google Cloud (SPIFFE) +credentials: + - name: wif_token + auth_style: bearer + header_name: Authorization + gce_metadata_token: true + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + jwt_svid_audience: //iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/spire/providers/spire + audience: //iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/spire/providers/spire + scopes: [https://www.googleapis.com/auth/cloud-platform] + requested_token_type: urn:ietf:params:oauth:token-type:access_token + client_authentication: none + subject_token: + source: jwt_svid + subject_token_type: urn:ietf:params:oauth:token-type:jwt +endpoints: + - { host: "*.googleapis.com", port: 443, protocol: rest, access: full } +``` + +The Workload Identity Federation provider must trust the SPIRE issuer, and IAM must grant the SPIFFE principal (`principal://iam.googleapis.com/projects//locations/global/workloadIdentityPools//subject/`) access to the resources. Requests that need a Google service account rather than a federated principal are not supported by this flow. + ### Token Grant Failures A failed grant returns HTTP 502 without forwarding the protected request. Connection setup, including an upstream TLS handshake, may already have completed. The workload response hides the cause; authorized sandbox readers can [diagnose the failure](/how-it-works/sandboxes/overview#read-token-grant-failures). The request ID correlates the response, sandbox status, and supervisor/gateway logs. OpenShell never logs the token service's `error` or `error_description`, which can echo credentials. diff --git a/examples/spiffe-gcp-sts-demo/README.md b/examples/spiffe-gcp-sts-demo/README.md new file mode 100644 index 0000000000..718793dd80 --- /dev/null +++ b/examples/spiffe-gcp-sts-demo/README.md @@ -0,0 +1,38 @@ + + + +# SPIFFE to Google STS Demo + +This example gives a sandbox Google Cloud access with no stored credential. The +supervisor exchanges its SPIFFE JWT-SVID at Google Security Token Service +(RFC 8693) and injects the federated access token on `*.googleapis.com`. + +1. SPIRE signs JWT-SVIDs with `jwt_issuer` set to a public HTTPS OIDC discovery + URL and an RS256 or ES256 key. +2. A Google Workload Identity Federation pool provider trusts that issuer. +3. IAM grants the sandbox's SPIFFE principal access, for example + `principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/onix-spire/subject/spiffe://example.org/ns/team/agent/app`. + +Replace `PROJECT_NUMBER` in `provider-profile.yaml`, then import the profile +and create a provider with no credentials: + +```shell +openshell profile lint -f examples/spiffe-gcp-sts-demo/provider-profile.yaml +openshell profile import -f examples/spiffe-gcp-sts-demo/provider-profile.yaml +openshell provider create --name gcp --type google-cloud-spiffe --runtime-credentials +``` + +Inside a sandbox with the provider attached, Google SDKs using Application +Default Credentials read a placeholder token from the OpenShell metadata +emulator. The supervisor replaces it with the federated token on Google API +requests. The STS request the supervisor sends is: + +```text +POST https://sts.googleapis.com/v1/token +grant_type=urn:ietf:params:oauth:grant-type:token-exchange +audience=//iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/onix-spire/providers/spire +scope=https://www.googleapis.com/auth/cloud-platform +requested_token_type=urn:ietf:params:oauth:token-type:access_token +subject_token_type=urn:ietf:params:oauth:token-type:jwt +subject_token= +``` diff --git a/examples/spiffe-gcp-sts-demo/provider-profile.yaml b/examples/spiffe-gcp-sts-demo/provider-profile.yaml new file mode 100644 index 0000000000..d2c3782334 --- /dev/null +++ b/examples/spiffe-gcp-sts-demo/provider-profile.yaml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Exchange the sandbox SPIFFE JWT-SVID at Google STS (Workload Identity +# Federation) and inject the federated access token on Google APIs. +# Replace PROJECT_NUMBER, the pool ID and the provider ID with your own. +id: google-cloud-spiffe +display_name: Google Cloud (SPIFFE Workload Identity Federation) +category: data +credentials: + - name: wif_token + auth_style: bearer + header_name: Authorization + gce_metadata_token: true + token_grant: + grant_type: token_exchange + token_endpoint: https://sts.googleapis.com/v1/token + jwt_svid_audience: //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/onix-spire/providers/spire + audience: //iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/onix-spire/providers/spire + scopes: [https://www.googleapis.com/auth/cloud-platform] + requested_token_type: urn:ietf:params:oauth:token-type:access_token + client_authentication: none + subject_token: + source: jwt_svid + subject_token_type: urn:ietf:params:oauth:token-type:jwt +endpoints: + - { host: "*.googleapis.com", port: 443, protocol: rest, access: full } diff --git a/proto/openshell.proto b/proto/openshell.proto index c01e88daf3..479b93b481 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -2550,16 +2550,32 @@ enum ProviderCredentialTokenGrantType { PROVIDER_CREDENTIAL_TOKEN_GRANT_TYPE_TOKEN_EXCHANGE = 2; } +// How the supervisor authenticates itself to the token endpoint. +enum ProviderCredentialTokenGrantClientAuthentication { + // Treated as CLIENT_ASSERTION for backwards compatibility. + PROVIDER_CREDENTIAL_TOKEN_GRANT_CLIENT_AUTHENTICATION_UNSPECIFIED = 0; + // Send the sandbox JWT-SVID as client_assertion. + PROVIDER_CREDENTIAL_TOKEN_GRANT_CLIENT_AUTHENTICATION_CLIENT_ASSERTION = 1; + // Send no client authentication. Only valid when the subject token is the + // sandbox JWT-SVID (subject_token.source "jwt_svid"). + PROVIDER_CREDENTIAL_TOKEN_GRANT_CLIENT_AUTHENTICATION_NONE = 2; +} + message ProviderCredentialTokenGrantSubjectToken { - // Source for the token exchange subject token. Phase one supports - // "provider_credential". + // Source for the token exchange subject token: + // "provider_credential": the gateway exchanges the stored provider + // credential named by `credential` (ExchangeProviderSubjectToken). + // "jwt_svid": the supervisor sends its own SPIFFE JWT-SVID, fetched with + // audience jwt_svid_audience, directly to the token endpoint. string source = 1; - // Provider credential key that stores the subject token. + // Provider credential key that stores the subject token. Required for + // "provider_credential"; must be empty for "jwt_svid". string credential = 2; // OAuth2 subject_token_type. If omitted, OpenShell uses - // urn:ietf:params:oauth:token-type:access_token. + // urn:ietf:params:oauth:token-type:access_token for "provider_credential" + // and urn:ietf:params:oauth:token-type:jwt for "jwt_svid". string subject_token_type = 3; } @@ -2599,6 +2615,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; + + // Client authentication sent to the token endpoint. If omitted/unspecified, + // OpenShell sends the JWT-SVID as client_assertion. + ProviderCredentialTokenGrantClientAuthentication client_authentication = 11; } // Provider credential declaration. @@ -2625,6 +2645,12 @@ message ProviderProfileCredential { // Gateway-managed refresh and token-grant credentials cannot opt in because // they require identity-bearing handles for authorization-epoch revocation. bool stable_placeholder = 12; + // Serve a non-secret placeholder access token for this token-grant + // credential from the sandbox GCE metadata emulator, so Google SDKs using + // Application Default Credentials send it as a bearer token. The token grant + // replaces it on the credential's endpoints; anywhere else the placeholder + // cannot be resolved and the request is refused. + bool gce_metadata_token = 13; } enum ProviderCredentialRefreshStrategy {