use crate::time::{Duration, Instant};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use jsonwebtoken::{Algorithm, EncodingKey, Header};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use uuid::Uuid;
use super::discovery::OidcConfiguration;
use super::exchange::{OidcTokenSet, TokenResponseWire, oauth2_error_or_fallback};
use crate::client::AxiamClient;
use crate::error::AxiamError;
use crate::management::error::local_refusal;
use crate::sensitive::Sensitive;
pub const CIBA_GRANT_TYPE: &str = "urn:openid:params:grant-type:ciba";
pub const DEFAULT_CIBA_INTERVAL_SECS: u64 = 5;
pub const CIBA_SLOW_DOWN_INCREMENT_SECS: u64 = 5;
pub const SIGNED_REQUEST_LIFETIME_SECS: i64 = 300;
#[derive(Debug, Clone)]
pub enum CibaUserHint {
LoginHint(String),
IdTokenHint(String),
}
#[derive(Debug, Clone)]
pub enum CibaDelivery {
Poll,
Ping {
client_notification_token: Sensitive<String>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CibaSigningAlg {
Ps256,
Es256,
EdDsa,
}
impl CibaSigningAlg {
fn jose(self) -> Algorithm {
match self {
CibaSigningAlg::Ps256 => Algorithm::PS256,
CibaSigningAlg::Es256 => Algorithm::ES256,
CibaSigningAlg::EdDsa => Algorithm::EdDSA,
}
}
}
#[derive(Clone)]
pub struct CibaRequestSigner {
alg: CibaSigningAlg,
key: Sensitive<RequestKey>,
kid: Option<String>,
}
#[derive(Clone)]
enum RequestKey {
Jwt(EncodingKey),
#[cfg(not(target_arch = "wasm32"))]
Es256(Arc<ring::signature::EcdsaKeyPair>),
#[cfg(not(target_arch = "wasm32"))]
Ps256(Arc<ring::signature::RsaKeyPair>),
}
impl std::fmt::Debug for CibaRequestSigner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CibaRequestSigner")
.field("alg", &self.alg)
.field("kid", &self.kid)
.field("key", &self.key)
.finish()
}
}
impl CibaRequestSigner {
pub fn from_pem(
alg: CibaSigningAlg,
pem: &Sensitive<Vec<u8>>,
kid: Option<String>,
) -> Result<Self, AxiamError> {
let refuse = || {
local_refusal(
"ciba_initiate",
"signing_key",
"the key is not a private key that signs under the given algorithm (CONTRACT.md §33.2)",
)
};
let key = match alg {
CibaSigningAlg::EdDsa => EncodingKey::from_ed_pem(pem.expose())
.map(RequestKey::Jwt)
.map_err(|_| refuse())?,
#[cfg(not(target_arch = "wasm32"))]
CibaSigningAlg::Es256 => {
let der = pkcs8_der_from_pem(pem.expose()).ok_or_else(refuse)?;
let pair = ring::signature::EcdsaKeyPair::from_pkcs8(
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
&der,
&ring::rand::SystemRandom::new(),
)
.map_err(|_| refuse())?;
RequestKey::Es256(Arc::new(pair))
}
#[cfg(target_arch = "wasm32")]
CibaSigningAlg::Es256 => {
return Err(local_refusal(
"ciba_initiate",
"signing_key",
"ES256 request signing is not available in the browser build (CONTRACT.md §33.2)",
));
}
#[cfg(not(target_arch = "wasm32"))]
CibaSigningAlg::Ps256 => {
let parsed = if let Some(der) = pkcs8_der_from_pem(pem.expose()) {
ring::signature::RsaKeyPair::from_pkcs8(&der)
} else {
let der = pkcs1_der_from_pem(pem.expose()).ok_or_else(refuse)?;
ring::signature::RsaKeyPair::from_der(&der)
};
let pair = parsed.map_err(|e| match e.to_string().as_str() {
"TooSmall" | "TooLarge" | "PrivateModulusLenNotMultipleOf512Bits" => {
local_refusal(
"ciba_initiate",
"signing_key",
"a PS256 key must be 2048 to 8192 bits, a multiple of 512 bits: the RSA sizes ring signs with (CONTRACT.md §33.2)",
)
}
_ => refuse(),
})?;
RequestKey::Ps256(Arc::new(pair))
}
#[cfg(target_arch = "wasm32")]
CibaSigningAlg::Ps256 => {
return Err(local_refusal(
"ciba_initiate",
"signing_key",
"PS256 request signing is not available in the browser build (CONTRACT.md §33.2)",
));
}
};
match &key {
RequestKey::Jwt(k) => {
jsonwebtoken::crypto::sign(b"axiam-ciba-probe", k, alg.jose())
.map_err(|_| refuse())?;
}
#[cfg(not(target_arch = "wasm32"))]
RequestKey::Es256(pair) => {
es256_sign(pair, b"axiam-ciba-probe").ok_or_else(refuse)?;
}
#[cfg(not(target_arch = "wasm32"))]
RequestKey::Ps256(pair) => {
ps256_sign(pair, b"axiam-ciba-probe").ok_or_else(refuse)?;
}
}
Ok(Self {
alg,
key: Sensitive::new(key),
kid,
})
}
pub fn alg(&self) -> CibaSigningAlg {
self.alg
}
#[cfg(all(test, not(target_arch = "wasm32")))]
fn ring_rsa(&self) -> Option<&ring::signature::RsaKeyPair> {
match self.key.expose() {
RequestKey::Ps256(pair) => Some(pair),
RequestKey::Jwt(_) | RequestKey::Es256(_) => None,
}
}
}
#[derive(Debug, Clone)]
pub struct CibaInitiateParams {
pub scope: String,
pub hint: CibaUserHint,
pub binding_message: Option<String>,
pub requested_expiry: Option<u32>,
pub acr_values: Option<String>,
pub resource: Option<String>,
pub delivery: CibaDelivery,
pub signer: Option<CibaRequestSigner>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
impl CibaInitiateParams {
pub fn new(scope: impl Into<String>, hint: CibaUserHint) -> Self {
Self {
scope: scope.into(),
hint,
binding_message: None,
requested_expiry: None,
acr_values: None,
resource: None,
delivery: CibaDelivery::Poll,
signer: None,
tenant_id: None,
configuration: None,
}
}
}
#[derive(Debug, Clone)]
pub struct CibaInitiateResponse {
pub auth_req_id: Sensitive<String>,
pub expires_in: u64,
pub interval: u64,
pub received_at: Instant,
}
#[derive(Deserialize)]
struct CibaInitiateResponseWire {
auth_req_id: String,
expires_in: u64,
#[serde(default)]
interval: Option<u64>,
}
#[derive(Debug, Clone)]
pub struct CibaPollParams {
pub auth_req_id: Sensitive<String>,
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
}
pub trait CibaClock: Send + Sync {
fn now(&self) -> Instant;
fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>>;
}
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemCibaClock;
impl CibaClock for SystemCibaClock {
fn now(&self) -> Instant {
Instant::now()
}
fn sleep(&self, duration: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
Box::pin(tokio::time::sleep(duration))
}
}
#[derive(Clone, Default)]
pub struct CibaAwaitParams {
pub tenant_id: Option<Uuid>,
pub configuration: Option<OidcConfiguration>,
pub clock: Option<Arc<dyn CibaClock>>,
}
impl std::fmt::Debug for CibaAwaitParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CibaAwaitParams")
.field("tenant_id", &self.tenant_id)
.field(
"configuration",
&self.configuration.as_ref().map(|c| &c.issuer),
)
.field("clock", &self.clock.as_ref().map(|_| "<clock>"))
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Step {
Pending,
SlowDown,
Transient,
Terminal,
}
struct PollFailure {
err: AxiamError,
step: Step,
}
impl PollFailure {
fn terminal(err: AxiamError) -> Self {
Self {
err,
step: Step::Terminal,
}
}
}
fn decisive_step(err: &AxiamError, status: u16) -> Step {
match err.oauth_error_code() {
Some("authorization_pending") => Step::Pending,
Some("slow_down") => Step::SlowDown,
Some("rate_limit_exceeded") => Step::Transient,
_ if status == 408 || status == 429 => Step::Transient,
_ => Step::Terminal,
}
}
struct ClientAuth {
client_id: String,
client_secret: Option<String>,
}
impl AxiamClient {
fn ciba_client_auth(&self, operation: &str) -> Result<ClientAuth, AxiamError> {
let client_id = self.oidc_client_id_or_err()?.to_string();
let client_secret = self.oidc_client_secret().map(|s| s.expose().clone());
if client_secret.is_none() && !self.presents_client_certificate() {
return Err(AxiamError::auth(format!(
"{operation} requires client authentication: a CIBA client is never public — \
build the client with .oidc_client_secret(...) or a §6.1 client certificate \
(CONTRACT.md §33.1)"
)));
}
Ok(ClientAuth {
client_id,
client_secret,
})
}
pub async fn ciba_initiate(
&self,
params: CibaInitiateParams,
) -> Result<CibaInitiateResponse, AxiamError> {
self.ensure_open()?;
let auth = self.ciba_client_auth("ciba_initiate")?;
if let CibaDelivery::Ping {
client_notification_token,
} = ¶ms.delivery
&& client_notification_token.expose().is_empty()
{
return Err(local_refusal(
"ciba_initiate",
"client_notification_token",
"a ping-mode request needs a client_notification_token: without one AXIAM has nothing to ping with (CONTRACT.md §33.8)",
));
}
let configuration = match params.configuration.clone() {
Some(c) => c,
None => self.oidc_discover().await?,
};
let tenant_id = self.resolve_oidc_tenant_id(params.tenant_id).await?;
let endpoint = self
.mtls_preferred_opt(
&configuration,
|a| a.backchannel_authentication_endpoint.as_deref(),
configuration.backchannel_authentication_endpoint.as_deref(),
)?
.ok_or_else(|| {
AxiamError::auth(
"the authorization server's discovery document advertises no \
backchannel_authentication_endpoint: this server does not support CIBA \
(CONTRACT.md §33.1)",
)
})?;
let url = self.oidc_endpoint_url(endpoint, tenant_id)?;
let mut form: Vec<(&'static str, Sensitive<String>)> =
vec![("client_id", Sensitive::new(auth.client_id.clone()))];
if let Some(secret) = &auth.client_secret {
form.push(("client_secret", Sensitive::new(secret.clone())));
}
match ¶ms.signer {
Some(signer) => {
let request =
signed_request(¶ms, signer, &auth.client_id, &configuration.issuer)?;
form.push(("request", request));
}
None => form.extend(plain_members(¶ms)),
}
let body: Vec<(&str, &str)> = form
.iter()
.map(|(k, v)| (*k, v.expose().as_str()))
.collect();
let response = self
.idp_form_post(url)
.form(&body)
.send()
.await
.map_err(|e| AxiamError::network(format!("ciba_initiate request failed: {e}")))?;
if !response.status().is_success() {
return Err(oauth2_error_or_fallback(response).await);
}
let wire: CibaInitiateResponseWire = response.json().await.map_err(|e| {
AxiamError::network(format!("failed to parse the ciba_initiate response: {e}"))
})?;
Ok(CibaInitiateResponse {
auth_req_id: Sensitive::new(wire.auth_req_id),
expires_in: wire.expires_in,
interval: wire
.interval
.filter(|i| *i > 0)
.unwrap_or(DEFAULT_CIBA_INTERVAL_SECS),
received_at: Instant::now(),
})
}
pub async fn ciba_poll(&self, params: CibaPollParams) -> Result<OidcTokenSet, AxiamError> {
self.ciba_poll_step(params, None).await.map_err(|f| f.err)
}
async fn ciba_poll_step(
&self,
params: CibaPollParams,
bound: Option<(Instant, &dyn CibaClock)>,
) -> Result<OidcTokenSet, PollFailure> {
use crate::retry::{
Attempt, RetryBound, RetryRunner, Sleeper, ThreadRngJitter, TokioSleeper,
parse_retry_after,
};
self.ensure_open().map_err(PollFailure::terminal)?;
let auth = self
.ciba_client_auth("ciba_poll")
.map_err(PollFailure::terminal)?;
let configuration = match params.configuration {
Some(c) => c,
None => self.oidc_discover().await.map_err(PollFailure::terminal)?,
};
let tenant_id = self
.resolve_oidc_tenant_id(params.tenant_id)
.await
.map_err(PollFailure::terminal)?;
let endpoint = self
.mtls_preferred(
&configuration,
|a| a.token_endpoint.as_deref(),
&configuration.token_endpoint,
)
.map_err(PollFailure::terminal)?;
let url = self
.oidc_endpoint_url(endpoint, tenant_id)
.map_err(PollFailure::terminal)?;
let mut form: Vec<(&str, &str)> = vec![
("grant_type", CIBA_GRANT_TYPE),
("auth_req_id", params.auth_req_id.expose().as_str()),
("client_id", auth.client_id.as_str()),
];
if let Some(secret) = &auth.client_secret {
form.push(("client_secret", secret.as_str()));
}
let runner = RetryRunner {
enabled: self.retry_enabled(),
operation: "ciba_poll",
telemetry: self.telemetry(),
jitter: &ThreadRngJitter,
sleeper: &TokioSleeper,
};
let (url, form) = (&url, &form);
struct ClockSleeper<'c>(&'c dyn CibaClock);
impl Sleeper for ClockSleeper<'_> {
fn sleep(&self, d: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
self.0.sleep(d)
}
}
let bound_sleeper = bound.map(|(_, clock)| ClockSleeper(clock));
let bound_now = bound.map(|(_, clock)| move || clock.now());
let retry_bound = match (bound, &bound_sleeper, &bound_now) {
(Some((deadline, _)), Some(sleeper), Some(now)) => Some(RetryBound {
deadline,
now,
sleeper,
}),
_ => None,
};
let wire: TokenResponseWire = runner
.run_until(retry_bound.as_ref(), |_| async move {
let response = self
.idp_form_post(url.clone())
.form(form)
.send()
.await
.map_err(|e| {
Attempt::bare(AxiamError::network(format!(
"ciba_poll request failed: {e}"
)))
})?;
if !response.status().is_success() {
let retry_after = response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(parse_retry_after);
let status = response.status().as_u16();
if status >= 500 {
let text = response.text().await.unwrap_or_default();
let err = AxiamError::from_http_status(status, text);
return Err(Attempt { err, retry_after });
}
let err = oauth2_error_or_fallback(response).await;
if err.oauth_error_code().is_some()
|| !crate::retry::status_is_retryable(status)
{
let step = decisive_step(&err, status);
return Ok(Err(PollFailure { err, step }));
}
return Err(Attempt { err, retry_after });
}
Ok(response.json::<TokenResponseWire>().await.map_err(|e| {
PollFailure::terminal(AxiamError::network(format!(
"failed to parse the ciba_poll response: {e}"
)))
}))
})
.await
.map_err(|ended| {
if ended.at_deadline {
return PollFailure::terminal(expired_token());
}
PollFailure {
err: ended.err,
step: Step::Transient,
}
})??;
self.to_token_set(wire, &configuration, None)
.await
.map_err(PollFailure::terminal)
}
pub async fn ciba_await(
&self,
initiated: &CibaInitiateResponse,
params: CibaAwaitParams,
) -> Result<OidcTokenSet, AxiamError> {
let clock: Arc<dyn CibaClock> = params
.clock
.clone()
.unwrap_or_else(|| Arc::new(SystemCibaClock));
let configuration = match params.configuration {
Some(c) => c,
None => self.oidc_discover().await?,
};
let deadline = initiated.received_at + Duration::from_secs(initiated.expires_in);
let mut interval = if initiated.interval == 0 {
DEFAULT_CIBA_INTERVAL_SECS
} else {
initiated.interval
};
loop {
let wait = Duration::from_secs(interval);
if clock.now() + wait >= deadline {
return Err(expired_token());
}
clock.sleep(wait).await;
match self
.ciba_poll_step(
CibaPollParams {
auth_req_id: initiated.auth_req_id.clone(),
tenant_id: params.tenant_id,
configuration: Some(configuration.clone()),
},
Some((deadline, clock.as_ref())),
)
.await
{
Ok(tokens) => return Ok(tokens),
Err(PollFailure { err, step }) => match step {
Step::Pending | Step::Transient => continue,
Step::SlowDown => interval += CIBA_SLOW_DOWN_INCREMENT_SECS,
Step::Terminal => return Err(err),
},
}
}
}
pub fn ciba_handle_ping<'a>(
&self,
headers: impl IntoIterator<Item = (&'a str, &'a [u8])>,
body: &[u8],
expected_token: &Sensitive<String>,
) -> Result<Sensitive<String>, AxiamError> {
use subtle::ConstantTimeEq;
let refused = || {
AxiamError::auth(
"ciba ping refused: the Authorization header is not the expected bearer \
(CONTRACT.md §33.1)",
)
};
let mut authorization = headers
.into_iter()
.filter(|(name, _)| name.eq_ignore_ascii_case("authorization"))
.map(|(_, value)| value);
let (Some(value), None) = (authorization.next(), authorization.next()) else {
return Err(refused());
};
let Some(space) = value.iter().position(|b| *b == b' ') else {
return Err(refused());
};
let (scheme, token) = (&value[..space], &value[space + 1..]);
if !scheme.eq_ignore_ascii_case(b"bearer") || token.is_empty() {
return Err(refused());
}
let expected = expected_token.expose().as_bytes();
if expected.is_empty() || !bool::from(token.ct_eq(expected)) {
return Err(refused());
}
let parsed: Value = serde_json::from_slice(body)
.map_err(|_| local_refusal("ciba_handle_ping", "body", "the ping body is not JSON"))?;
match parsed.get("auth_req_id") {
Some(Value::String(id)) if !id.is_empty() && parsed.is_object() => {
Ok(Sensitive::new(id.clone()))
}
_ => Err(local_refusal(
"ciba_handle_ping",
"auth_req_id",
"the ping body carries no non-empty auth_req_id string",
)),
}
}
}
impl AxiamError {
pub fn is_access_denied(&self) -> bool {
self.oauth_error_code() == Some("access_denied")
}
pub fn is_expired_token(&self) -> bool {
self.oauth_error_code() == Some("expired_token")
}
}
fn expired_token() -> AxiamError {
AxiamError::oauth_protocol_error(
"expired_token",
"the CIBA request expired before it was decided (client-side deadline from \
expires_in; CONTRACT.md §33.7 rule 4)",
)
}
fn plain_members(params: &CibaInitiateParams) -> Vec<(&'static str, Sensitive<String>)> {
let mut out = vec![("scope", Sensitive::new(params.scope.clone()))];
match ¶ms.hint {
CibaUserHint::LoginHint(h) => out.push(("login_hint", Sensitive::new(h.clone()))),
CibaUserHint::IdTokenHint(h) => out.push(("id_token_hint", Sensitive::new(h.clone()))),
}
if let Some(m) = ¶ms.binding_message {
out.push(("binding_message", Sensitive::new(m.clone())));
}
if let Some(e) = params.requested_expiry {
out.push(("requested_expiry", Sensitive::new(e.to_string())));
}
if let Some(a) = ¶ms.acr_values {
out.push(("acr_values", Sensitive::new(a.clone())));
}
if let Some(r) = ¶ms.resource {
out.push(("resource", Sensitive::new(r.clone())));
}
if let CibaDelivery::Ping {
client_notification_token,
} = ¶ms.delivery
{
out.push((
"client_notification_token",
client_notification_token.clone(),
));
}
out
}
#[derive(Serialize)]
struct SignedClaims<'a> {
iss: &'a str,
aud: &'a str,
iat: i64,
nbf: i64,
exp: i64,
jti: String,
#[serde(flatten)]
members: serde_json::Map<String, Value>,
}
#[cfg(not(target_arch = "wasm32"))]
fn der_from_pem(pem: &[u8], label: &str) -> Option<zeroize::Zeroizing<Vec<u8>>> {
use base64::Engine as _;
use zeroize::Zeroizing;
let text = std::str::from_utf8(pem).ok()?;
let body = text
.trim()
.strip_prefix(&format!("-----BEGIN {label}-----"))?
.strip_suffix(&format!("-----END {label}-----"))?;
let compact: Zeroizing<String> = Zeroizing::new(body.split_whitespace().collect());
base64::engine::general_purpose::STANDARD
.decode(compact.as_bytes())
.ok()
.map(Zeroizing::new)
}
#[cfg(not(target_arch = "wasm32"))]
fn pkcs8_der_from_pem(pem: &[u8]) -> Option<zeroize::Zeroizing<Vec<u8>>> {
der_from_pem(pem, "PRIVATE KEY")
}
#[cfg(not(target_arch = "wasm32"))]
fn pkcs1_der_from_pem(pem: &[u8]) -> Option<zeroize::Zeroizing<Vec<u8>>> {
der_from_pem(pem, "RSA PRIVATE KEY")
}
#[cfg(not(target_arch = "wasm32"))]
fn ps256_sign(pair: &ring::signature::RsaKeyPair, message: &[u8]) -> Option<Vec<u8>> {
let mut signature = vec![0; pair.public().modulus_len()];
pair.sign(
&ring::signature::RSA_PSS_SHA256,
&ring::rand::SystemRandom::new(),
message,
&mut signature,
)
.ok()?;
Some(signature)
}
#[cfg(not(target_arch = "wasm32"))]
fn es256_sign(pair: &ring::signature::EcdsaKeyPair, message: &[u8]) -> Option<Vec<u8>> {
pair.sign(&ring::rand::SystemRandom::new(), message)
.ok()
.map(|s| s.as_ref().to_vec())
}
#[cfg(not(target_arch = "wasm32"))]
fn ring_jws<C: Serialize>(
header: &Header,
claims: &C,
sign: impl FnOnce(&[u8]) -> Option<Vec<u8>>,
) -> Option<String> {
use base64::Engine as _;
let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
let input = format!(
"{}.{}",
b64.encode(serde_json::to_vec(header).ok()?),
b64.encode(serde_json::to_vec(claims).ok()?)
);
let signature = sign(input.as_bytes())?;
Some(format!("{input}.{}", b64.encode(signature)))
}
fn signed_request(
params: &CibaInitiateParams,
signer: &CibaRequestSigner,
client_id: &str,
issuer: &str,
) -> Result<Sensitive<String>, AxiamError> {
let now = crate::time::SystemTime::now()
.duration_since(crate::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
let mut members = serde_json::Map::new();
for (k, v) in plain_members(params) {
let value = if k == "requested_expiry" {
json!(params.requested_expiry)
} else {
Value::String(v.expose().clone())
};
members.insert(k.to_string(), value);
}
let claims = SignedClaims {
iss: client_id,
aud: issuer,
iat: now,
nbf: now,
exp: now + SIGNED_REQUEST_LIFETIME_SECS,
jti: Uuid::new_v4().simple().to_string(),
members,
};
let mut header = Header::new(signer.alg.jose());
header.kid = signer.kid.clone();
let signed = match signer.key.expose() {
RequestKey::Jwt(key) => jsonwebtoken::encode(&header, &claims, key).ok(),
#[cfg(not(target_arch = "wasm32"))]
RequestKey::Es256(pair) => ring_jws(&header, &claims, |m| es256_sign(pair, m)),
#[cfg(not(target_arch = "wasm32"))]
RequestKey::Ps256(pair) => ring_jws(&header, &claims, |m| ps256_sign(pair, m)),
};
signed.map(Sensitive::new).ok_or_else(|| {
local_refusal(
"ciba_initiate",
"signing_key",
"the signed request could not be signed with the given key",
)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_classification_follows_section_33_3_rule_6() {
let cases = [
("authorization_pending", Step::Pending),
("slow_down", Step::SlowDown),
("rate_limit_exceeded", Step::Transient),
("access_denied", Step::Terminal),
("expired_token", Step::Terminal),
("invalid_grant", Step::Terminal),
("something_new", Step::Terminal),
];
for (code, step) in cases {
assert_eq!(
decisive_step(&AxiamError::oauth_protocol_error(code, "d"), 400),
step,
"{code}"
);
}
let unknown = AxiamError::oauth_protocol_error("something_new", "d");
assert_eq!(decisive_step(&unknown, 429), Step::Transient);
assert_eq!(decisive_step(&unknown, 408), Step::Transient);
assert_eq!(
decisive_step(&AxiamError::from_http_status(400, "x"), 400),
Step::Terminal
);
assert_eq!(
decisive_step(&AxiamError::from_http_status(404, "x"), 404),
Step::Terminal
);
}
#[test]
fn the_two_terminal_outcomes_are_told_apart() {
let denied = AxiamError::oauth_protocol_error("access_denied", "no");
let expired = AxiamError::oauth_protocol_error("expired_token", "late");
assert!(denied.is_access_denied() && !denied.is_expired_token());
assert!(expired.is_expired_token() && !expired.is_access_denied());
}
#[cfg(not(target_arch = "wasm32"))]
fn p256_pem() -> (String, Vec<u8>) {
use base64::Engine as _;
let der = ring::signature::EcdsaKeyPair::generate_pkcs8(
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
&ring::rand::SystemRandom::new(),
)
.expect("generate");
let body = base64::engine::general_purpose::STANDARD.encode(der.as_ref());
let pem = format!("-----BEGIN PRIVATE KEY-----\n{body}\n-----END PRIVATE KEY-----\n");
(pem, der.as_ref().to_vec())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_es256_signer_is_rings_not_rust_cryptos() {
let (pem, _) = p256_pem();
let signer = CibaRequestSigner::from_pem(
CibaSigningAlg::Es256,
&Sensitive::new(pem.clone().into_bytes()),
None,
)
.expect("a P-256 key");
let RequestKey::Es256(pair) = signer.key.expose() else {
panic!("an ES256 signer must hold the ring key pair");
};
let message = b"the same message, signed twice";
let (a, b) = (
es256_sign(pair, message).expect("sign"),
es256_sign(pair, message).expect("sign"),
);
assert_ne!(a, b, "ring's randomised nonce: two signatures differ");
assert_eq!(a.len(), 64, "r || s, as JWS ES256 wants");
let rc = EncodingKey::from_ec_pem(pem.as_bytes()).expect("parses");
let (c, d) = (
jsonwebtoken::crypto::sign(message, &rc, Algorithm::ES256).expect("sign"),
jsonwebtoken::crypto::sign(message, &rc, Algorithm::ES256).expect("sign"),
);
assert_eq!(c, d, "RFC 6979: the RustCrypto signer is deterministic");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_ring_signed_request_verifies_as_es256() {
use ring::signature::KeyPair as _;
let (pem, der) = p256_pem();
let public = ring::signature::EcdsaKeyPair::from_pkcs8(
&ring::signature::ECDSA_P256_SHA256_FIXED_SIGNING,
&der,
&ring::rand::SystemRandom::new(),
)
.expect("parses")
.public_key()
.as_ref()
.to_vec();
let signer = CibaRequestSigner::from_pem(
CibaSigningAlg::Es256,
&Sensitive::new(pem.into_bytes()),
Some("k1".into()),
)
.expect("a P-256 key");
let RequestKey::Es256(pair) = signer.key.expose() else {
panic!("ring key pair");
};
let mut header = Header::new(Algorithm::ES256);
header.kid = Some("k1".into());
let jws = ring_jws(&header, &json!({"iss": "c", "aud": "i"}), |m| {
es256_sign(pair, m)
})
.expect("signs");
use base64::Engine as _;
let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
let (x, y) = (b64.encode(&public[1..33]), b64.encode(&public[33..65]));
let key = jsonwebtoken::DecodingKey::from_ec_components(&x, &y).expect("jwk");
let mut validation = jsonwebtoken::Validation::new(Algorithm::ES256);
validation.set_audience(&["i"]);
validation.set_required_spec_claims::<&str>(&[]);
let claims = jsonwebtoken::decode::<Value>(&jws, &key, &validation).expect("verifies");
assert_eq!(claims.claims["iss"], "c");
assert_eq!(claims.header.kid.as_deref(), Some("k1"));
}
#[cfg(not(target_arch = "wasm32"))]
fn openssl(args: &[&str], stdin: &[u8]) -> Vec<u8> {
use std::io::Write as _;
use std::process::{Command, Stdio};
let mut child = Command::new("openssl")
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("the openssl CLI generates the test RSA keys");
child
.stdin
.take()
.expect("stdin")
.write_all(stdin)
.expect("write");
let out = child.wait_with_output().expect("openssl");
assert!(
out.status.success(),
"openssl {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
out.stdout
}
#[cfg(not(target_arch = "wasm32"))]
fn rsa_pems(bits: u32) -> (String, String, String) {
let pkcs8 = openssl(
&[
"genpkey",
"-algorithm",
"RSA",
"-pkeyopt",
&format!("rsa_keygen_bits:{bits}"),
],
b"",
);
let pkcs1 = openssl(&["pkey", "-traditional"], &pkcs8);
let public = openssl(&["pkey", "-pubout"], &pkcs8);
let text = |b: Vec<u8>| String::from_utf8(b).expect("PEM is text");
(text(pkcs8), text(pkcs1), text(public))
}
#[cfg(not(target_arch = "wasm32"))]
fn ps256_signer(pem: &str) -> Result<CibaRequestSigner, AxiamError> {
CibaRequestSigner::from_pem(
CibaSigningAlg::Ps256,
&Sensitive::new(pem.as_bytes().to_vec()),
Some("k1".into()),
)
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_ring_signed_request_verifies_as_ps256_from_pkcs8_and_pkcs1() {
let (pkcs8, pkcs1, public) = rsa_pems(2048);
assert!(pkcs8.starts_with("-----BEGIN PRIVATE KEY-----"));
assert!(pkcs1.starts_with("-----BEGIN RSA PRIVATE KEY-----"));
let key = jsonwebtoken::DecodingKey::from_rsa_pem(public.as_bytes()).expect("public");
let mut validation = jsonwebtoken::Validation::new(Algorithm::PS256);
validation.set_audience(&["https://issuer.example"]);
validation.set_required_spec_claims(&["exp", "nbf", "aud", "iss"]);
let params = CibaInitiateParams::new("openid", CibaUserHint::LoginHint("alice".into()));
for pem in [&pkcs8, &pkcs1] {
let signer = ps256_signer(pem).expect("an RSA key");
let jws = signed_request(¶ms, &signer, "client-1", "https://issuer.example")
.expect("signs");
let token = jsonwebtoken::decode::<Value>(jws.expose(), &key, &validation)
.expect("verifies as PS256");
assert_eq!(token.header.alg, Algorithm::PS256);
assert_eq!(token.header.kid.as_deref(), Some("k1"));
assert_eq!(token.claims["iss"], "client-1");
assert_eq!(token.claims["login_hint"], "alice");
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_ps256_signer_is_rings_not_rust_cryptos() {
let (pkcs8, pkcs1, public) = rsa_pems(2048);
let key = jsonwebtoken::DecodingKey::from_rsa_pem(public.as_bytes()).expect("public");
for pem in [&pkcs8, &pkcs1] {
let signer = ps256_signer(pem).expect("an RSA key");
let pair = signer
.ring_rsa()
.expect("a PS256 signer must hold the ring key pair");
assert_eq!(
pair.public().modulus_len(),
256,
"the caller's 2048-bit key"
);
let message = b"signed by the held ring pair";
let signature = ps256_sign(pair, message).expect("sign");
use base64::Engine as _;
let b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(signature);
assert!(
jsonwebtoken::crypto::verify(&b64, message, &key, Algorithm::PS256)
.expect("verify"),
"the held ring pair is the caller's key"
);
}
let ed = ring::signature::Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new())
.expect("generate");
use base64::Engine as _;
let ed_pem = format!(
"-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n",
base64::engine::general_purpose::STANDARD.encode(ed.as_ref())
);
let eddsa = CibaRequestSigner::from_pem(
CibaSigningAlg::EdDsa,
&Sensitive::new(ed_pem.into_bytes()),
None,
)
.expect("an Ed25519 key");
assert!(eddsa.ring_rsa().is_none(), "EdDSA keeps jsonwebtoken");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_ps256_key_under_2048_bits_is_refused_saying_why() {
let (pkcs8, pkcs1, _) = rsa_pems(1024);
for pem in [&pkcs8, &pkcs1] {
let err = ps256_signer(pem).expect_err("too small for ring");
let text = err.to_string();
assert!(
text.contains("a PS256 key must be 2048 to 8192 bits"),
"{text}"
);
}
}
}