use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::AxiamClient;
use super::discovery::OidcConfiguration;
pub const CODE_CHALLENGE_METHOD_S256: &str = "S256";
pub const CSPRNG_BYTES: usize = 32;
const OPENID_SCOPE: &str = "openid";
const RESERVED_AUTHORIZE_PARAMS: &[&str] = &[
"response_type",
"client_id",
"redirect_uri",
"scope",
"state",
"nonce",
"code_challenge",
"code_challenge_method",
];
pub const IDP_HINT_PARAM: &str = "axiam_idp_hint";
pub const MAX_IDP_HINT_BYTES: usize = 256;
pub(crate) fn validate_idp_hint(operation: &'static str, hint: &str) -> Result<(), AxiamError> {
if hint.is_empty() {
return Err(crate::management::error::local_refusal(
operation,
"idp_hint",
"idp_hint must not be empty: leave it unset for no hint (CONTRACT.md §12.1)",
));
}
if hint.len() > MAX_IDP_HINT_BYTES {
return Err(crate::management::error::local_refusal(
operation,
"idp_hint",
format!(
"idp_hint is {} bytes; the limit is {MAX_IDP_HINT_BYTES} (CONTRACT.md §12.1)",
hint.len()
),
));
}
Ok(())
}
pub fn random_url_safe_token(bytes: usize) -> Result<String, AxiamError> {
let mut buf = vec![0u8; bytes];
getrandom::fill(&mut buf).map_err(|e| AxiamError::Network {
message: format!("failed to generate CSPRNG bytes: {e}"),
source: None,
})?;
Ok(URL_SAFE_NO_PAD.encode(buf))
}
pub fn generate_code_verifier() -> Result<Sensitive<String>, AxiamError> {
Ok(Sensitive::new(random_url_safe_token(CSPRNG_BYTES)?))
}
pub fn compute_code_challenge(code_verifier: &str) -> String {
let digest = Sha256::digest(code_verifier.as_bytes());
URL_SAFE_NO_PAD.encode(digest)
}
#[derive(Debug)]
pub struct AuthorizationRequest {
pub url: String,
pub state: String,
pub nonce: String,
pub code_verifier: Sensitive<String>,
}
#[derive(Debug, Clone, Default)]
pub struct OidcBeginParams {
pub redirect_uri: String,
pub scope: Option<String>,
pub extra_params: Vec<(String, String)>,
pub idp_hint: Option<String>,
}
impl OidcBeginParams {
pub fn new(redirect_uri: impl Into<String>) -> Self {
Self {
redirect_uri: redirect_uri.into(),
scope: None,
extra_params: Vec::new(),
idp_hint: None,
}
}
pub fn with_idp_hint(mut self, hint: impl Into<String>) -> Self {
self.idp_hint = Some(hint.into());
self
}
pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
pub fn with_extra_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.extra_params.push((key.into(), value.into()));
self
}
}
fn percent_encode_query_spaces(url: &mut url::Url) {
if let Some(query) = url.query()
&& query.contains('+')
{
let rfc3986 = query.replace('+', "%20");
url.set_query(Some(&rfc3986));
}
}
pub(crate) fn normalize_scope(scope: Option<&str>) -> String {
let mut seen = BTreeSet::new();
let mut ordered = Vec::new();
ordered.push(OPENID_SCOPE.to_string());
seen.insert(OPENID_SCOPE.to_string());
for token in scope.unwrap_or_default().split_whitespace() {
if seen.insert(token.to_string()) {
ordered.push(token.to_string());
}
}
ordered.join(" ")
}
impl AxiamClient {
pub fn oidc_begin(
&self,
configuration: &OidcConfiguration,
params: OidcBeginParams,
) -> Result<AuthorizationRequest, AxiamError> {
for (key, _) in ¶ms.extra_params {
assert!(
!RESERVED_AUTHORIZE_PARAMS.contains(&key.as_str()),
"oidc_begin: extra_params may not override the SDK-owned authorization parameter \"{key}\" (CONTRACT.md §12.1 rule 5)"
);
}
if let Some(hint) = ¶ms.idp_hint {
validate_idp_hint("oidc_begin", hint)?;
} else if let Some((_, hint)) = params
.extra_params
.iter()
.find(|(k, _)| k == IDP_HINT_PARAM)
{
validate_idp_hint("oidc_begin", hint)?;
}
let state = random_url_safe_token(CSPRNG_BYTES)?;
let nonce = random_url_safe_token(CSPRNG_BYTES)?;
let code_verifier = generate_code_verifier()?;
let code_challenge = compute_code_challenge(code_verifier.expose());
let scope = normalize_scope(params.scope.as_deref());
let mut url = url::Url::parse(&configuration.authorization_endpoint).map_err(|e| {
AxiamError::Network {
message: format!("invalid authorization_endpoint in discovery document: {e}"),
source: None,
}
})?;
{
let mut query = url.query_pairs_mut();
let mut hint_extra_seen = params.idp_hint.is_some();
for (key, value) in ¶ms.extra_params {
if key == IDP_HINT_PARAM {
if hint_extra_seen {
continue;
}
hint_extra_seen = true;
}
query.append_pair(key, value);
}
query.append_pair("response_type", "code");
query.append_pair("client_id", self.oidc_client_id_or_err()?);
query.append_pair("redirect_uri", ¶ms.redirect_uri);
query.append_pair("scope", &scope);
query.append_pair("state", &state);
query.append_pair("nonce", &nonce);
query.append_pair("code_challenge", &code_challenge);
query.append_pair("code_challenge_method", CODE_CHALLENGE_METHOD_S256);
if let Some(hint) = ¶ms.idp_hint {
query.append_pair(IDP_HINT_PARAM, hint);
}
}
percent_encode_query_spaces(&mut url);
Ok(AuthorizationRequest {
url: url.to_string(),
state,
nonce,
code_verifier,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc7636_appendix_b_test_vector() {
let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
let expected_challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";
assert_eq!(compute_code_challenge(verifier), expected_challenge);
}
#[test]
fn random_tokens_are_at_least_128_bits_and_unique() {
let a = random_url_safe_token(CSPRNG_BYTES).expect("csprng token");
let b = random_url_safe_token(CSPRNG_BYTES).expect("csprng token");
assert_ne!(a, b, "two draws must not collide");
assert_eq!(a.len(), 43);
assert!(!a.contains('='));
}
#[test]
fn code_verifier_is_43_chars_from_the_unreserved_set() {
let verifier = generate_code_verifier().expect("verifier");
let raw = verifier.expose();
assert_eq!(raw.len(), 43);
assert!(
raw.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '~'))
);
}
#[test]
fn percent_encode_query_spaces_rewrites_plus_as_rfc3986_space() {
let mut url = url::Url::parse("https://iam.example.com/oauth2/authorize").unwrap();
url.query_pairs_mut()
.append_pair("scope", "openid profile email")
.append_pair("literal_plus", "a+b");
assert!(url.query().unwrap().contains("openid+profile+email"));
percent_encode_query_spaces(&mut url);
let raw = url.to_string();
assert!(
raw.contains("scope=openid%20profile%20email"),
"spaces must be %20: {raw}"
);
assert!(!raw.contains('+'), "no raw '+' may survive: {raw}");
assert!(raw.contains("literal_plus=a%2Bb"), "{raw}");
assert_eq!(
url.query_pairs()
.find(|(k, _)| k == "literal_plus")
.map(|(_, v)| v.into_owned()),
Some("a+b".to_string())
);
assert!(!raw.contains("%2520"), "{raw}");
}
#[test]
fn percent_encode_query_spaces_leaves_a_plus_free_query_and_the_path_alone() {
let mut url = url::Url::parse("https://iam.example.com/oauth2/a+b?x=1").unwrap();
percent_encode_query_spaces(&mut url);
assert_eq!(url.as_str(), "https://iam.example.com/oauth2/a+b?x=1");
}
#[test]
fn normalize_scope_adds_openid_and_dedupes() {
assert_eq!(normalize_scope(None), "openid");
assert_eq!(normalize_scope(Some("profile")), "openid profile");
assert_eq!(
normalize_scope(Some("openid openid profile")),
"openid profile"
);
}
}