Skip to content
Open
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
58 changes: 37 additions & 21 deletions crates/core/src/oauth2_client/token_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,10 @@ pub enum TokenExchangeError {
#[error("subject_token's context has no resolved authorization scope")]
NoAuthorization,

/// The validated subject token has no expiry to bound the exchanged token.
#[error("subject_token has no expiration")]
MissingSubjectTokenExpiry,

/// The credential-chain expiry is not later than the new token's issue
/// time. Subject token/App Cred has either already expired or expires
/// at/before the new token's issue time.
/// The resulting expiry is not later than the new token's issue time:
/// the subject token or application credential has already expired (or
/// expires at/before the issue time), or the default lifetime passed in
/// leaves no positive lifetime.
#[error("credential-chain expiry does not leave a positive token lifetime")]
CredentialChainExpired,

Expand Down Expand Up @@ -158,6 +155,14 @@ pub async fn validate_subject_token(
/// [`DelegationContext`]. `aud` is [`Audience::control_plane`] unless the
/// request narrowed it to service types (ADR 0036 §7.1).
///
/// `default_exp` is the default expiry (`iat` + configured access-token
/// lifetime).
/// The issued `exp` is the minimum of it, the subject token's expiry and the
/// application credential's expiry, ignoring any of the latter two that are
/// absent. A token is therefore always issued with an expiration, and the
/// token endpoint reports `expires_in` from the resulting `exp` (RFC 6749
/// §5.1, as used by RFC 8693 §2.2.1).
///
/// # Errors
/// See [`TokenExchangeError`] for each rejection reason.
#[allow(clippy::too_many_arguments)]
Expand All @@ -169,7 +174,7 @@ pub fn build_token_exchange_claims(
issuer: &str,
jti: String,
iat: i64,
exp: i64,
default_exp: i64,
aud: Audience,
) -> Result<OpenStackAccessTokenClaims, TokenExchangeError> {
let principal = vsc.inner().principal();
Expand Down Expand Up @@ -200,13 +205,10 @@ pub fn build_token_exchange_claims(
return Err(TokenExchangeError::CrossDomainSubjectToken);
}

let subject_expires_at = vsc
.inner()
.expires_at()
.ok_or(TokenExchangeError::MissingSubjectTokenExpiry)?
.timestamp();

let mut exp = exp.min(subject_expires_at);
let mut exp = default_exp;
if let Some(subject_expires_at) = vsc.inner().expires_at() {
exp = exp.min(subject_expires_at.timestamp());
}
if let Some(credential_expires_at) = credential_expiration {
exp = exp.min(credential_expires_at.timestamp());
}
Expand Down Expand Up @@ -482,7 +484,7 @@ mod tests {
fn build_claims_with_expiries(
subject_expires_at: Option<chrono::DateTime<chrono::Utc>>,
app_cred_expires_at: Option<chrono::DateTime<chrono::Utc>>,
requested_exp: i64,
default_exp: i64,
) -> Result<OpenStackAccessTokenClaims, TokenExchangeError> {
let ctx = app_cred_context("project-1", app_cred_expires_at);
let (delegation, credential_expiration) = derive_delegation_context(&ctx).unwrap();
Expand All @@ -495,7 +497,7 @@ mod tests {
"https://ks.example/v4/oauth2/domain-1",
"jti-1".to_string(),
1000,
requested_exp,
default_exp,
Audience::control_plane(),
)
}
Expand Down Expand Up @@ -537,11 +539,25 @@ mod tests {
}

#[test]
fn test_build_token_exchange_claims_rejects_missing_subject_expiry() {
let app_cred_expiry = Some(chrono::DateTime::from_timestamp(2000, 0).unwrap());
fn test_build_token_exchange_claims_applies_default_when_no_expiry_present() {
let at = |ts| Some(chrono::DateTime::from_timestamp(ts, 0).unwrap());

// Neither subject token nor app cred expires; default applied.
let claims = build_claims_with_expiries(None, None, 1900).unwrap();
assert_eq!(claims.exp, 1900);

// No subject expiry, app cred expires later than the default.
let claims = build_claims_with_expiries(None, at(2100), 1900).unwrap();
assert_eq!(claims.exp, 1900);

// No subject expiry, app cred expires sooner than the default.
let claims = build_claims_with_expiries(None, at(1500), 1900).unwrap();
assert_eq!(claims.exp, 1500);

// An already-expired app cred is still rejected without a subject expiry.
assert!(matches!(
build_claims_with_expiries(None, app_cred_expiry, 1900),
Err(TokenExchangeError::MissingSubjectTokenExpiry)
build_claims_with_expiries(None, at(1000), 1900),
Err(TokenExchangeError::CredentialChainExpired)
));
}

Expand Down
32 changes: 26 additions & 6 deletions crates/keystone/src/api/v4/oauth2/token/token_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ pub(super) async fn handle_token_exchange_grant(
let issuer = format!("{base}/v4/oauth2/{domain_id}");
let now = chrono::Utc::now().timestamp();
let access_lifetime = i64::from(oauth2_cfg.access_token_lifetime_minutes) * 60;
if access_lifetime <= 0 {
tracing::error!("oauth2 access_token_lifetime_minutes must be greater than zero");
return Err(Oauth2TokenError::internal("token issuance failed"));
}
let jti = uuid::Uuid::new_v4().to_string();

let mut claims = openstack_keystone_core::oauth2_client::build_token_exchange_claims(
Expand Down Expand Up @@ -172,8 +176,9 @@ pub(super) async fn handle_token_exchange_grant(
Ok((StatusCode::OK, Json(response)).into_response())
}

/// RFC 8693 §2.2.2: invalid subjects use invalid_request; provider failures
/// are server errors rather than evidence of invalid credentials.
/// RFC 8693 §2.2.2: a request whose subject_token is invalid for any reason
/// (expired, revoked, not delegated, outside policy) is `invalid_request`.
/// Provider failures are server errors, not evidence of a bad credential.
fn exchange_error(
error: openstack_keystone_core::oauth2_client::TokenExchangeError,
) -> Oauth2TokenError {
Expand All @@ -199,9 +204,6 @@ fn exchange_error(
TokenExchangeError::CrossDomainSubjectToken => Oauth2TokenError::invalid_request(
"subject_token's scope belongs to a different domain than this token endpoint",
),
TokenExchangeError::MissingSubjectTokenExpiry => Oauth2TokenError::invalid_request(
"subject_token is missing an expiry claim, cannot be exchanged",
),
TokenExchangeError::CredentialChainExpired => Oauth2TokenError::invalid_request(
"subject_token or application credential expiry does not permit token exchange",
),
Expand All @@ -216,7 +218,6 @@ fn exchange_error(
_ => Oauth2TokenError::internal("token issuance failed"),
}
}

/// Whether `token` is a JWT whose payload has a `cnf` claim, or one whose
/// payload cannot be read. The payload is read without verifying anything:
/// the caller has already validated the token and only uses this to fail
Expand Down Expand Up @@ -1341,4 +1342,23 @@ mod tests {
assert!(subject_token_carries_cnf(&jwt("not json")));
assert!(subject_token_carries_cnf(&jwt("[1]")));
}

#[tokio::test]
async fn test_exchange_error_variants() {
use openstack_keystone_core::oauth2_client::TokenExchangeError;

let client_side = [
TokenExchangeError::NotAUserPrincipal,
TokenExchangeError::NoAuthorization,
TokenExchangeError::NoDelegationProject,
TokenExchangeError::CrossDomainSubjectToken,
TokenExchangeError::UnsupportedDelegation("ec2"),
];
for error in client_side {
let label = format!("{error:?}");
let mapped = super::exchange_error(error);
assert_eq!(mapped.status(), StatusCode::BAD_REQUEST, "{label}");
assert_eq!(mapped.error_code(), "invalid_request", "{label}");
}
}
}
13 changes: 7 additions & 6 deletions doc/src/adr/0026-oauth2-oidc-provider.md
Original file line number Diff line number Diff line change
Expand Up @@ -1728,12 +1728,13 @@ The grant above is now built, as the follow-up amendment this section itself
anticipated. Concrete choices made during implementation:

- **Expiry bounded by the credential chain.** The exchanged access token's
`exp` is capped at the earliest of the configured access-token lifetime, the
validated `subject_token` expiry, and the application credential's expiry.
Both credential expiries must be present; a missing expiry or a resulting
non-positive lifetime is rejected as `invalid_grant`. The response's
`expires_in` reports the capped lifetime, so repeated exchanges cannot extend
a delegated credential past its configured expiry.
`exp` is capped at the earliest of the configured access-token lifetime and
any expiry present on the validated `subject_token` and its application
credential. A credential without an expiry does not further constrain the
token; if neither credential expires, the configured access-token lifetime
applies. A resulting non-positive lifetime is rejected as `invalid_grant`.
The response's `expires_in` reports the capped lifetime, so repeated
exchanges cannot extend a delegated credential past its configured expiry.
- **`AppCred` only, not `Trust` or `Ec2`.** Only `ApplicationCredential`'s
immutable project (`ApplicationCredential.project_id`) is carried on the
object embedded in `AuthenticationContext::ApplicationCredential` once
Expand Down
2 changes: 1 addition & 1 deletion doc/src/adr/0036-service-delegation.md
Original file line number Diff line number Diff line change
Expand Up @@ -1394,4 +1394,4 @@ will stop carrying scope.
`keystone-rs`.
- **New state and a new driver crate**, plus one more `AuthenticationContext`
pair to keep in every match arm. The ADR 0017 checklist and compile-time
exhaustive matches make omissions a build error rather than a runtime hole.
exhaustive matches make omissions a build error rather than a runtime hole.
23 changes: 19 additions & 4 deletions tests/integration/src/oauth2_token_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,19 @@ async fn test_token_exchange_full_flow_issues_app_cred_delegated_claims() -> Res

let (vsc, delegation, credential_expiration) =
validate_subject_token(&state, &subject_token).await?;
let iat = chrono::Utc::now().timestamp();
let default_exp = iat + 900;
assert!(
vsc.inner()
.expires_at()
.is_some_and(|subject_exp| subject_exp.timestamp() > default_exp),
"validated subject token must outlive the configured default"
);
assert!(
credential_expiration
.is_some_and(|credential_exp| credential_exp.timestamp() > default_exp),
"application credential must outlive the configured default"
);
let issuer = format!("https://ks.example/v4/oauth2/{}", domain.id);
let claims = build_token_exchange_claims(
&client,
Expand All @@ -197,12 +210,14 @@ async fn test_token_exchange_full_flow_issues_app_cred_delegated_claims() -> Res
credential_expiration,
&issuer,
Uuid::new_v4().to_string(),
chrono::Utc::now().timestamp(),
chrono::Utc::now().timestamp() + 900,
iat,
default_exp,
Audience::control_plane(),
)?;

assert_eq!(claims.aud, Audience::control_plane());
assert_eq!(claims.iat, iat);
assert_eq!(claims.exp, default_exp);
assert!(claims.amr.contains(&"application_credential".to_string()));

Ok(())
Expand All @@ -229,8 +244,8 @@ async fn test_token_exchange_caps_expiry_at_short_lived_app_credential() -> Resu
credential_expiration,
&issuer,
Uuid::new_v4().to_string(),
chrono::Utc::now().timestamp(),
chrono::Utc::now().timestamp() + 900,
now,
now + 900,
Audience::control_plane(),
)?;

Expand Down
Loading