beyondigital_auth_sdk/
client_assertion.rs1use std::fmt;
9use std::sync::Arc;
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use serde_json::{json, Map, Value};
13
14use crate::error::AuthError;
15use crate::keys::{PrivateKeyInput, SigningAlgorithm, SigningKey};
16use crate::wire::{non_blank, origin_of};
17
18pub const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
20pub const DEFAULT_CLIENT_ASSERTION_LIFETIME_SECONDS: u64 = 60;
22pub const MAX_CLIENT_ASSERTION_LIFETIME_SECONDS: u64 = 300;
24
25#[derive(Clone)]
28pub struct ClientAssertionKey {
29 alg: SigningAlgorithm,
30 kid: Option<String>,
31 key: Arc<SigningKey>,
32}
33
34impl fmt::Debug for ClientAssertionKey {
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.debug_struct("ClientAssertionKey")
37 .field("alg", &self.alg)
38 .field("kid", &self.kid)
39 .finish()
40 }
41}
42
43impl ClientAssertionKey {
44 pub fn algorithm(&self) -> SigningAlgorithm {
45 self.alg
46 }
47 pub fn kid(&self) -> Option<&str> {
49 self.kid.as_deref()
50 }
51}
52
53pub fn import_client_assertion_key(
58 alg: SigningAlgorithm,
59 key: PrivateKeyInput,
60 kid: Option<String>,
61) -> Result<ClientAssertionKey, AuthError> {
62 let loaded = SigningKey::from_input(alg, &key)?;
63 if let Some(kid) = &kid {
64 if !non_blank(kid) {
65 return Err(AuthError::Config(
66 "kid must be a non-empty string when given".into(),
67 ));
68 }
69 }
70 Ok(ClientAssertionKey {
71 alg: loaded.algorithm(),
72 kid,
73 key: Arc::new(loaded),
74 })
75}
76
77#[derive(Debug, Default, Clone)]
79pub struct ClientAssertionOptions {
80 pub lifetime_seconds: Option<u64>,
82 pub now: Option<i64>,
84 pub jti: Option<String>,
86}
87
88pub(crate) fn unix_now() -> i64 {
89 SystemTime::now()
90 .duration_since(UNIX_EPOCH)
91 .map(|d| d.as_secs() as i64)
92 .unwrap_or(0)
93}
94
95pub fn create_client_assertion(
97 client_id: &str,
98 audience: &str,
99 key: &ClientAssertionKey,
100 options: ClientAssertionOptions,
101) -> Result<String, AuthError> {
102 if !non_blank(client_id) {
103 return Err(AuthError::Config(
104 "client_id is required for a client assertion".into(),
105 ));
106 }
107 if origin_of(audience).is_none() {
108 return Err(AuthError::Config(
109 "The client assertion audience must be the absolute URL of the endpoint".into(),
110 ));
111 }
112 let lifetime = options
113 .lifetime_seconds
114 .unwrap_or(DEFAULT_CLIENT_ASSERTION_LIFETIME_SECONDS);
115 if !(1..=MAX_CLIENT_ASSERTION_LIFETIME_SECONDS).contains(&lifetime) {
116 return Err(AuthError::Config(format!(
117 "The client assertion lifetime must be a whole number of seconds from 1 to {MAX_CLIENT_ASSERTION_LIFETIME_SECONDS}"
118 )));
119 }
120 let jti = options
121 .jti
122 .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
123 if jti.is_empty() || jti.chars().count() > 256 {
124 return Err(AuthError::Config(
125 "The client assertion needs a non-empty jti".into(),
126 ));
127 }
128 let iat = options.now.unwrap_or_else(unix_now);
129 let mut header = Map::new();
130 header.insert("alg".into(), Value::String(key.alg.as_str().into()));
131 if let Some(kid) = &key.kid {
132 header.insert("kid".into(), Value::String(kid.clone()));
133 }
134 let claims = json!({
135 "iss": client_id,
136 "sub": client_id,
137 "aud": audience,
138 "iat": iat,
139 "exp": iat + lifetime as i64,
140 "jti": jti,
141 });
142 let Value::Object(claims) = claims else {
143 unreachable!("a JSON object literal is an object")
144 };
145 key.key.sign_jws(&header, &claims)
146}