use serde::Serialize;
use sha2::{Digest, Sha256};
use uuid::Uuid;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::AxiamClient;
use crate::management::error::local_refusal;
use super::authorize::{CSPRNG_BYTES, random_url_safe_token};
use super::discovery::OidcConfiguration;
use super::exchange::OidcTokenSet;
pub const PROVIDER_ID_TOKEN_GRANT_TYPE: &str =
"urn:axiam:params:oauth:grant-type:provider-id-token";
const OPERATION: &str = "login_with_provider_id_token";
#[derive(Debug, Clone)]
pub struct ProviderNonce {
pub raw: Sensitive<String>,
pub hashed: String,
}
impl ProviderNonce {
pub fn generate() -> Result<Self, AxiamError> {
let raw = random_url_safe_token(CSPRNG_BYTES)?;
let hashed = hash_nonce(&raw);
Ok(Self {
raw: Sensitive::new(raw),
hashed,
})
}
}
fn hash_nonce(raw: &str) -> String {
hex::encode(Sha256::digest(raw.as_bytes()))
}
pub fn native_nonce() -> Result<ProviderNonce, AxiamError> {
ProviderNonce::generate()
}
#[derive(Debug, Default, Clone)]
pub struct ProviderIdTokenOptions {
pub scopes: Option<Vec<String>>,
pub resource: Option<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
#[derive(Serialize)]
struct ProviderIdTokenForm<'a> {
grant_type: &'a str,
client_id: &'a str,
provider: &'a str,
id_token: &'a str,
nonce: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
scope: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
resource: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
client_secret: Option<&'a str>,
}
impl AxiamClient {
pub async fn login_with_provider_id_token(
&self,
provider: &str,
id_token: Sensitive<String>,
nonce: Sensitive<String>,
options: ProviderIdTokenOptions,
) -> Result<OidcTokenSet, AxiamError> {
self.ensure_open()?;
for (field, empty) in [
("provider", provider.is_empty()),
("id_token", id_token.expose().is_empty()),
("nonce", nonce.expose().is_empty()),
] {
if empty {
return Err(local_refusal(
OPERATION,
field,
format!("{field} must not be empty (CONTRACT.md §37.2 rule 4)"),
));
}
}
let client_id = self.oidc_client_id_or_err()?.to_string();
let tenant_id = self.resolve_oidc_tenant_id(options.tenant_id).await?;
let configuration = match options.configuration {
Some(c) => c,
None => self.oidc_discover().await?,
};
let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());
let scope = options
.scopes
.as_ref()
.filter(|s| !s.is_empty())
.map(|s| s.join(" "));
let form = ProviderIdTokenForm {
grant_type: PROVIDER_ID_TOKEN_GRANT_TYPE,
client_id: &client_id,
provider,
id_token: id_token.expose().as_str(),
nonce: nonce.expose().as_str(),
scope: scope.as_deref(),
resource: options.resource.as_deref(),
client_secret: client_secret.as_deref(),
};
let wire = self.post_token(&configuration, &form, tenant_id).await?;
self.to_token_set(wire, &configuration, Some(nonce.expose().as_str()))
.await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hashing_matches_the_contract_vector() {
assert_eq!(
hash_nonce("n-0S6_WzA2Mj"),
"0823a09b54cb9381561068b00aaf4e539b3f54604631d3e6a820879b6b04cc19"
);
}
#[test]
fn the_form_never_debug_prints_and_the_pair_redacts_raw() {
let pair = native_nonce().expect("nonce");
let rendered = format!("{pair:?}");
assert!(!rendered.contains(pair.raw.expose()), "{rendered}");
assert!(rendered.contains(&pair.hashed));
}
}