use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::client::AxiamClient;
use crate::error::AxiamError;
use crate::oidc::discovery::OidcConfiguration;
use crate::oidc::exchange::oauth2_error_or_fallback;
use crate::rest::auth::CsrfHeaderExt;
use crate::sensitive::Sensitive;
pub const UMA_TICKET_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:uma-ticket";
pub const UMA_PROTECTION_SCOPE: &str = "uma_protection";
pub const UMA_CLAIM_TOKEN_FORMAT: &str = "urn:ietf:params:oauth:token-type:access_token";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceSet {
#[serde(rename = "_id", default, skip_serializing_if = "Option::is_none")]
pub id: Option<Uuid>,
pub name: String,
#[serde(rename = "type", default, skip_serializing_if = "String::is_empty")]
pub resource_type: String,
#[serde(default)]
pub resource_scopes: Vec<String>,
}
impl ResourceSet {
pub fn new(name: impl Into<String>) -> Self {
Self {
id: None,
name: name.into(),
resource_type: String::new(),
resource_scopes: Vec::new(),
}
}
pub fn with_type(mut self, resource_type: impl Into<String>) -> Self {
self.resource_type = resource_type.into();
self
}
pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.resource_scopes = scopes.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RequestedPermission {
pub resource_id: Uuid,
pub resource_scopes: Vec<String>,
}
impl RequestedPermission {
pub fn new<I, S>(resource_id: Uuid, scopes: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
resource_id,
resource_scopes: scopes.into_iter().map(Into::into).collect(),
}
}
}
#[derive(Deserialize)]
struct TicketResponseWire {
ticket: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RptPermission {
pub resource_id: Uuid,
pub resource_scopes: Vec<String>,
pub exp: i64,
}
#[derive(Deserialize)]
struct RptResponseWire {
access_token: String,
token_type: String,
expires_in: u64,
}
#[derive(Debug, Clone)]
pub struct RequestingPartyToken {
pub access_token: Sensitive<String>,
pub token_type: String,
pub expires_in: u64,
}
#[derive(Debug, Clone)]
pub struct UmaChallenge {
pub realm: Option<String>,
pub as_uri: Option<String>,
pub ticket: Option<Sensitive<String>>,
}
pub fn uma_parse_challenge(header: &str) -> Option<UmaChallenge> {
let rest = header.trim().strip_prefix("UMA")?;
if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
return None;
}
let mut challenge = UmaChallenge {
realm: None,
as_uri: None,
ticket: None,
};
for part in rest.split(',') {
let Some((key, value)) = part.split_once('=') else {
continue;
};
let value = value.trim().trim_matches('"').to_string();
match key.trim() {
"realm" => challenge.realm = Some(value),
"as_uri" => challenge.as_uri = Some(value),
"ticket" => challenge.ticket = Some(Sensitive::new(value)),
_ => {}
}
}
Some(challenge)
}
pub fn uma_challenge_header(realm: &str, as_uri: &str, ticket: &Sensitive<String>) -> String {
format!(
"UMA realm=\"{realm}\", as_uri=\"{as_uri}\", ticket=\"{}\"",
ticket.expose()
)
}
#[derive(Serialize)]
struct UmaTicketForm<'a> {
grant_type: &'a str,
ticket: &'a str,
claim_token: &'a str,
claim_token_format: &'a str,
client_id: &'a str,
client_secret: &'a str,
}
impl AxiamClient {
pub async fn uma_register_resource(
&self,
pat: &Sensitive<String>,
resource: &ResourceSet,
) -> Result<ResourceSet, AxiamError> {
self.uma_protection_json("POST", "/uma2/rreg/resource_set", pat, Some(resource))
.await
}
pub async fn uma_read_resource(
&self,
pat: &Sensitive<String>,
id: Uuid,
) -> Result<ResourceSet, AxiamError> {
let path = format!("/uma2/rreg/resource_set/{id}");
self.uma_protection_json::<ResourceSet, ResourceSet>("GET", &path, pat, None)
.await
}
pub async fn uma_update_resource(
&self,
pat: &Sensitive<String>,
id: Uuid,
resource: &ResourceSet,
) -> Result<ResourceSet, AxiamError> {
let path = format!("/uma2/rreg/resource_set/{id}");
self.uma_protection_json("PUT", &path, pat, Some(resource))
.await
}
pub async fn uma_delete_resource(
&self,
pat: &Sensitive<String>,
id: Uuid,
) -> Result<(), AxiamError> {
let path = format!("/uma2/rreg/resource_set/{id}");
let response = self
.uma_protection_request("DELETE", &path, pat, None::<&()>)
.await?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
Ok(())
}
pub async fn uma_list_resources(
&self,
pat: &Sensitive<String>,
) -> Result<Vec<Uuid>, AxiamError> {
self.uma_protection_json::<Vec<Uuid>, ()>("GET", "/uma2/rreg/resource_set", pat, None)
.await
}
pub async fn uma_request_ticket(
&self,
pat: &Sensitive<String>,
permissions: &[RequestedPermission],
) -> Result<Sensitive<String>, AxiamError> {
let wire: TicketResponseWire = self
.uma_protection_json("POST", "/uma2/perm", pat, Some(permissions))
.await?;
Ok(Sensitive::new(wire.ticket))
}
pub async fn uma_exchange_ticket(
&self,
ticket: &Sensitive<String>,
claim_token: &Sensitive<String>,
) -> Result<RequestingPartyToken, AxiamError> {
self.uma_exchange_ticket_with(ticket, claim_token, None, None)
.await
}
pub async fn uma_exchange_ticket_with(
&self,
ticket: &Sensitive<String>,
claim_token: &Sensitive<String>,
tenant_id: Option<Uuid>,
configuration: Option<OidcConfiguration>,
) -> Result<RequestingPartyToken, AxiamError> {
let configuration = match configuration {
Some(c) => c,
None => self.oidc_discover().await?,
};
let tenant_id = self.resolve_oidc_tenant_id(tenant_id).await?;
let client_id = self.oidc_client_id_or_err()?.to_string();
let client_secret = self.oidc_client_secret_or_err("uma_exchange_ticket")?;
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 form = UmaTicketForm {
grant_type: UMA_TICKET_GRANT_TYPE,
ticket: ticket.expose().as_str(),
claim_token: claim_token.expose().as_str(),
claim_token_format: UMA_CLAIM_TOKEN_FORMAT,
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!("uma ticket exchange request failed: {e}"),
source: Some(Box::new(e)),
})?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
let wire: RptResponseWire = response.json().await.map_err(|e| AxiamError::Network {
message: format!("failed to parse RPT response: {e}"),
source: Some(Box::new(e)),
})?;
Ok(RequestingPartyToken {
access_token: Sensitive::new(wire.access_token),
token_type: wire.token_type,
expires_in: wire.expires_in,
})
}
async fn uma_protection_request<B: Serialize + ?Sized>(
&self,
method: &str,
path: &str,
pat: &Sensitive<String>,
body: Option<&B>,
) -> Result<reqwest::Response, AxiamError> {
let url = self
.base_url()
.join(path)
.map_err(|e| AxiamError::Network {
message: format!("invalid UMA path {path}: {e}"),
source: None,
})?;
let mut request = match method {
"POST" => self.http().post(url),
"PUT" => self.http().put(url),
"DELETE" => self.http().delete(url),
_ => self.http().get(url),
}
.header("X-Tenant-ID", self.tenant_header_value())
.bearer_auth(pat.expose())
.maybe_csrf_header(self);
if let Some(body) = body {
request = request.json(body);
}
request.send().await.map_err(|e| AxiamError::Network {
message: format!("UMA protection API request failed: {e}"),
source: Some(Box::new(e)),
})
}
async fn uma_protection_json<R, B>(
&self,
method: &str,
path: &str,
pat: &Sensitive<String>,
body: Option<&B>,
) -> Result<R, AxiamError>
where
R: for<'de> Deserialize<'de>,
B: Serialize + ?Sized,
{
let response = self.uma_protection_request(method, path, pat, body).await?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
response.json().await.map_err(|e| AxiamError::Network {
message: format!("failed to parse UMA response: {e}"),
source: Some(Box::new(e)),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_well_formed_challenge() {
let c = uma_parse_challenge(
r#"UMA realm="example", as_uri="https://id.example", ticket="abc123""#,
)
.expect("should parse");
assert_eq!(c.realm.as_deref(), Some("example"));
assert_eq!(c.as_uri.as_deref(), Some("https://id.example"));
assert_eq!(c.ticket.map(|t| t.expose().clone()), Some("abc123".into()));
}
#[test]
fn rejects_a_non_uma_scheme() {
assert!(uma_parse_challenge(r#"Bearer realm="example""#).is_none());
assert!(uma_parse_challenge(r#"UMAX realm="example""#).is_none());
}
#[test]
fn a_ticket_is_not_printed_by_debug() {
let c = uma_parse_challenge(r#"UMA ticket="super-secret-ticket""#).unwrap();
let rendered = format!("{c:?}");
assert!(
!rendered.contains("super-secret-ticket"),
"the ticket must be redacted in Debug output, got: {rendered}"
);
}
#[test]
fn challenge_header_round_trips() {
let header = uma_challenge_header(
"example",
"https://id.example",
&Sensitive::new("tkt".to_string()),
);
let parsed = uma_parse_challenge(&header).expect("round trip");
assert_eq!(parsed.as_uri.as_deref(), Some("https://id.example"));
assert_eq!(
parsed.ticket.map(|t| t.expose().clone()),
Some("tkt".into())
);
}
#[test]
fn an_update_payload_carries_exactly_the_scopes_given() {
let set = ResourceSet::new("invoice").with_scopes(["view"]);
let json = serde_json::to_value(&set).unwrap();
assert_eq!(json["resource_scopes"], serde_json::json!(["view"]));
}
}
#[cfg(test)]
mod wire_redaction_tests {
#[test]
fn no_wire_struct_holding_a_secret_is_debug() {
assert!(
!crate::sensitive::implements_debug!(super::TicketResponseWire),
"TicketResponseWire is Debug"
);
assert!(
!crate::sensitive::implements_debug!(super::RptResponseWire),
"RptResponseWire is Debug"
);
}
}