use serde::{Deserialize, Serialize};
use uuid::Uuid;
use super::discovery::OidcConfiguration;
use super::exchange::oauth2_error_or_fallback;
use crate::client::AxiamClient;
use crate::error::AxiamError;
use crate::sensitive::Sensitive;
pub const TOKEN_EXCHANGE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:token-exchange";
pub const ACCESS_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:access_token";
pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
#[derive(Serialize)]
struct TokenExchangeForm<'a> {
grant_type: &'a str,
subject_token: &'a str,
subject_token_type: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
actor_token: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
actor_token_type: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
scope: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
audience: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
resource: Option<&'a str>,
client_id: &'a str,
client_secret: &'a str,
}
#[derive(Deserialize)]
struct TokenExchangeResponseWire {
access_token: String,
issued_token_type: String,
token_type: String,
expires_in: u64,
#[serde(default)]
scope: Option<String>,
}
pub struct TokenExchangeParams {
pub subject_token: Sensitive<String>,
pub subject_token_type: String,
pub actor_token: Option<Sensitive<String>>,
pub scopes: Option<Vec<String>>,
pub audience: Option<String>,
pub resource: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
impl TokenExchangeParams {
pub fn new(subject_token: Sensitive<String>, subject_token_type: impl Into<String>) -> Self {
Self {
subject_token,
subject_token_type: subject_token_type.into(),
actor_token: None,
scopes: None,
audience: None,
resource: None,
tenant_id: None,
configuration: None,
}
}
}
#[derive(Debug, Clone)]
pub struct ExchangedToken {
pub access_token: Sensitive<String>,
pub issued_token_type: String,
pub token_type: String,
pub expires_in: u64,
pub scope: Option<String>,
}
impl AxiamClient {
pub async fn token_exchange(
&self,
params: TokenExchangeParams,
) -> Result<ExchangedToken, AxiamError> {
let configuration = match params.configuration {
Some(c) => c,
None => self.oidc_discover().await?,
};
let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
let client_id = self.oidc_client_id_or_err()?.to_string();
let client_secret = self.oidc_client_secret_or_err("token_exchange")?;
let endpoint = self.mtls_preferred(
&configuration,
|a| a.token_endpoint.as_deref(),
&configuration.token_endpoint,
)?;
let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
let scope = params.scopes.as_ref().map(|s| s.join(" "));
let actor = params.actor_token.as_ref().map(|t| t.expose().as_str());
let form = TokenExchangeForm {
grant_type: TOKEN_EXCHANGE_GRANT_TYPE,
subject_token: params.subject_token.expose().as_str(),
subject_token_type: params.subject_token_type.as_str(),
actor_token: actor,
actor_token_type: actor.map(|_| ACCESS_TOKEN_TYPE),
scope: scope.as_deref(),
audience: params.audience.as_deref(),
resource: params.resource.as_deref(),
client_id: &client_id,
client_secret: &client_secret,
};
let response = self
.idp_form_post(url)
.form(&form)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("token exchange request failed: {e}"),
source: Some(Box::new(e)),
})?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
let wire: TokenExchangeResponseWire =
response.json().await.map_err(|e| AxiamError::Network {
message: format!("failed to parse token exchange response: {e}"),
source: Some(Box::new(e)),
})?;
Ok(ExchangedToken {
access_token: Sensitive::new(wire.access_token),
issued_token_type: wire.issued_token_type,
token_type: wire.token_type,
expires_in: wire.expires_in,
scope: wire.scope,
})
}
}
#[cfg(test)]
mod wire_redaction_tests {
#[test]
fn no_wire_struct_holding_a_secret_is_debug() {
assert!(
!crate::sensitive::implements_debug!(super::TokenExchangeResponseWire),
"TokenExchangeResponseWire is Debug"
);
}
}