use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::AxiamClient;
use crate::oidc::authorize::{
AuthorizationRequest, CODE_CHALLENGE_METHOD_S256, IDP_HINT_PARAM, compute_code_challenge,
normalize_scope, validate_idp_hint,
};
use crate::oidc::discovery::OidcConfiguration;
use crate::oidc::exchange::oauth2_error_or_fallback;
#[derive(Debug, Clone)]
pub struct PushedAuthorizationRequest {
pub url: String,
pub request_uri: Sensitive<String>,
pub expires_in: i64,
pub state: String,
pub nonce: String,
pub code_verifier: Sensitive<String>,
}
#[derive(Debug)]
pub struct OidcParParams {
pub request: AuthorizationRequest,
pub redirect_uri: String,
pub scope: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
pub dpop_jkt: Option<String>,
}
#[derive(Serialize)]
struct ParForm<'a> {
client_id: &'a str,
response_type: &'a str,
redirect_uri: &'a str,
scope: &'a str,
state: &'a str,
nonce: &'a str,
code_challenge: &'a str,
code_challenge_method: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
client_secret: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
dpop_jkt: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
axiam_idp_hint: Option<&'a str>,
}
impl std::fmt::Debug for ParForm<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ParForm")
.field("client_id", &self.client_id)
.field("response_type", &self.response_type)
.field("redirect_uri", &self.redirect_uri)
.field("scope", &self.scope)
.field("state", &self.state)
.field("nonce", &self.nonce)
.field("code_challenge", &self.code_challenge)
.field("code_challenge_method", &self.code_challenge_method)
.field(
"client_secret",
&self.client_secret.map(|_| "[REDACTED]").unwrap_or("None"),
)
.field("dpop_jkt", &self.dpop_jkt)
.field("axiam_idp_hint", &self.axiam_idp_hint)
.finish()
}
}
#[derive(Deserialize)]
struct PushedAuthorizationWire {
request_uri: String,
expires_in: i64,
}
fn idp_hint_of(authorization_url: &str) -> Option<String> {
url::Url::parse(authorization_url).ok().and_then(|u| {
u.query_pairs()
.find(|(k, _)| k == IDP_HINT_PARAM)
.map(|(_, v)| v.into_owned())
})
}
impl AxiamClient {
pub async fn oidc_par(
&self,
params: OidcParParams,
) -> Result<PushedAuthorizationRequest, AxiamError> {
self.ensure_open()?;
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 endpoint = self
.mtls_preferred_opt(
&configuration,
|a| a.pushed_authorization_request_endpoint.as_deref(),
configuration
.pushed_authorization_request_endpoint
.as_deref(),
)?
.ok_or_else(|| {
AxiamError::auth(
"the authorization server's discovery document advertises no \
pushed_authorization_request_endpoint: this server does not support \
RFC 9126 (CONTRACT.md §26.1)",
)
})?;
let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
let scope = normalize_scope(params.scope.as_deref());
let code_challenge = compute_code_challenge(params.request.code_verifier.expose());
let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());
let idp_hint = idp_hint_of(¶ms.request.url);
if let Some(hint) = &idp_hint {
validate_idp_hint("oidc_par", hint)?;
}
let form = ParForm {
client_id: &client_id,
response_type: "code",
redirect_uri: ¶ms.redirect_uri,
scope: &scope,
state: ¶ms.request.state,
nonce: ¶ms.request.nonce,
code_challenge: &code_challenge,
code_challenge_method: CODE_CHALLENGE_METHOD_S256,
client_secret: client_secret.as_deref(),
dpop_jkt: params.dpop_jkt.as_deref(),
axiam_idp_hint: idp_hint.as_deref(),
};
let response = self
.idp_form_post(url)
.form(&form)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("pushed authorization request failed: {e}"),
source: Some(Box::new(e)),
})?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
let wire: PushedAuthorizationWire =
response.json().await.map_err(|e| AxiamError::Network {
message: format!("failed to parse pushed authorization response: {e}"),
source: Some(Box::new(e)),
})?;
let advertised = url::Url::parse(&configuration.authorization_endpoint).map_err(|e| {
AxiamError::Network {
message: format!("invalid authorization_endpoint in discovery document: {e}"),
source: None,
}
})?;
let mut target = advertised;
target.set_query(None);
target
.query_pairs_mut()
.append_pair("tenant_id", &tenant_id.to_string())
.append_pair("client_id", &client_id)
.append_pair("request_uri", &wire.request_uri);
Ok(PushedAuthorizationRequest {
url: target.to_string(),
request_uri: Sensitive::new(wire.request_uri),
expires_in: wire.expires_in,
state: params.request.state,
nonce: params.request.nonce,
code_verifier: params.request.code_verifier,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn par_form_debug_redacts_only_the_client_secret() {
let rendered = format!(
"{:?}",
ParForm {
client_id: "client-abc",
response_type: "code",
redirect_uri: "https://rp.example/callback",
scope: "openid profile",
state: "state-value",
nonce: "nonce-value",
code_challenge: "challenge-value",
code_challenge_method: CODE_CHALLENGE_METHOD_S256,
client_secret: Some("super-secret-value"),
dpop_jkt: None,
axiam_idp_hint: None,
}
);
assert!(!rendered.contains("super-secret-value"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
for visible in [
"client-abc",
"https://rp.example/callback",
"openid profile",
"state-value",
"nonce-value",
"challenge-value",
CODE_CHALLENGE_METHOD_S256,
] {
assert!(
rendered.contains(visible),
"{visible} missing from {rendered}"
);
}
}
#[test]
fn par_form_debug_distinguishes_a_public_client_from_a_redacted_secret() {
let rendered = format!(
"{:?}",
ParForm {
client_id: "client-abc",
response_type: "code",
redirect_uri: "https://rp.example/callback",
scope: "openid",
state: "state-value",
nonce: "nonce-value",
code_challenge: "challenge-value",
code_challenge_method: CODE_CHALLENGE_METHOD_S256,
client_secret: None,
dpop_jkt: Some("0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"),
axiam_idp_hint: None,
}
);
assert!(rendered.contains("None"), "{rendered}");
assert!(!rendered.contains("[REDACTED]"), "{rendered}");
assert!(
rendered.contains("0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I"),
"{rendered}"
);
}
}