Skip to main content

beyondigital_auth_sdk/
keys.rs

1//! Private signing keys for the client-side proofs: `private_key_jwt` assertions and DPoP proofs.
2//!
3//! Only the three algorithms the service verifies are allowed (RS256, PS256, ES256), only with a key of the matching
4//! type, and never a symmetric key: a shared secret has no business signing a proof the service checks against a
5//! registered or embedded public key. Signing is done by `ring`. The private half is held in a [`SigningKey`] that
6//! has no `Debug`, `Serialize` or accessor for it: the types built on it print the algorithm and the public part only.
7use std::collections::BTreeMap;
8use std::fmt;
9use std::str::FromStr;
10
11use ring::rand::SystemRandom;
12use ring::signature::{self, EcdsaKeyPair, KeyPair, RsaKeyPair};
13use rsa::pkcs1::EncodeRsaPrivateKey;
14use rsa::pkcs8::DecodePrivateKey;
15use rsa::traits::PublicKeyParts;
16use rsa::{BigUint, RsaPrivateKey};
17use serde_json::{Map, Value};
18
19use crate::error::AuthError;
20use crate::wire::{b64url, b64url_decode};
21
22/// The smallest RSA modulus accepted (the service's own floor).
23pub const MIN_RSA_BITS: usize = 2048;
24
25/// A JOSE signing algorithm the service verifies for client-side proofs.
26#[derive(Clone, Copy, PartialEq, Eq, Hash)]
27pub enum SigningAlgorithm {
28    /// ECDSA over P-256 with SHA-256.
29    Es256,
30    /// RSASSA-PSS with SHA-256 (RSA 2048 bits or more).
31    Ps256,
32    /// RSASSA-PKCS1-v1_5 with SHA-256 (RSA 2048 bits or more).
33    Rs256,
34}
35
36impl SigningAlgorithm {
37    /// The JOSE name: `ES256`, `PS256` or `RS256`.
38    pub const fn as_str(self) -> &'static str {
39        match self {
40            Self::Es256 => "ES256",
41            Self::Ps256 => "PS256",
42            Self::Rs256 => "RS256",
43        }
44    }
45}
46
47impl fmt::Debug for SigningAlgorithm {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.write_str(self.as_str())
50    }
51}
52
53impl fmt::Display for SigningAlgorithm {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str(self.as_str())
56    }
57}
58
59impl FromStr for SigningAlgorithm {
60    type Err = AuthError;
61    fn from_str(value: &str) -> Result<Self, AuthError> {
62        match value {
63            "ES256" => Ok(Self::Es256),
64            "PS256" => Ok(Self::Ps256),
65            "RS256" => Ok(Self::Rs256),
66            _ => Err(AuthError::Config(
67                "Unsupported signing algorithm: use ES256, PS256 or RS256".into(),
68            )),
69        }
70    }
71}
72
73/// Where a private key comes from.
74#[derive(Clone)]
75pub enum PrivateKeyInput {
76    /// A private JWK (RFC 7517) as JSON: EC P-256 with `x`, `y`, `d`; RSA with `n`, `e`, `d`, `p` and `q`.
77    Jwk(Value),
78    /// An unencrypted PKCS#8 PEM (`-----BEGIN PRIVATE KEY-----`).
79    Pem(String),
80}
81
82impl fmt::Debug for PrivateKeyInput {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str("PrivateKeyInput(..)")
85    }
86}
87
88enum Pair {
89    Rsa(RsaKeyPair),
90    Ec(EcdsaKeyPair),
91}
92
93/// A private key and the public JWK derived from it. Never printed, never serialised.
94pub(crate) struct SigningKey {
95    alg: SigningAlgorithm,
96    pair: Pair,
97    public_jwk: BTreeMap<String, String>,
98}
99
100fn bad_key(alg: SigningAlgorithm) -> AuthError {
101    AuthError::Config(
102        match alg {
103            SigningAlgorithm::Es256 => "The key could not be imported for ES256: it needs an EC P-256 private key",
104            SigningAlgorithm::Ps256 => "The key could not be imported for PS256: it needs an RSA private key of 2048 bits or more",
105            SigningAlgorithm::Rs256 => "The key could not be imported for RS256: it needs an RSA private key of 2048 bits or more",
106        }
107        .into(),
108    )
109}
110
111fn jwk_bytes(jwk: &Value, name: &str) -> Option<Vec<u8>> {
112    let text = jwk.get(name)?.as_str()?;
113    if text.is_empty() {
114        return None;
115    }
116    b64url_decode(text)
117}
118
119fn pad32(bytes: Vec<u8>) -> Option<[u8; 32]> {
120    if bytes.is_empty() || bytes.len() > 32 {
121        return None;
122    }
123    let mut out = [0_u8; 32];
124    out[32 - bytes.len()..].copy_from_slice(&bytes);
125    Some(out)
126}
127
128fn ec_from_scalar_and_point(
129    d: &[u8; 32],
130    x: &[u8; 32],
131    y: &[u8; 32],
132) -> Result<EcdsaKeyPair, AuthError> {
133    let mut point = Vec::with_capacity(65);
134    point.push(4);
135    point.extend_from_slice(x);
136    point.extend_from_slice(y);
137    EcdsaKeyPair::from_private_key_and_public_key(
138        &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
139        d,
140        &point,
141        &SystemRandom::new(),
142    )
143    .map_err(|_| bad_key(SigningAlgorithm::Es256))
144}
145
146fn ec_public_jwk(pair: &EcdsaKeyPair) -> BTreeMap<String, String> {
147    let point = pair.public_key().as_ref();
148    // Uncompressed point: 0x04 || x (32) || y (32).
149    BTreeMap::from([
150        ("kty".to_string(), "EC".to_string()),
151        ("crv".to_string(), "P-256".to_string()),
152        ("x".to_string(), b64url(&point[1..33])),
153        ("y".to_string(), b64url(&point[33..65])),
154    ])
155}
156
157fn rsa_signing_key(alg: SigningAlgorithm, key: &RsaPrivateKey) -> Result<SigningKey, AuthError> {
158    if key.n().bits() < MIN_RSA_BITS {
159        return Err(AuthError::Config(format!(
160            "The RSA key must be at least {MIN_RSA_BITS} bits"
161        )));
162    }
163    let der = key.to_pkcs1_der().map_err(|_| bad_key(alg))?;
164    let pair = RsaKeyPair::from_der(der.as_bytes()).map_err(|_| bad_key(alg))?;
165    let public_jwk = BTreeMap::from([
166        ("kty".to_string(), "RSA".to_string()),
167        ("n".to_string(), b64url(&key.n().to_bytes_be())),
168        ("e".to_string(), b64url(&key.e().to_bytes_be())),
169    ]);
170    Ok(SigningKey {
171        alg,
172        pair: Pair::Rsa(pair),
173        public_jwk,
174    })
175}
176
177fn ec_signing_key(pair: EcdsaKeyPair) -> SigningKey {
178    let public_jwk = ec_public_jwk(&pair);
179    SigningKey {
180        alg: SigningAlgorithm::Es256,
181        pair: Pair::Ec(pair),
182        public_jwk,
183    }
184}
185
186impl SigningKey {
187    pub(crate) fn algorithm(&self) -> SigningAlgorithm {
188        self.alg
189    }
190
191    /// The public members of the key as a JWK, and nothing else (no `d`, no CRT parameters).
192    pub(crate) fn public_jwk(&self) -> &BTreeMap<String, String> {
193        &self.public_jwk
194    }
195
196    pub(crate) fn from_input(
197        alg: SigningAlgorithm,
198        input: &PrivateKeyInput,
199    ) -> Result<Self, AuthError> {
200        match input {
201            PrivateKeyInput::Jwk(jwk) => Self::from_jwk(alg, jwk),
202            PrivateKeyInput::Pem(pem) => Self::from_pkcs8_pem(alg, pem),
203        }
204    }
205
206    pub(crate) fn from_jwk(alg: SigningAlgorithm, jwk: &Value) -> Result<Self, AuthError> {
207        if !jwk.is_object() {
208            return Err(AuthError::Config("A private key is required".into()));
209        }
210        let kty = jwk.get("kty").and_then(Value::as_str);
211        match alg {
212            SigningAlgorithm::Es256 => {
213                if kty != Some("EC") || jwk.get("crv").and_then(Value::as_str) != Some("P-256") {
214                    return Err(AuthError::Config("ES256 needs an EC P-256 key".into()));
215                }
216            }
217            _ => {
218                if kty != Some("RSA") {
219                    return Err(AuthError::Config(format!("{alg} needs an RSA key")));
220                }
221            }
222        }
223        if jwk
224            .get("d")
225            .and_then(Value::as_str)
226            .unwrap_or("")
227            .is_empty()
228        {
229            return Err(AuthError::Config(
230                "The key must be a private key (it has no private part)".into(),
231            ));
232        }
233        match alg {
234            SigningAlgorithm::Es256 => {
235                let parts = (
236                    jwk_bytes(jwk, "d").and_then(pad32),
237                    jwk_bytes(jwk, "x").and_then(pad32),
238                    jwk_bytes(jwk, "y").and_then(pad32),
239                );
240                let (Some(d), Some(x), Some(y)) = parts else {
241                    return Err(bad_key(alg));
242                };
243                Ok(ec_signing_key(ec_from_scalar_and_point(&d, &x, &y)?))
244            }
245            _ => {
246                let component =
247                    |name: &str| jwk_bytes(jwk, name).map(|b| BigUint::from_bytes_be(&b));
248                let (Some(n), Some(e), Some(d), Some(p), Some(q)) = (
249                    component("n"),
250                    component("e"),
251                    component("d"),
252                    component("p"),
253                    component("q"),
254                ) else {
255                    return Err(AuthError::Config(
256                        "An RSA private JWK needs n, e, d, p and q".into(),
257                    ));
258                };
259                if n.bits() < MIN_RSA_BITS {
260                    return Err(AuthError::Config(format!(
261                        "The RSA key must be at least {MIN_RSA_BITS} bits"
262                    )));
263                }
264                let key = RsaPrivateKey::from_components(n, e, d, vec![p, q])
265                    .map_err(|_| bad_key(alg))?;
266                key.validate().map_err(|_| bad_key(alg))?;
267                rsa_signing_key(alg, &key)
268            }
269        }
270    }
271
272    pub(crate) fn from_pkcs8_pem(alg: SigningAlgorithm, pem: &str) -> Result<Self, AuthError> {
273        let not_pkcs8 = || {
274            AuthError::Config("The PEM is not a PKCS#8 private key that fits this algorithm".into())
275        };
276        let der = pem_pkcs8_to_der(pem).ok_or_else(not_pkcs8)?;
277        match alg {
278            SigningAlgorithm::Es256 => {
279                let pair = EcdsaKeyPair::from_pkcs8(
280                    &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
281                    &der,
282                    &SystemRandom::new(),
283                )
284                .map_err(|_| not_pkcs8())?;
285                Ok(ec_signing_key(pair))
286            }
287            _ => {
288                let key = RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| not_pkcs8())?;
289                rsa_signing_key(alg, &key)
290            }
291        }
292    }
293
294    pub(crate) fn generate(alg: SigningAlgorithm) -> Result<Self, AuthError> {
295        match alg {
296            SigningAlgorithm::Es256 => {
297                let rng = SystemRandom::new();
298                let pkcs8 =
299                    EcdsaKeyPair::generate_pkcs8(&signature::ECDSA_P256_SHA256_FIXED_SIGNING, &rng)
300                        .map_err(|_| AuthError::Config("Could not generate a key".into()))?;
301                let pair = EcdsaKeyPair::from_pkcs8(
302                    &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
303                    pkcs8.as_ref(),
304                    &rng,
305                )
306                .map_err(|_| AuthError::Config("Could not generate a key".into()))?;
307                Ok(ec_signing_key(pair))
308            }
309            _ => {
310                let key = RsaPrivateKey::new(&mut rand::thread_rng(), MIN_RSA_BITS)
311                    .map_err(|_| AuthError::Config("Could not generate a key".into()))?;
312                rsa_signing_key(alg, &key)
313            }
314        }
315    }
316
317    /// A compact JWS over `header` and `claims`. ES256 signatures are the fixed-size `r || s` JOSE form.
318    pub(crate) fn sign_jws(
319        &self,
320        header: &Map<String, Value>,
321        claims: &Map<String, Value>,
322    ) -> Result<String, AuthError> {
323        let part = |value: &Map<String, Value>| -> Result<String, AuthError> {
324            serde_json::to_vec(value)
325                .map(|bytes| b64url(&bytes))
326                .map_err(|_| AuthError::Config("The proof could not be encoded".into()))
327        };
328        let signing_input = format!("{}.{}", part(header)?, part(claims)?);
329        let rng = SystemRandom::new();
330        let failed = || AuthError::Config("The proof could not be signed".into());
331        let signature_bytes = match (&self.pair, self.alg) {
332            (Pair::Ec(pair), _) => pair
333                .sign(&rng, signing_input.as_bytes())
334                .map_err(|_| failed())?
335                .as_ref()
336                .to_vec(),
337            (Pair::Rsa(pair), alg) => {
338                let padding: &'static dyn signature::RsaEncoding = if alg == SigningAlgorithm::Ps256
339                {
340                    &signature::RSA_PSS_SHA256
341                } else {
342                    &signature::RSA_PKCS1_SHA256
343                };
344                let mut out = vec![0_u8; pair.public().modulus_len()];
345                pair.sign(padding, &rng, signing_input.as_bytes(), &mut out)
346                    .map_err(|_| failed())?;
347                out
348            }
349        };
350        Ok(format!("{signing_input}.{}", b64url(&signature_bytes)))
351    }
352}
353
354fn pem_pkcs8_to_der(pem: &str) -> Option<Vec<u8>> {
355    use base64::Engine as _;
356    const BEGIN: &str = "-----BEGIN PRIVATE KEY-----";
357    const END: &str = "-----END PRIVATE KEY-----";
358    let trimmed = pem.trim();
359    let body = trimmed.strip_prefix(BEGIN)?.strip_suffix(END)?;
360    let compact: String = body.chars().filter(|c| !c.is_whitespace()).collect();
361    if compact.is_empty() || compact.contains('-') {
362        return None;
363    }
364    base64::engine::general_purpose::STANDARD
365        .decode(compact)
366        .ok()
367}
368
369/// RFC 7638 SHA-256 thumbprint (base64url) of a public EC or RSA JWK.
370pub(crate) fn thumbprint_of(jwk: &BTreeMap<String, String>) -> Result<String, AuthError> {
371    use sha2::{Digest, Sha256};
372    let names: &[&str] = match jwk.get("kty").map(String::as_str) {
373        Some("EC") => &["crv", "kty", "x", "y"],
374        Some("RSA") => &["e", "kty", "n"],
375        _ => {
376            return Err(AuthError::Config(
377                "The key type is not supported: use an RSA or EC P-256 key".into(),
378            ))
379        }
380    };
381    let mut members = BTreeMap::new();
382    for name in names {
383        let value = jwk
384            .get(*name)
385            .ok_or_else(|| AuthError::Config("The public key is incomplete".into()))?;
386        members.insert(*name, value.as_str());
387    }
388    // BTreeMap order is lexicographic by member name, as RFC 7638 section 3.3 requires, and serde_json writes no
389    // whitespace.
390    let text = serde_json::to_string(&members)
391        .map_err(|_| AuthError::Config("The public key could not be encoded".into()))?;
392    Ok(b64url(&Sha256::digest(text.as_bytes())))
393}