Skip to content

Commit f1acec3

Browse files
committed
feat(providers): exchange the sandbox JWT-SVID as a token grant subject
Add subject_token.source jwt_svid and client_authentication (client_assertion | none) to provider token grants so the sandbox JWT-SVID can be sent directly as the RFC 8693 subject_token, for example to Google STS for Workload Identity Federation. Invalid combinations are rejected at profile load. Dedicated supervisors perform the exchange without a gateway call; gateway-brokered grants for shared supervisors use the stable sandbox JWT-SVID. Grant flow resolution is shared in openshell-core. Add gce_metadata_token so the sandbox GCE metadata emulator serves a placeholder access token that the token grant replaces, letting unmodified Google SDKs using Application Default Credentials work. Closes #5897 Signed-off-by: paezba <64277512+paezba@users.noreply.github.com>
1 parent 1fca4c8 commit f1acec3

19 files changed

Lines changed: 1727 additions & 169 deletions

File tree

‎crates/openshell-core/src/google_cloud.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,21 @@ pub const GCP_SERVICE_ACCOUNT_EMAIL_CONFIG_KEY: &str = "service_account_email";
5252
/// credential precedence.
5353
pub const TOKEN_ENV_KEYS: &[&str] = &["GCP_SA_ACCESS_TOKEN", "GCP_ADC_ACCESS_TOKEN"];
5454

55+
/// Reserved key of the placeholder served for `gce_metadata_token` credentials.
56+
///
57+
/// No credential is stored under this key, so the placeholder never resolves:
58+
/// a token grant replaces it on the credential's endpoints, and anywhere else
59+
/// placeholder resolution refuses the request.
60+
pub const TOKEN_GRANT_PLACEHOLDER_ENV_KEY: &str = "OPENSHELL_GCE_METADATA_TOKEN_GRANT";
61+
62+
/// `expires_in` reported for the token grant placeholder.
63+
///
64+
/// Equal to the longest lifetime of a cached grant token (3600 s cap minus the
65+
/// 30 s refresh skew), so an SDK never holds the placeholder longer than the
66+
/// supervisor would hold the token it stands for. The supervisor obtains the
67+
/// real token independently on each request, so the value only paces refresh.
68+
pub const TOKEN_GRANT_PLACEHOLDER_EXPIRES_IN_SECONDS: i64 = 3570;
69+
5570
// ── Vertex-specific env vars ────────────────────────────────────────────────
5671

5772
/// Env var injected to signal Vertex AI usage to Goose.

‎crates/openshell-core/src/oauth.rs‎

Lines changed: 157 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ use crate::token_grant_failure::{
2222
pub const DEFAULT_CLIENT_ASSERTION_TYPE: &str =
2323
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
2424
pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
25+
/// RFC 8693 token type for a JWT, such as a SPIFFE JWT-SVID subject token.
26+
pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
2527
const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
2628
const ERROR_CONTRACT: &str = "openshell.token-grant.v1";
2729
const MAX_TOKEN_RESPONSE_BYTES: usize = 64 * 1024;
@@ -207,7 +209,9 @@ pub async fn post_oauth_token_grant(
207209
/// RFC 8693 token-exchange form fields.
208210
pub struct TokenExchangeParams<'a> {
209211
/// Secret JWT client assertion sent only to the configured endpoint.
210-
pub client_assertion: &'a str,
212+
/// `None` sends no client authentication: neither `client_assertion` nor
213+
/// `client_assertion_type` is included in the form.
214+
pub client_assertion: Option<&'a str>,
211215
pub client_assertion_type: &'a str,
212216
/// Secret subject credential to exchange for a resource token.
213217
pub subject_token: &'a str,
@@ -221,25 +225,29 @@ pub struct TokenExchangeParams<'a> {
221225
///
222226
/// Assembles the standard token-exchange form fields, applies defaults for
223227
/// `client_assertion_type`, `subject_token_type`, and `requested_token_type`,
224-
/// and conditionally includes `audience` and `scope`. A `request_id` is sent
225-
/// as the `x-openshell-request-id` header.
228+
/// and conditionally includes the client assertion, `audience` and `scope`.
229+
/// A `request_id` is sent as the `x-openshell-request-id` header.
226230
pub async fn post_oauth_token_exchange(
227231
client: &TokenGrantClient,
228232
token_endpoint: &str,
229233
params: &TokenExchangeParams<'_>,
230234
request_id: Option<&str>,
231235
) -> Result<OAuthTokenResponse, TokenGrantFailure> {
232-
let client_assertion_type = effective_client_assertion_type(params.client_assertion_type);
233236
let subject_token_type = effective_token_type(params.subject_token_type);
234237
let requested_token_type = effective_token_type(params.requested_token_type);
235-
let form_params = vec![
236-
("grant_type", TOKEN_EXCHANGE_GRANT_TYPE),
237-
("client_assertion_type", client_assertion_type),
238-
("client_assertion", params.client_assertion),
238+
let mut form_params = vec![("grant_type", TOKEN_EXCHANGE_GRANT_TYPE)];
239+
if let Some(client_assertion) = params.client_assertion {
240+
form_params.push((
241+
"client_assertion_type",
242+
effective_client_assertion_type(params.client_assertion_type),
243+
));
244+
form_params.push(("client_assertion", client_assertion));
245+
}
246+
form_params.extend([
239247
("subject_token", params.subject_token),
240248
("subject_token_type", subject_token_type),
241249
("requested_token_type", requested_token_type),
242-
];
250+
]);
243251
post_oauth_token_request(
244252
client,
245253
token_endpoint,
@@ -267,6 +275,94 @@ pub fn effective_token_type(token_type: &str) -> &str {
267275
}
268276
}
269277

278+
/// Subject token source resolved from a stored provider credential.
279+
pub const SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL: &str = "provider_credential";
280+
/// Subject token source that is the sandbox's own JWT-SVID.
281+
pub const SUBJECT_TOKEN_SOURCE_JWT_SVID: &str = "jwt_svid";
282+
283+
/// How a token grant uses the sandbox JWT-SVID, decided before any I/O.
284+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285+
pub enum TokenGrantFlow {
286+
/// RFC 7523 client credentials with the SVID as client assertion.
287+
ClientCredentials,
288+
/// RFC 8693 exchange of a stored provider credential, with the SVID as
289+
/// client assertion.
290+
ProviderCredentialSubjectExchange,
291+
/// RFC 8693 exchange of the SVID itself.
292+
JwtSvidSubjectExchange { client_assertion: bool },
293+
}
294+
295+
impl TokenGrantFlow {
296+
/// Resolve the flow, failing closed on unknown or inconsistent settings.
297+
///
298+
/// An empty subject source keeps the provider credential exchange, which
299+
/// predates the field.
300+
pub fn resolve(
301+
grant_type: crate::proto::ProviderCredentialTokenGrantType,
302+
subject_token_source: &str,
303+
client_authentication: Option<
304+
&crate::proto::ProviderCredentialTokenGrantClientAuthentication,
305+
>,
306+
) -> Result<Self, TokenGrantFailure> {
307+
use crate::proto::ProviderCredentialTokenGrantType as GrantType;
308+
let configuration = || {
309+
TokenGrantFailure::new(
310+
TokenGrantFailureKind::Configuration,
311+
TokenGrantStage::Configuration,
312+
)
313+
};
314+
let client_assertion =
315+
resolve_client_assertion(client_authentication).ok_or_else(configuration)?;
316+
match (grant_type, subject_token_source.trim()) {
317+
(GrantType::ClientCredentials | GrantType::Unspecified, _) if client_assertion => {
318+
Ok(Self::ClientCredentials)
319+
}
320+
(GrantType::TokenExchange, "" | SUBJECT_TOKEN_SOURCE_PROVIDER_CREDENTIAL)
321+
if client_assertion =>
322+
{
323+
Ok(Self::ProviderCredentialSubjectExchange)
324+
}
325+
(GrantType::TokenExchange, SUBJECT_TOKEN_SOURCE_JWT_SVID) => {
326+
Ok(Self::JwtSvidSubjectExchange { client_assertion })
327+
}
328+
_ => Err(configuration()),
329+
}
330+
}
331+
}
332+
333+
/// Whether client authentication sends a `client_assertion`.
334+
///
335+
/// Absent authentication keeps the original behavior, an assertion made from
336+
/// the sandbox JWT-SVID. Returns `None` for an unknown mechanism, an
337+
/// unsupported credential source, or a credential on mechanism `none`.
338+
pub fn resolve_client_assertion(
339+
client_authentication: Option<&crate::proto::ProviderCredentialTokenGrantClientAuthentication>,
340+
) -> Option<bool> {
341+
use crate::proto::ProviderCredentialTokenGrantClientAuthenticationMechanism as Mechanism;
342+
let Some(authentication) = client_authentication else {
343+
return Some(true);
344+
};
345+
let source = authentication
346+
.credential
347+
.as_ref()
348+
.map_or("", |credential| credential.source.trim());
349+
match Mechanism::try_from(authentication.mechanism).ok()? {
350+
Mechanism::Unspecified | Mechanism::ClientAssertion => {
351+
(source.is_empty() || source == SUBJECT_TOKEN_SOURCE_JWT_SVID).then_some(true)
352+
}
353+
Mechanism::None => (authentication.credential.is_none()).then_some(false),
354+
}
355+
}
356+
357+
/// Subject token type for a JWT-SVID subject; defaults to [`JWT_TOKEN_TYPE`].
358+
pub fn effective_jwt_svid_subject_token_type(subject_token_type: &str) -> &str {
359+
if subject_token_type.trim().is_empty() {
360+
JWT_TOKEN_TYPE
361+
} else {
362+
subject_token_type
363+
}
364+
}
365+
270366
/// Cache lifetime for a granted access token.
271367
///
272368
/// A configured override is used exactly, including zero to disable caching.
@@ -885,7 +981,7 @@ mod tests {
885981
&client,
886982
&endpoint,
887983
&TokenExchangeParams {
888-
client_assertion: "jwt-svid-token",
984+
client_assertion: Some("jwt-svid-token"),
889985
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe",
890986
subject_token: "subject-access-token",
891987
subject_token_type: ACCESS_TOKEN_TYPE,
@@ -942,6 +1038,56 @@ mod tests {
9421038
);
9431039
}
9441040

1041+
#[tokio::test]
1042+
async fn token_exchange_without_client_authentication_omits_client_assertion() {
1043+
let (endpoint, request) = token_endpoint_once(
1044+
"200 OK",
1045+
r#"{"access_token":"federated-token","token_type":"Bearer","expires_in":3599}"#,
1046+
)
1047+
.await;
1048+
let scopes = vec!["https://www.googleapis.com/auth/cloud-platform".to_string()];
1049+
let audience = "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/p/providers/spire";
1050+
1051+
let response = post_oauth_token_exchange(
1052+
&test_client(),
1053+
&endpoint,
1054+
&TokenExchangeParams {
1055+
client_assertion: None,
1056+
// Ignored without a client assertion.
1057+
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
1058+
subject_token: "header.svid.signature",
1059+
subject_token_type: JWT_TOKEN_TYPE,
1060+
audience,
1061+
scopes: &scopes,
1062+
requested_token_type: ACCESS_TOKEN_TYPE,
1063+
},
1064+
None,
1065+
)
1066+
.await
1067+
.expect("token exchange should succeed");
1068+
let request = request.await.expect("endpoint task");
1069+
1070+
assert_eq!(response.access_token, "federated-token");
1071+
assert!(!request.form.contains_key("client_assertion"));
1072+
assert!(!request.form.contains_key("client_assertion_type"));
1073+
let expected = HashMap::from([
1074+
("grant_type", TOKEN_EXCHANGE_GRANT_TYPE),
1075+
("audience", audience),
1076+
("scope", "https://www.googleapis.com/auth/cloud-platform"),
1077+
("requested_token_type", ACCESS_TOKEN_TYPE),
1078+
("subject_token_type", JWT_TOKEN_TYPE),
1079+
("subject_token", "header.svid.signature"),
1080+
]);
1081+
assert_eq!(
1082+
request
1083+
.form
1084+
.iter()
1085+
.map(|(name, value)| (name.as_str(), value.as_str()))
1086+
.collect::<HashMap<_, _>>(),
1087+
expected
1088+
);
1089+
}
1090+
9451091
#[tokio::test]
9461092
async fn token_exchange_applies_defaults_for_empty_type_fields() {
9471093
let (endpoint, request) =
@@ -952,7 +1098,7 @@ mod tests {
9521098
&client,
9531099
&endpoint,
9541100
&TokenExchangeParams {
955-
client_assertion: "jwt-svid-token",
1101+
client_assertion: Some("jwt-svid-token"),
9561102
client_assertion_type: "",
9571103
subject_token: "subject-token",
9581104
subject_token_type: "",

0 commit comments

Comments
 (0)