Skip to main content

beyondigital_auth_sdk/
client_assertion.rs

1//! `private_key_jwt` client authentication (RFC 7523 section 2.2, OIDC Core section 9).
2//!
3//! The client proves who it is with a JWT signed by a key whose public half it registered, instead of sending a shared
4//! secret. The service (`services/client_assertion.rs`) accepts it at the token endpoint and the pushed authorization
5//! endpoint only, and requires: RS256, PS256 or ES256; `iss` and `sub` both the client id; `aud` the URL of the
6//! endpoint it is presented to (or the issuer); an `exp` at most 300 seconds ahead; a `jti` it has not seen. An
7//! assertion is single use: [`create_client_assertion`] mints a new one, with a new random `jti`, per request.
8use 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
18/// `client_assertion_type` for a JWT assertion (RFC 7523).
19pub const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
20/// Lifetime of an assertion when the caller does not say.
21pub const DEFAULT_CLIENT_ASSERTION_LIFETIME_SECONDS: u64 = 60;
22/// The service refuses an assertion whose `exp` is further than this ahead.
23pub const MAX_CLIENT_ASSERTION_LIFETIME_SECONDS: u64 = 300;
24
25/// A private key registered for a client. The private half cannot be read back from this value, and it prints only
26/// the algorithm and the `kid`.
27#[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    /// Sent as the JOSE `kid` so the service picks the right registered key.
48    pub fn kid(&self) -> Option<&str> {
49        self.kid.as_deref()
50    }
51}
52
53/// Load a private key for `private_key_jwt`: a private JWK or a PKCS#8 PEM.
54///
55/// Only RS256 (RSA, 2048 bits or more), PS256 (the same) and ES256 (P-256) are accepted, and a key must be a private
56/// key of the matching type.
57pub 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/// Test hooks and the lifetime of one assertion.
78#[derive(Debug, Default, Clone)]
79pub struct ClientAssertionOptions {
80    /// Seconds the assertion is valid for: 1 to 300 (default 60).
81    pub lifetime_seconds: Option<u64>,
82    /// Issued-at, unix seconds. For tests: a real call leaves it out and gets the current time.
83    pub now: Option<i64>,
84    /// For tests: a real call leaves it out and every assertion gets a fresh random `jti`.
85    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
95/// A signed assertion for `audience`: `<issuer>/oauth/token` or `<issuer>/oauth/par`.
96pub 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}