use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::rest::auth::CsrfHeaderExt;
use super::discovery::{MtlsEndpointAliases, OidcConfiguration};
use super::id_token::{IdTokenClaims, IdTokenExpectations, check_id_token_claims};
pub const SSO_START_PATH: &str = "/api/v1/auth/federation/oidc/start";
pub const SSO_CALLBACK_PATH: &str = "/api/v1/auth/federation/oidc/callback";
#[derive(Serialize)]
struct TokenRequestForm<'a> {
grant_type: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
code: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
code_verifier: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
redirect_uri: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
refresh_token: Option<&'a str>,
client_id: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
client_secret: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
scope: Option<&'a str>,
}
#[derive(Serialize)]
struct IntrospectOrRevokeForm<'a> {
token: &'a str,
client_id: &'a str,
client_secret: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
token_type_hint: Option<&'a str>,
}
#[derive(Deserialize)]
pub(crate) struct TokenResponseWire {
pub(crate) access_token: String,
pub(crate) token_type: String,
pub(crate) expires_in: u64,
#[serde(default)]
pub(crate) scope: Option<String>,
#[serde(default)]
pub(crate) refresh_token: Option<String>,
#[serde(default)]
pub(crate) id_token: Option<String>,
}
#[derive(Debug, Deserialize)]
struct IntrospectionResponseWire {
active: bool,
#[serde(default)]
sub: Option<String>,
#[serde(default)]
client_id: Option<String>,
#[serde(default)]
scope: Option<String>,
#[serde(default)]
token_type: Option<String>,
#[serde(default)]
exp: Option<i64>,
#[serde(default)]
iat: Option<i64>,
}
#[derive(Debug, Deserialize)]
struct OAuth2ErrorResponseWire {
error: String,
#[serde(default)]
error_description: String,
}
#[derive(Serialize)]
struct OidcStartRequestWire {
federation_config_id: String,
redirect_uri: String,
#[serde(skip_serializing_if = "Option::is_none")]
tenant_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
tenant_slug: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
org_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
org_slug: Option<String>,
}
#[derive(Debug, Deserialize)]
struct OidcStartResponseWire {
authorize_url: String,
state: String,
expires_in_secs: u64,
}
#[derive(Serialize)]
struct OidcPublicCallbackRequestWire<'a> {
state: &'a str,
code: &'a str,
}
#[derive(Debug, Deserialize)]
struct SsoLoginSuccessResponseWire {
user_id: Uuid,
session_id: Uuid,
expires_in: u64,
redirect_uri: String,
}
#[derive(Debug, Clone)]
pub struct OidcTokenSet {
pub access_token: Sensitive<String>,
pub token_type: String,
pub expires_in: u64,
pub scope: Option<String>,
pub refresh_token: Option<Sensitive<String>>,
pub id_token: Option<Sensitive<String>>,
pub id_claims: Option<IdTokenClaims>,
}
pub struct OidcExchangeParams {
pub code: String,
pub code_verifier: Sensitive<String>,
pub redirect_uri: String,
pub nonce: String,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
pub struct OidcRefreshParams {
pub refresh_token: Sensitive<String>,
pub scope: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
#[derive(Default)]
pub struct LoginClientCredentialsParams {
pub scope: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
pub struct IntrospectParams {
pub token: Sensitive<String>,
pub token_type_hint: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
pub struct RevokeParams {
pub token: Sensitive<String>,
pub token_type_hint: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IntrospectionResult {
pub active: bool,
pub sub: Option<String>,
pub client_id: Option<String>,
pub scope: Option<String>,
pub token_type: Option<String>,
pub exp: Option<i64>,
pub iat: Option<i64>,
}
#[derive(Default)]
pub struct SsoStartParams {
pub federation_config_id: String,
pub redirect_uri: String,
pub tenant_id: Option<Uuid>,
pub tenant_slug: Option<String>,
pub org_id: Option<Uuid>,
pub org_slug: Option<String>,
}
#[derive(Debug, Clone)]
pub struct SsoStartResult {
pub authorize_url: String,
pub state: String,
pub expires_in_secs: u64,
}
pub struct SsoCompleteParams {
pub state: String,
pub code: String,
}
#[derive(Debug, Clone)]
pub struct SsoCompleteResult {
pub user_id: Uuid,
pub session_id: Uuid,
pub expires_in: u64,
pub redirect_uri: String,
}
pub(crate) async fn oauth2_error_or_fallback(response: reqwest::Response) -> AxiamError {
let status = response.status().as_u16();
if (300..400).contains(&status) {
return AxiamError::Network {
message: format!(
"unexpected redirect (HTTP {status}) from an OAuth2 endpoint; not followed"
),
source: None,
};
}
let retry_after = response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(crate::retry::parse_retry_after);
let text = response
.text()
.await
.unwrap_or_else(|_| "no response body".to_string());
if let Ok(body) = serde_json::from_str::<OAuth2ErrorResponseWire>(&text)
&& !body.error.is_empty()
{
let mut err = AxiamError::oauth_protocol_error(body.error, body.error_description);
if status == 429
&& let AxiamError::Auth {
retry_after: slot, ..
} = &mut err
{
*slot = retry_after;
}
return err;
}
AxiamError::from_http_status(status, text)
}
pub(crate) fn network_err(context: &str, e: reqwest::Error) -> AxiamError {
AxiamError::Network {
message: format!("{context}: {e}"),
source: Some(Box::new(e)),
}
}
fn validate_mtls_alias(alias: &str, replaces: &str) -> Result<(), AxiamError> {
let url = url::Url::parse(alias).map_err(|e| AxiamError::Network {
message: format!(
"mtls_endpoint_aliases publishes {alias:?}, which is not an absolute URL ({e}). \
Refusing rather than falling back to the top-level endpoint: this call presents a \
client certificate, and sending it to the front-channel host would authenticate \
nothing while appearing to work."
),
source: None,
})?;
let replaced_is_tls = url::Url::parse(replaces).is_ok_and(|e| e.scheme() == "https");
if replaced_is_tls && url.scheme() != "https" {
return Err(AxiamError::Network {
message: format!(
"mtls_endpoint_aliases publishes {alias:?}, whose scheme is {:?}, in place of \
an https endpoint. That is a downgrade, and mutual TLS over cleartext is a \
contradiction; refusing rather than falling back to the top-level endpoint.",
url.scheme()
),
source: None,
});
}
Ok(())
}
impl AxiamClient {
pub(crate) fn oidc_client_id_or_err(&self) -> Result<&str, AxiamError> {
self.oidc_client_id().ok_or_else(|| AxiamError::Auth {
message:
"this OIDC operation requires a client_id: build the client with .oidc_client_id(...) (CONTRACT.md §12.1)"
.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})
}
pub(crate) fn oidc_client_secret_or_err(&self, operation: &str) -> Result<String, AxiamError> {
self.oidc_client_secret()
.map(|s| s.expose().clone())
.ok_or_else(|| AxiamError::Auth {
message: format!(
"{operation} requires confidential-client credentials: build the client with .oidc_client_secret(...) (CONTRACT.md §12.1 note 4)"
),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})
}
pub(crate) async fn resolve_oidc_tenant_id(
&self,
explicit: Option<Uuid>,
) -> Result<Uuid, AxiamError> {
if let Some(id) = explicit {
return Ok(id);
}
self.resolved_tenant_id().await.ok_or_else(|| AxiamError::Auth {
message:
"this operation requires a tenant_id UUID for the /oauth2 query parameter: pass tenant_id explicitly, or construct the client with the tenant_id (UUID) form (CONTRACT.md §12.3 rule 4)"
.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})
}
pub(crate) fn presents_client_certificate(&self) -> bool {
self.inner.client_cert_pem.is_some()
}
pub(crate) fn mtls_preferred<'a>(
&self,
configuration: &'a OidcConfiguration,
select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
top_level: &'a str,
) -> Result<&'a str, AxiamError> {
Ok(self
.mtls_alias(configuration, select, Some(top_level))?
.unwrap_or(top_level))
}
fn mtls_alias<'a>(
&self,
configuration: &'a OidcConfiguration,
select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
replaces: Option<&str>,
) -> Result<Option<&'a str>, AxiamError> {
if !self.presents_client_certificate() {
return Ok(None);
}
let Some(alias) = configuration
.mtls_endpoint_aliases
.as_ref()
.and_then(select)
else {
return Ok(None);
};
validate_mtls_alias(alias, replaces.unwrap_or(""))?;
Ok(Some(alias))
}
pub(crate) fn mtls_preferred_opt<'a>(
&self,
configuration: &'a OidcConfiguration,
select: impl Fn(&'a MtlsEndpointAliases) -> Option<&'a str>,
top_level: Option<&'a str>,
) -> Result<Option<&'a str>, AxiamError> {
Ok(self
.mtls_alias(configuration, select, top_level)?
.or(top_level))
}
pub(crate) fn oidc_endpoint_url(
&self,
endpoint: &str,
tenant_id: Uuid,
) -> Result<url::Url, AxiamError> {
let mut url = url::Url::parse(endpoint).map_err(|e| AxiamError::Network {
message: format!("invalid endpoint URL in discovery document: {e}"),
source: None,
})?;
let has_tenant = url.query_pairs().any(|(k, _)| k == "tenant_id");
if has_tenant {
let retained: Vec<(String, String)> = url
.query_pairs()
.filter(|(k, _)| k != "tenant_id")
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect();
url.set_query(None);
let mut pairs = url.query_pairs_mut();
for (k, v) in &retained {
pairs.append_pair(k, v);
}
pairs.append_pair("tenant_id", &tenant_id.to_string());
} else {
url.query_pairs_mut()
.append_pair("tenant_id", &tenant_id.to_string());
}
Ok(url)
}
pub(crate) async fn post_token<F: Serialize + ?Sized>(
&self,
configuration: &OidcConfiguration,
form: &F,
tenant_id: Uuid,
) -> Result<TokenResponseWire, AxiamError> {
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 response = self
.idp_form_post(url)
.form(form)
.send()
.await
.map_err(|e| network_err("token request failed", e))?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
response
.json::<TokenResponseWire>()
.await
.map_err(|e| network_err("failed to parse token response", e))
}
pub(crate) async fn to_token_set(
&self,
wire: TokenResponseWire,
configuration: &OidcConfiguration,
nonce: Option<&str>,
) -> Result<OidcTokenSet, AxiamError> {
let id_claims = match &wire.id_token {
Some(id_token) => {
let verifier = self.oidc_verifier_for(&configuration.jwks_uri)?;
let claims: IdTokenClaims = verifier.verify_id_token_signature(id_token).await?;
let expectations = IdTokenExpectations {
issuer: &configuration.issuer,
client_id: self.oidc_client_id_or_err()?,
nonce,
clock_skew_sec: self.oidc_clock_skew_sec(),
};
let now_sec = crate::time::SystemTime::now()
.duration_since(crate::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
Some(check_id_token_claims(claims, &expectations, now_sec)?)
}
None => None,
};
Ok(OidcTokenSet {
access_token: Sensitive::new(wire.access_token),
token_type: wire.token_type,
expires_in: wire.expires_in,
scope: wire.scope,
refresh_token: wire.refresh_token.map(Sensitive::new),
id_token: wire.id_token.map(Sensitive::new),
id_claims,
})
}
}
impl AxiamClient {
pub async fn oidc_exchange(
&self,
params: OidcExchangeParams,
) -> Result<OidcTokenSet, 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().map(|s| s.expose().clone());
let form = TokenRequestForm {
grant_type: "authorization_code",
code: Some(¶ms.code),
code_verifier: Some(params.code_verifier.expose().as_str()),
redirect_uri: Some(¶ms.redirect_uri),
refresh_token: None,
client_id: &client_id,
client_secret: client_secret.as_deref(),
scope: None,
};
let wire = self.post_token(&configuration, &form, tenant_id).await?;
self.to_token_set(wire, &configuration, Some(¶ms.nonce))
.await
}
pub async fn oidc_refresh(
&self,
params: OidcRefreshParams,
) -> Result<OidcTokenSet, AxiamError> {
use super::single_flight::{OidcRefreshCancelled, OidcRefreshElection};
let leader = match self.oidc_refresh_election() {
OidcRefreshElection::Waiter(waiter) => {
return match waiter.wait().await {
Ok(Ok(tokens)) => Ok(tokens),
Ok(Err(shared)) => Err(shared.clone_for_waiter()),
Err(OidcRefreshCancelled) => Err(AxiamError::auth(
"the in-flight oidc_refresh was cancelled before completing; retry or re-authenticate (CONTRACT.md §9)",
)),
};
}
OidcRefreshElection::Leader(leader) => leader,
};
let result = self.oidc_refresh_wire_call(params).await;
leader.publish(&result);
result
}
async fn oidc_refresh_wire_call(
&self,
params: OidcRefreshParams,
) -> Result<OidcTokenSet, 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().map(|s| s.expose().clone());
let form = TokenRequestForm {
grant_type: "refresh_token",
code: None,
code_verifier: None,
redirect_uri: None,
refresh_token: Some(params.refresh_token.expose().as_str()),
client_id: &client_id,
client_secret: client_secret.as_deref(),
scope: params.scope.as_deref(),
};
let wire = self.post_token(&configuration, &form, tenant_id).await?;
self.to_token_set(wire, &configuration, None).await
}
pub async fn login_client_credentials(
&self,
params: LoginClientCredentialsParams,
) -> Result<OidcTokenSet, 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("login_client_credentials")?;
let form = TokenRequestForm {
grant_type: "client_credentials",
code: None,
code_verifier: None,
redirect_uri: None,
refresh_token: None,
client_id: &client_id,
client_secret: Some(&client_secret),
scope: params.scope.as_deref(),
};
let wire = self.post_token(&configuration, &form, tenant_id).await?;
self.to_token_set(wire, &configuration, None).await
}
pub async fn introspect(
&self,
params: IntrospectParams,
) -> Result<IntrospectionResult, 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("introspect")?;
let endpoint = self.mtls_preferred(
&configuration,
|a| a.introspection_endpoint.as_deref(),
&configuration.introspection_endpoint,
)?;
let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
let form = IntrospectOrRevokeForm {
token: params.token.expose().as_str(),
client_id: &client_id,
client_secret: &client_secret,
token_type_hint: params.token_type_hint.as_deref(),
};
let response = self
.idp_form_post(url)
.form(&form)
.send()
.await
.map_err(|e| network_err("introspect request failed", e))?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
let wire: IntrospectionResponseWire = response
.json()
.await
.map_err(|e| network_err("failed to parse introspect response", e))?;
Ok(IntrospectionResult {
active: wire.active,
sub: wire.sub,
client_id: wire.client_id,
scope: wire.scope,
token_type: wire.token_type,
exp: wire.exp,
iat: wire.iat,
})
}
pub async fn revoke(&self, params: RevokeParams) -> Result<(), 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("revoke")?;
let endpoint = self.mtls_preferred(
&configuration,
|a| a.revocation_endpoint.as_deref(),
&configuration.revocation_endpoint,
)?;
let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
let form = IntrospectOrRevokeForm {
token: params.token.expose().as_str(),
client_id: &client_id,
client_secret: &client_secret,
token_type_hint: params.token_type_hint.as_deref(),
};
let response = self
.idp_form_post(url)
.form(&form)
.send()
.await
.map_err(|e| network_err("revoke request failed", e))?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
Ok(())
}
pub async fn sso_start(&self, params: SsoStartParams) -> Result<SsoStartResult, AxiamError> {
let (tenant_id, tenant_slug) = match (params.tenant_id, params.tenant_slug) {
(Some(id), _) => (Some(id), None),
(None, Some(slug)) => (None, Some(slug)),
(None, None) => match &self.inner.tenant {
TenantIdentifier::Id(id) => (Some(*id), None),
TenantIdentifier::Slug(slug) => (None, Some(slug.clone())),
},
};
let (org_id, org_slug) = match (params.org_id, params.org_slug) {
(Some(id), _) => (Some(id), None),
(None, Some(slug)) => (None, Some(slug)),
(None, None) => match self.org_identifier() {
Some(OrgIdentifier::Id(id)) => (Some(*id), None),
Some(OrgIdentifier::Slug(slug)) => (None, Some(slug.clone())),
None => (self.resolved_org_id(), None),
},
};
if org_id.is_none() && org_slug.is_none() {
return Err(AxiamError::Auth {
message:
"sso_start requires organization context: pass org_id or org_slug, or construct the client with one (CONTRACT.md §5.1)"
.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
});
}
let body = OidcStartRequestWire {
federation_config_id: params.federation_config_id,
redirect_uri: params.redirect_uri,
tenant_id,
tenant_slug,
org_id,
org_slug,
};
let url = self
.base_url()
.join(SSO_START_PATH)
.expect("sso_start path is a well-formed relative URL literal");
let response = self
.http()
.post(url)
.header("X-Tenant-ID", self.tenant_header_value())
.maybe_csrf_header(self)
.json(&body)
.send()
.await
.map_err(|e| network_err("sso_start request failed", e))?;
if !response.status().is_success() {
let status = response.status().as_u16();
let message = response
.text()
.await
.unwrap_or_else(|_| "no response body".to_string());
return Err(AxiamError::from_http_status(status, message));
}
let wire: OidcStartResponseWire = response
.json()
.await
.map_err(|e| network_err("failed to parse sso_start response", e))?;
Ok(SsoStartResult {
authorize_url: wire.authorize_url,
state: wire.state,
expires_in_secs: wire.expires_in_secs,
})
}
pub async fn sso_complete(
&self,
params: SsoCompleteParams,
) -> Result<SsoCompleteResult, AxiamError> {
let body = OidcPublicCallbackRequestWire {
state: ¶ms.state,
code: ¶ms.code,
};
let url = self
.base_url()
.join(SSO_CALLBACK_PATH)
.expect("sso_complete path is a well-formed relative URL literal");
let response = self
.http()
.post(url)
.header("X-Tenant-ID", self.tenant_header_value())
.maybe_csrf_header(self)
.json(&body)
.send()
.await
.map_err(|e| network_err("sso_complete request failed", e))?;
if !response.status().is_success() {
let status = response.status().as_u16();
let message = response
.text()
.await
.unwrap_or_else(|_| "no response body".to_string());
return Err(AxiamError::from_http_status(status, message));
}
let wire: SsoLoginSuccessResponseWire = response
.json()
.await
.map_err(|e| network_err("failed to parse sso_complete response", e))?;
crate::rest::auth::absorb_session_cookies(self).await?;
Ok(SsoCompleteResult {
user_id: wire.user_id,
session_id: wire.session_id,
expires_in: wire.expires_in,
redirect_uri: wire.redirect_uri,
})
}
}
#[cfg(test)]
mod wire_redaction_tests {
#[test]
fn no_wire_struct_holding_a_secret_is_debug() {
assert!(
!crate::sensitive::implements_debug!(super::TokenResponseWire),
"TokenResponseWire is Debug"
);
}
}