Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/openshell-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ pub mod shell;
pub mod telemetry;
pub mod time;
pub mod token_endpoint;
pub mod token_grant_config;
pub mod token_grant_failure;
pub mod transport_errors;
pub mod upload;
Expand Down
97 changes: 86 additions & 11 deletions crates/openshell-core/src/oauth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::token_grant_failure::{
pub const DEFAULT_CLIENT_ASSERTION_TYPE: &str =
"urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
pub use crate::token_grant_config::JWT_TOKEN_TYPE;
const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
const ERROR_CONTRACT: &str = "openshell.token-grant.v1";
const MAX_TOKEN_RESPONSE_BYTES: usize = 64 * 1024;
Expand Down Expand Up @@ -204,11 +205,37 @@ pub async fn post_oauth_token_grant(
.await
}

/// Authentication to the external token endpoint, independent of the subject.
#[derive(Clone, Copy)]
pub enum ClientAuthentication<'a> {
None,
ClientAssertion {
assertion: &'a str,
assertion_type: &'a str,
},
}

impl<'a> ClientAuthentication<'a> {
/// Resolve a validated profile's authentication using the acquired SVID.
pub fn from_config(
config: Option<&crate::proto::ProviderCredentialTokenGrantClientAuthentication>,
svid: &'a str,
assertion_type: &'a str,
) -> Self {
if config.is_some_and(|auth| auth.mechanism == "none") {
Self::None
} else {
Self::ClientAssertion {
assertion: svid,
assertion_type,
}
}
}
}

/// RFC 8693 token-exchange form fields.
pub struct TokenExchangeParams<'a> {
/// Secret JWT client assertion sent only to the configured endpoint.
pub client_assertion: &'a str,
pub client_assertion_type: &'a str,
pub client_authentication: ClientAuthentication<'a>,
/// Secret subject credential to exchange for a resource token.
pub subject_token: &'a str,
pub subject_token_type: &'a str,
Expand All @@ -229,17 +256,25 @@ pub async fn post_oauth_token_exchange(
params: &TokenExchangeParams<'_>,
request_id: Option<&str>,
) -> Result<OAuthTokenResponse, TokenGrantFailure> {
let client_assertion_type = effective_client_assertion_type(params.client_assertion_type);
let subject_token_type = effective_token_type(params.subject_token_type);
let requested_token_type = effective_token_type(params.requested_token_type);
let form_params = vec![
let mut form_params = vec![
("grant_type", TOKEN_EXCHANGE_GRANT_TYPE),
("client_assertion_type", client_assertion_type),
("client_assertion", params.client_assertion),
("subject_token", params.subject_token),
("subject_token_type", subject_token_type),
("requested_token_type", requested_token_type),
];
if let ClientAuthentication::ClientAssertion {
assertion,
assertion_type,
} = params.client_authentication
{
form_params.push(("client_assertion", assertion));
form_params.push((
"client_assertion_type",
effective_client_assertion_type(assertion_type),
));
}
post_oauth_token_request(
client,
token_endpoint,
Expand Down Expand Up @@ -459,6 +494,7 @@ mod tests {

#[derive(Debug)]
struct CapturedRequest {
authorization: Option<String>,
form: HashMap<String, String>,
request_id: Option<String>,
}
Expand Down Expand Up @@ -508,6 +544,11 @@ mod tests {
});
let form_body = String::from_utf8_lossy(&buf[header_end..]);
CapturedRequest {
authorization: headers.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("authorization")
.then(|| value.trim().to_string())
}),
form: parse_form_body(&form_body),
request_id,
}
Expand Down Expand Up @@ -790,6 +831,36 @@ mod tests {
server.await.expect("bound fixture");
}

#[tokio::test]
async fn jwt_subject_exchange_without_client_authentication() {
let (endpoint, request) = token_endpoint_once(
"200 OK",
r#"{"access_token":"google-token","expires_in":3600}"#,
)
.await;
post_oauth_token_exchange(&test_client(), &endpoint, &TokenExchangeParams {
client_authentication: ClientAuthentication::None,
subject_token: "sandbox-jwt-svid",
subject_token_type: JWT_TOKEN_TYPE,
audience: "//iam.googleapis.com/projects/1/locations/global/workloadIdentityPools/pool/providers/spire",
scopes: &["https://www.googleapis.com/auth/cloud-platform".into()],
requested_token_type: "",
}, None).await.expect("exchange");
let request = request.await.unwrap();
assert!(request.authorization.is_none());
assert_eq!(request.form.len(), 6);
assert_eq!(request.form["grant_type"], TOKEN_EXCHANGE_GRANT_TYPE);
assert_eq!(request.form["subject_token"], "sandbox-jwt-svid");
assert_eq!(request.form["subject_token_type"], JWT_TOKEN_TYPE);
assert_eq!(request.form["requested_token_type"], ACCESS_TOKEN_TYPE);
assert_eq!(
request.form["scope"],
"https://www.googleapis.com/auth/cloud-platform"
);
assert!(!request.form.contains_key("client_assertion"));
assert!(!request.form.contains_key("client_assertion_type"));
}

#[tokio::test]
async fn posts_form_params_and_parses_success_response() {
let (endpoint, request) = token_endpoint_once(
Expand Down Expand Up @@ -885,8 +956,10 @@ mod tests {
&client,
&endpoint,
&TokenExchangeParams {
client_assertion: "jwt-svid-token",
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe",
client_authentication: ClientAuthentication::ClientAssertion {
assertion: "jwt-svid-token",
assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe",
},
subject_token: "subject-access-token",
subject_token_type: ACCESS_TOKEN_TYPE,
audience: "api://resource",
Expand Down Expand Up @@ -952,8 +1025,10 @@ mod tests {
&client,
&endpoint,
&TokenExchangeParams {
client_assertion: "jwt-svid-token",
client_assertion_type: "",
client_authentication: ClientAuthentication::ClientAssertion {
assertion: "jwt-svid-token",
assertion_type: "",
},
subject_token: "subject-token",
subject_token_type: "",
audience: "",
Expand Down
58 changes: 56 additions & 2 deletions crates/openshell-core/src/provider_credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -701,15 +701,42 @@ impl ProviderCredentialState {
/// Searches `google_cloud::TOKEN_ENV_KEYS` in priority order (SA before
/// ADC) atomically to avoid inconsistency during credential
/// refresh. Returns `None` if no GCP token is configured or all are
/// expired. The `expires_in` defaults to 3600 when expiry is unknown.
/// expired. Dynamic grants return a placeholder with a 3600-second SDK
/// refresh interval; their real token expiry is managed by the grant cache.
/// Static credentials also default to 3600 when expiry is unknown.
pub fn gcp_token_response(&self) -> Option<(String, i64)> {
const DEFAULT_EXPIRES_IN: i64 = 3600;
let inner = self
.inner
.read()
.expect("provider credential state poisoned");
let resolver = inner.current_resolver.as_ref()?;
for key in crate::google_cloud::TOKEN_ENV_KEYS {
// A dynamic grant has no static secret to unwrap. Its placeholder
// is replaced only after endpoint admission by token-grant injection.
if inner
.current
.dynamic_credentials
.values()
.any(|credential| {
credential.env_vars.iter().any(|env| env == key)
&& credential.auth_style == "bearer"
&& !credential.token_grant_owners.is_empty()
&& credential.token_grant.as_ref().is_some_and(|grant| {
crate::token_grant_config::validate_token_grant_identity(grant).is_ok()
})
})
{
return Some((
crate::secrets::placeholder_for_env_key_for_revision(
key,
inner.current.revision,
),
DEFAULT_EXPIRES_IN,
));
}
let Some(resolver) = inner.current_resolver.as_ref() else {
continue;
};
let Some(placeholder) = inner.current.child_env.get(*key).cloned() else {
continue;
};
Expand Down Expand Up @@ -3511,6 +3538,33 @@ mod tests {
);
}

#[test]
fn gcp_token_response_serves_dynamic_placeholder_and_revokes_on_detach() {
let declaration = crate::proto::ProviderProfileCredential {
name: "access_token".into(),
env_vars: vec!["GCP_ADC_ACCESS_TOKEN".into()],
auth_style: "bearer".into(),
token_grant_owners: vec!["owner".into()],
token_grant: Some(crate::proto::ProviderCredentialTokenGrant {
token_endpoint: "https://sts.googleapis.com/v1/token".into(),
..Default::default()
}),
..Default::default()
};
let state = ProviderCredentialState::from_environment(
7,
HashMap::new(),
HashMap::new(),
HashMap::from([("gcp:access_token".into(), declaration)]),
);
let (placeholder, lifetime) = state.gcp_token_response().expect("dynamic metadata");
assert_eq!(placeholder, "openshell:resolve:env:v7_GCP_ADC_ACCESS_TOKEN");
assert_eq!(lifetime, 3600);
assert!(state.snapshot().child_env.is_empty());
state.install_environment(8, HashMap::new(), HashMap::new(), HashMap::new());
assert!(state.gcp_token_response().is_none());
}

#[test]
fn gcp_token_response_returns_sa_over_adc() {
let state = ProviderCredentialState::from_environment(
Expand Down
115 changes: 115 additions & 0 deletions crates/openshell-core/src/token_grant_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Pure validation for token-grant identity configuration.

pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";

/// A profile field and a credential-free validation diagnostic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TokenGrantIdentityError {
pub field: &'static str,
pub message: &'static str,
}

const fn invalid(field: &'static str, message: &'static str) -> TokenGrantIdentityError {
TokenGrantIdentityError { field, message }
}

/// Validate identity choices before acquiring credentials or serving cached tokens.
pub fn validate_token_grant_identity(
grant: &crate::proto::ProviderCredentialTokenGrant,
) -> Result<(), TokenGrantIdentityError> {
use crate::proto::ProviderCredentialTokenGrantType as Grant;
let kind = Grant::try_from(grant.grant_type)
.map_err(|_| invalid("grant_type", "unsupported grant_type"))?;
if let Some(auth) = &grant.client_authentication {
match auth.mechanism.as_str() {
"none" => {
if auth.credential.is_some() {
return Err(invalid(
"client_authentication.credential",
"client_authentication none forbids credential",
));
}
if !grant.client_assertion_type.is_empty() {
return Err(invalid(
"client_assertion_type",
"client_assertion_type requires client_assertion authentication",
));
}
if kind != Grant::TokenExchange {
return Err(invalid(
"client_authentication.mechanism",
"client_credentials requires client_assertion authentication",
));
}
}
"client_assertion" => {
if auth
.credential
.as_ref()
.is_none_or(|credential| credential.source != "jwt_svid")
{
return Err(invalid(
"client_authentication.credential.source",
"client_assertion requires credential.source: jwt_svid",
));
}
}
_ => {
return Err(invalid(
"client_authentication.mechanism",
"unsupported client_authentication.mechanism",
));
}
}
}
if kind != Grant::TokenExchange {
return if grant.subject_token.is_some() {
Err(invalid(
"subject_token",
"subject_token is only valid for token_exchange grants",
))
} else {
Ok(())
};
}
let subject = grant.subject_token.as_ref().ok_or(invalid(
"subject_token",
"token_exchange grants require subject_token",
))?;
match subject.source.as_str() {
"provider_credential" => {
if subject.credential.trim().is_empty() {
return Err(invalid(
"subject_token.credential",
"subject_token.credential is required",
));
}
}
"jwt_svid" => {
if !subject.credential.is_empty() {
return Err(invalid(
"subject_token.credential",
"jwt_svid subject forbids subject_token.credential",
));
}
if !subject.subject_token_type.is_empty()
&& subject.subject_token_type != JWT_TOKEN_TYPE
{
return Err(invalid(
"subject_token.subject_token_type",
"jwt_svid subject requires the JWT subject_token_type",
));
}
}
_ => {
return Err(invalid(
"subject_token.source",
"subject_token.source must be provider_credential or jwt_svid",
));
}
}
Ok(())
}
7 changes: 5 additions & 2 deletions crates/openshell-core/tests/oauth_error_logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,11 @@ async fn rejected_grant_log_omits_token_service_error_text() {
&client,
&endpoint,
&TokenExchangeParams {
client_assertion: "jwt-svid-token",
client_assertion_type: "",
client_authentication:
openshell_core::oauth::ClientAuthentication::ClientAssertion {
assertion: "jwt-svid-token",
assertion_type: "",
},
subject_token: CANARY,
subject_token_type: "",
audience: "",
Expand Down
Loading