Skip to main content

rs_identity_model/dpop/
key.rs

1//! DPoP key pairs (RFC 9449 §4.1) and their RFC 7638 JWK thumbprints.
2
3use std::fmt;
4use std::str::FromStr;
5
6use aws_lc_rs::encoding::{AsDer, Pkcs8V1Der};
7use base64::Engine;
8use base64::engine::general_purpose::{STANDARD as BASE64_PAD, URL_SAFE_NO_PAD};
9use jsonwebtoken::EncodingKey;
10use jsonwebtoken::jwk::{AlgorithmParameters, EllipticCurve, Jwk, ThumbprintHash};
11use p256::pkcs8::EncodePrivateKey;
12use serde::Deserialize;
13use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
14
15use crate::jwks::JsonWebKey;
16use crate::{IdentityError, Result};
17
18/// How many times [`DpopAlgorithm::Es256`] generation re-draws from the CSPRNG
19/// before giving up. A uniform 32-byte draw lands outside the valid P-256 scalar
20/// range `[1, n-1]` with probability below 2^-32, so a single retry is already
21/// beyond reach; the loop exists so the failure is an error rather than a panic.
22const EC_SCALAR_DRAWS: usize = 8;
23
24/// The PEM label PKCS#8 private keys carry (RFC 7468 §10).
25const PKCS8_PEM_LABEL: &str = "PRIVATE KEY";
26
27/// A DPoP proof signing algorithm.
28///
29/// DPoP requires an **asymmetric** algorithm (RFC 9449 §4.2); a symmetric one
30/// such as `HS256` would let anyone holding the shared secret mint proofs, which
31/// defeats the whole point of sender-constraining a token. These are the two
32/// RFC 9449 §4.1 expects every implementation to provide.
33#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
34pub enum DpopAlgorithm {
35    /// ECDSA using P-256 and SHA-256 (RFC 7518 §3.4). Keys are EC P-256.
36    Es256,
37    /// RSASSA-PKCS1-v1_5 using SHA-256 (RFC 7518 §3.3). Keys are RSA of at least
38    /// 2048 bits.
39    Rs256,
40}
41
42impl DpopAlgorithm {
43    /// Returns the JWA algorithm name (RFC 7518 §3.1), the value that appears in
44    /// a proof's `alg` header.
45    pub const fn as_str(self) -> &'static str {
46        match self {
47            Self::Es256 => "ES256",
48            Self::Rs256 => "RS256",
49        }
50    }
51
52    /// The `jsonwebtoken` algorithm this maps to. Internal: the crate keeps
53    /// `jsonwebtoken` types out of its public surface.
54    pub(crate) const fn jwt(self) -> jsonwebtoken::Algorithm {
55        match self {
56            Self::Es256 => jsonwebtoken::Algorithm::ES256,
57            Self::Rs256 => jsonwebtoken::Algorithm::RS256,
58        }
59    }
60}
61
62impl fmt::Display for DpopAlgorithm {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(self.as_str())
65    }
66}
67
68impl FromStr for DpopAlgorithm {
69    type Err = IdentityError;
70
71    /// Parses a JWA algorithm name into a DPoP algorithm (DPOP-007).
72    ///
73    /// # Errors
74    ///
75    /// [`IdentityError::Configuration`] for anything other than `ES256` or
76    /// `RS256` — including the symmetric algorithms and `none`, which
77    /// RFC 9449 §4.2 forbids for proofs.
78    fn from_str(s: &str) -> Result<Self> {
79        match s {
80            "ES256" => Ok(Self::Es256),
81            "RS256" => Ok(Self::Rs256),
82            other => Err(IdentityError::Configuration(format!(
83                "unsupported DPoP algorithm {other:?}: DPoP proofs require an \
84                 asymmetric algorithm, either \"ES256\" or \"RS256\" \
85                 (RFC 9449 §4.1)"
86            ))),
87        }
88    }
89}
90
91/// The private-key JWK members [`DpopKey::from_private_jwk`] reads (RFC 7517 §4,
92/// RFC 7518 §6.2.2 / §6.3.2). Kept private: it exists to carry key material in,
93/// not to be part of the public surface. The members arrive as base64url text,
94/// private ones included, so every member is zeroed on drop.
95#[derive(Deserialize, Zeroize, ZeroizeOnDrop)]
96struct PrivateJwk {
97    #[serde(default)]
98    kty: String,
99    #[serde(default)]
100    alg: String,
101    #[serde(default)]
102    crv: String,
103    // EC public coordinates (RFC 7518 §6.2.1) and private key (§6.2.2).
104    #[serde(default)]
105    x: String,
106    #[serde(default)]
107    y: String,
108    #[serde(default)]
109    d: String,
110    // RSA public half (RFC 7518 §6.3.1).
111    #[serde(default)]
112    n: String,
113    #[serde(default)]
114    e: String,
115    // RSA private half, including the CRT members (RFC 7518 §6.3.2).
116    #[serde(default)]
117    p: String,
118    #[serde(default)]
119    q: String,
120    #[serde(default)]
121    dp: String,
122    #[serde(default)]
123    dq: String,
124    #[serde(default)]
125    qi: String,
126}
127
128/// A DPoP key pair: the private key that signs proof JWTs, plus its algorithm.
129///
130/// The public half is embedded in every proof's `jwk` header (RFC 9449 §4.2) and
131/// its RFC 7638 thumbprint ([`DpopKey::thumbprint`]) is the value an
132/// authorization server binds a token to via `cnf.jkt` (RFC 9449 §6).
133///
134/// Create one with [`DpopKey::generate`], or load a persisted one with
135/// [`DpopKey::from_pkcs8_pem`], [`DpopKey::from_pkcs8_der`], or
136/// [`DpopKey::from_private_jwk`]. Persist one with [`DpopKey::to_pkcs8_pem`] so
137/// it survives a restart: a key that outlives the process can be rotated without
138/// invalidating already-issued bound tokens.
139///
140/// The PKCS#8 copy this type keeps, and every intermediate buffer it decodes
141/// private material into, is zeroed on drop. The signing key held inside
142/// `jsonwebtoken`'s `EncodingKey` is outside this crate's control and is not.
143#[derive(Clone)]
144pub struct DpopKey {
145    algorithm: DpopAlgorithm,
146    /// The signing key handed to `jsonwebtoken`.
147    encoding: EncodingKey,
148    /// The public half, derived once at construction.
149    public: Jwk,
150    /// The PKCS#8 DER form, retained so the key can be re-serialized.
151    pkcs8: Zeroizing<Vec<u8>>,
152}
153
154/// Prints only the algorithm and the public thumbprint. Private key material is
155/// deliberately absent so a `{:?}` of a key — or of any struct holding one —
156/// cannot leak it into a log.
157impl fmt::Debug for DpopKey {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.debug_struct("DpopKey")
160            .field("algorithm", &self.algorithm.as_str())
161            .field(
162                "thumbprint",
163                &self.thumbprint().unwrap_or_else(|_| "<unavailable>".into()),
164            )
165            .finish_non_exhaustive()
166    }
167}
168
169impl DpopKey {
170    /// Generates a fresh DPoP key pair (RFC 9449 §4.1, DPOP-007).
171    ///
172    /// [`DpopAlgorithm::Es256`] produces an EC P-256 key and
173    /// [`DpopAlgorithm::Rs256`] a 2048-bit RSA key. Entropy comes from the
174    /// operating-system CSPRNG.
175    ///
176    /// # Errors
177    ///
178    /// [`IdentityError::Configuration`] if the system random source is
179    /// unavailable or key generation fails.
180    pub fn generate(algorithm: DpopAlgorithm) -> Result<Self> {
181        let pkcs8 = match algorithm {
182            DpopAlgorithm::Es256 => generate_p256_pkcs8()?,
183            DpopAlgorithm::Rs256 => generate_rsa_pkcs8()?,
184        };
185        Self::from_pkcs8_der(&pkcs8, algorithm)
186    }
187
188    /// Loads a key pair from a PKCS#8 DER private key, tagging it `algorithm`.
189    ///
190    /// # Errors
191    ///
192    /// [`IdentityError::Validation`] if the DER is not a private key of the type
193    /// `algorithm` requires, or if an RSA modulus is shorter than
194    /// 2048 bits (RFC 7518 §3.3).
195    pub fn from_pkcs8_der(der: &[u8], algorithm: DpopAlgorithm) -> Result<Self> {
196        // The two families want different byte formats. EC takes the PKCS#8 DER
197        // as-is; RSA signing goes through `signature::RsaKeyPair::from_der`,
198        // which wants the *inner* PKCS#1 `RSAPrivateKey`. Rather than unwrap the
199        // PKCS#8 here, hand jsonwebtoken the PEM form — its PEM decoder already
200        // extracts that inner structure.
201        let encoding = match algorithm {
202            DpopAlgorithm::Es256 => EncodingKey::from_ec_der(der),
203            DpopAlgorithm::Rs256 => EncodingKey::from_rsa_pem(
204                pem_encode(PKCS8_PEM_LABEL, der).as_bytes(),
205            )
206            .map_err(|e| {
207                IdentityError::Validation(format!(
208                    "load DPoP RS256 key: not a valid PKCS#8 RSA private key: {e}"
209                ))
210            })?,
211        };
212
213        // Deriving the public half is also what enforces that the DER holds a key
214        // of the right shape, so there is no separate strength check below. The
215        // backend has to read the private components to compute the public ones,
216        // and it rejects what DPoP would have to reject anyway: an RSA modulus
217        // under 2048 bits comes back `TooSmall` (RFC 7518 §3.3) and an EC key on
218        // any curve but P-256 comes back `InvalidEcdsaKey`, as does an RSA key
219        // labelled ES256 or vice versa. `key_strength_is_enforced_by_the_backend`
220        // in this module's tests pins each of those, so a backend that relaxes one
221        // fails the suite rather than silently widening what DPoP accepts.
222        let public = Jwk::from_encoding_key(&encoding, algorithm.jwt()).map_err(|e| {
223            IdentityError::Validation(format!(
224                "load DPoP {algorithm} key: cannot derive the public key: {e}"
225            ))
226        })?;
227
228        Ok(Self {
229            algorithm,
230            encoding,
231            public,
232            pkcs8: Zeroizing::new(der.to_vec()),
233        })
234    }
235
236    /// Loads a key pair from a PKCS#8 PEM private key, tagging it `algorithm`.
237    ///
238    /// Pair it with [`DpopKey::to_pkcs8_pem`] to round-trip a persisted key.
239    ///
240    /// # Errors
241    ///
242    /// [`IdentityError::Validation`] if `pem` is not a single PKCS#8
243    /// `PRIVATE KEY` block holding a key of the type `algorithm` requires.
244    pub fn from_pkcs8_pem(pem: &str, algorithm: DpopAlgorithm) -> Result<Self> {
245        let der = pem_decode(pem, PKCS8_PEM_LABEL)?;
246        Self::from_pkcs8_der(&der, algorithm)
247    }
248
249    /// Loads a key pair from a **private** JWK document (RFC 7517 §4,
250    /// RFC 7518 §6.2.2 / §6.3.2).
251    ///
252    /// The JWK's `alg` member selects the algorithm when present; otherwise it is
253    /// inferred from `kty` (`EC` → ES256, `RSA` → RS256). An RSA JWK must carry
254    /// the full Chinese-Remainder set — `n`, `e`, `d`, `p`, `q`, `dp`, `dq`, `qi`
255    /// — because the backend validates the components against each other rather
256    /// than recomputing them.
257    ///
258    /// # Errors
259    ///
260    /// - [`IdentityError::Deserialization`] — `jwk` is not valid JSON.
261    /// - [`IdentityError::Validation`] — a required member is missing, a member
262    ///   is not valid base64url, or the components do not form a usable key.
263    /// - [`IdentityError::Configuration`] — the `alg` member names an algorithm
264    ///   DPoP does not allow.
265    pub fn from_private_jwk(jwk: &str) -> Result<Self> {
266        let parsed: PrivateJwk = serde_json::from_str(jwk)
267            .map_err(|e| IdentityError::Deserialization(format!("parse DPoP private JWK: {e}")))?;
268
269        let algorithm = if parsed.alg.is_empty() {
270            match parsed.kty.as_str() {
271                "EC" => DpopAlgorithm::Es256,
272                "RSA" => DpopAlgorithm::Rs256,
273                other => {
274                    return Err(IdentityError::Validation(format!(
275                        "DPoP private JWK has key type {other:?}: expected \"EC\" or \"RSA\""
276                    )));
277                }
278            }
279        } else {
280            parsed.alg.parse()?
281        };
282
283        let pkcs8 = match algorithm {
284            DpopAlgorithm::Es256 => ec_jwk_to_pkcs8(&parsed)?,
285            DpopAlgorithm::Rs256 => rsa_jwk_to_pkcs8(&parsed)?,
286        };
287        let key = Self::from_pkcs8_der(&pkcs8, algorithm)?;
288        if algorithm == DpopAlgorithm::Es256 {
289            // The key is built from `d` alone. `x` and `y` are REQUIRED
290            // (RFC 7518 §6.2.1) and must describe the same key, or a JWK whose
291            // public half disagrees with `d` would load as a different key.
292            let public = key.public_jwk();
293            for (member, given, derived) in
294                [("x", &parsed.x, &public.x), ("y", &parsed.y, &public.y)]
295            {
296                if given.is_empty() {
297                    return Err(IdentityError::Validation(format!(
298                        "DPoP private JWK is missing required member {member:?}"
299                    )));
300                }
301                if given != derived {
302                    return Err(IdentityError::Validation(format!(
303                        "DPoP private JWK member {member:?} does not match the public key \
304                         derived from \"d\""
305                    )));
306                }
307            }
308        }
309        Ok(key)
310    }
311
312    /// Returns the key's DPoP signing algorithm.
313    pub const fn algorithm(&self) -> DpopAlgorithm {
314        self.algorithm
315    }
316
317    /// Returns the public half as a JWK — the form embedded in a proof's `jwk`
318    /// header (RFC 9449 §4.2). It carries no private material.
319    pub fn public_jwk(&self) -> JsonWebKey {
320        let mut key = JsonWebKey {
321            kty: String::new(),
322            kid: String::new(),
323            use_: "sig".to_string(),
324            alg: self.algorithm.as_str().to_string(),
325            n: String::new(),
326            e: String::new(),
327            crv: String::new(),
328            x: String::new(),
329            y: String::new(),
330            extra: std::collections::HashMap::new(),
331        };
332        match &self.public.algorithm {
333            AlgorithmParameters::EllipticCurve(ec) => {
334                key.kty = "EC".to_string();
335                key.crv = curve_name(&ec.curve);
336                key.x = ec.x.clone();
337                key.y = ec.y.clone();
338            }
339            AlgorithmParameters::RSA(rsa) => {
340                key.kty = "RSA".to_string();
341                key.n = rsa.n.clone();
342                key.e = rsa.e.clone();
343            }
344            // Unreachable: the constructors only admit EC P-256 and RSA keys.
345            // Leaving `kty` empty rather than panicking keeps a library
346            // invariant violation from taking the caller's process down.
347            _ => {}
348        }
349        key
350    }
351
352    /// Returns the RFC 7638 SHA-256 JWK thumbprint of the public key,
353    /// base64url-encoded without padding.
354    ///
355    /// This is the value an authorization server places in a DPoP-bound token's
356    /// `cnf.jkt` (RFC 9449 §6, DPOP-005); compare it against that claim to
357    /// confirm a token is bound to this key.
358    ///
359    /// # Errors
360    ///
361    /// [`IdentityError::Validation`] if the thumbprint cannot be computed.
362    pub fn thumbprint(&self) -> Result<String> {
363        self.public
364            .thumbprint(ThumbprintHash::SHA256)
365            .map_err(|e| IdentityError::Validation(format!("compute DPoP key thumbprint: {e}")))
366    }
367
368    /// Returns the private key in PKCS#8 DER form, for persistence.
369    pub fn to_pkcs8_der(&self) -> &[u8] {
370        &self.pkcs8
371    }
372
373    /// Returns the private key as a PKCS#8 `PRIVATE KEY` PEM block, for
374    /// persistence. Pair it with [`DpopKey::from_pkcs8_pem`] to reload. The
375    /// returned string is zeroed on drop.
376    pub fn to_pkcs8_pem(&self) -> Zeroizing<String> {
377        pem_encode(PKCS8_PEM_LABEL, &self.pkcs8)
378    }
379
380    /// The signing key, for [`crate::dpop`]'s proof builder.
381    pub(crate) const fn encoding_key(&self) -> &EncodingKey {
382        &self.encoding
383    }
384
385    /// The public JWK in `jsonwebtoken`'s representation, for embedding in a
386    /// proof header.
387    pub(crate) const fn embedded_jwk(&self) -> &Jwk {
388        &self.public
389    }
390}
391
392/// Computes the RFC 7638 SHA-256 JWK thumbprint of a **public** JWK,
393/// base64url-encoded without padding (DPOP-005).
394///
395/// Use this to check a DPoP-bound token's `cnf.jkt` against a public key you
396/// hold as a JWK rather than as a [`DpopKey`] — a resource server verifying a
397/// proof it just accepted, for instance, against
398/// [`crate::DpopProof::public_jwk`]. For a key you hold the private half of,
399/// [`DpopKey::thumbprint`] is the direct route.
400///
401/// The thumbprint covers only the required members in lexicographic order
402/// (RFC 7638 §3.2), so `kid`, `use`, and `alg` do not affect it: two JWKs
403/// describing the same key produce the same thumbprint whatever their metadata.
404///
405/// # Errors
406///
407/// [`IdentityError::Validation`] if `key` is not a JWK whose thumbprint is
408/// defined — an unsupported `kty`, or a key missing the members its type
409/// requires.
410///
411/// # Examples
412///
413/// ```
414/// use rs_identity_model::{JsonWebKey, jwk_thumbprint};
415///
416/// # fn main() -> rs_identity_model::Result<()> {
417/// // The RFC 7638 §3.1 canonical example key.
418/// let key: JsonWebKey = serde_json::from_str(
419///     r#"{"kty":"RSA","e":"AQAB","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"}"#,
420/// )
421/// .expect("the RFC 7638 example key parses");
422/// assert_eq!(jwk_thumbprint(&key)?, "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs");
423/// # Ok(())
424/// # }
425/// ```
426pub fn jwk_thumbprint(key: &JsonWebKey) -> Result<String> {
427    // Go via JSON rather than matching on `kty` by hand: the JWK member names are
428    // identical on both sides, so serde does the mapping and a key type added to
429    // either representation later needs no change here.
430    let value = serde_json::to_value(key)
431        .map_err(|e| IdentityError::Validation(format!("serialize JWK for thumbprint: {e}")))?;
432    let jwk: Jwk = serde_json::from_value(value).map_err(|e| {
433        IdentityError::Validation(format!(
434            "JWK thumbprint is not defined for this key: {e} (RFC 7638 §3.2)"
435        ))
436    })?;
437    jwk.thumbprint(ThumbprintHash::SHA256)
438        .map_err(|e| IdentityError::Validation(format!("compute JWK thumbprint: {e}")))
439}
440
441/// Returns the RFC 7518 §6.2.1.1 `crv` name for a curve.
442///
443/// `EllipticCurve` is `#[non_exhaustive]`, so a curve `jsonwebtoken` adds later
444/// falls back to its own serde name rather than silently becoming the wrong
445/// curve or panicking.
446pub(crate) fn curve_name(curve: &EllipticCurve) -> String {
447    match curve {
448        EllipticCurve::P256 => "P-256".to_string(),
449        EllipticCurve::P384 => "P-384".to_string(),
450        EllipticCurve::P521 => "P-521".to_string(),
451        EllipticCurve::Ed25519 => "Ed25519".to_string(),
452        other => serde_json::to_value(other)
453            .ok()
454            .and_then(|v| v.as_str().map(str::to_string))
455            .unwrap_or_default(),
456    }
457}
458
459/// Generates an EC P-256 private key in PKCS#8 DER form.
460fn generate_p256_pkcs8() -> Result<Zeroizing<Vec<u8>>> {
461    // p256 exposes no CSPRNG-free constructor, and pulling `rand` in for one
462    // scalar is not worth it: draw 32 uniform bytes from the OS CSPRNG the way
463    // `PkceChallenge::generate` does and let `from_slice` enforce the valid
464    // scalar range, re-drawing on the (vanishingly rare) rejection.
465    let mut seed = [0u8; 32];
466    for _ in 0..EC_SCALAR_DRAWS {
467        getrandom::fill(&mut seed)
468            .map_err(|e| IdentityError::Configuration(format!("generate DPoP ES256 key: {e}")))?;
469        let secret = p256::SecretKey::from_slice(&seed);
470        seed.fill(0);
471        if let Ok(secret) = secret {
472            return secret
473                .to_pkcs8_der()
474                .map(|der| Zeroizing::new(der.as_bytes().to_vec()))
475                .map_err(|e| {
476                    IdentityError::Configuration(format!(
477                        "generate DPoP ES256 key: encode PKCS#8: {e}"
478                    ))
479                });
480        }
481    }
482    Err(IdentityError::Configuration(format!(
483        "generate DPoP ES256 key: {EC_SCALAR_DRAWS} draws from the system CSPRNG all fell \
484         outside the valid P-256 scalar range, which suggests the random source is broken"
485    )))
486}
487
488/// Generates a 2048-bit RSA private key in PKCS#8 DER form. 2048 is the
489/// RFC 7518 §3.3 minimum for RS256 and the minimum DPOP-007 asserts; it is also
490/// the smallest size `aws_lc_rs::rsa::KeySize` offers, so there is no way to
491/// generate a key this crate would then refuse to load.
492fn generate_rsa_pkcs8() -> Result<Zeroizing<Vec<u8>>> {
493    let pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
494        .map_err(|e| IdentityError::Configuration(format!("generate DPoP RS256 key: {e}")))?;
495    let der: Pkcs8V1Der<'static> = pair.as_der().map_err(|e| {
496        IdentityError::Configuration(format!("generate DPoP RS256 key: encode PKCS#8: {e}"))
497    })?;
498    Ok(Zeroizing::new(der.as_ref().to_vec()))
499}
500
501/// Converts an EC private JWK to PKCS#8 DER via its `d` scalar.
502fn ec_jwk_to_pkcs8(jwk: &PrivateJwk) -> Result<Zeroizing<Vec<u8>>> {
503    if jwk.crv != "P-256" {
504        return Err(IdentityError::Validation(format!(
505            "DPoP ES256 requires curve P-256, got {:?}",
506            jwk.crv
507        )));
508    }
509    let d = decode_b64url(&jwk.d, "d")?;
510    let secret = p256::SecretKey::from_slice(&d).map_err(|e| {
511        IdentityError::Validation(format!(
512            "DPoP private JWK member \"d\" is not a valid P-256 scalar: {e}"
513        ))
514    })?;
515    secret
516        .to_pkcs8_der()
517        .map(|der| Zeroizing::new(der.as_bytes().to_vec()))
518        .map_err(|e| IdentityError::Validation(format!("encode DPoP ES256 key as PKCS#8: {e}")))
519}
520
521/// Converts an RSA private JWK to PKCS#8 DER via its CRT components.
522fn rsa_jwk_to_pkcs8(jwk: &PrivateJwk) -> Result<Zeroizing<Vec<u8>>> {
523    let components = aws_lc_rs::rsa::KeyPairComponents {
524        public_key: aws_lc_rs::rsa::PublicKeyComponents {
525            n: decode_b64url(&jwk.n, "n")?,
526            e: decode_b64url(&jwk.e, "e")?,
527        },
528        d: decode_b64url(&jwk.d, "d")?,
529        p: decode_b64url(&jwk.p, "p")?,
530        q: decode_b64url(&jwk.q, "q")?,
531        dP: decode_b64url(&jwk.dp, "dp")?,
532        dQ: decode_b64url(&jwk.dq, "dq")?,
533        qInv: decode_b64url(&jwk.qi, "qi")?,
534    };
535    let pair = aws_lc_rs::rsa::KeyPair::from_components(&components).map_err(|e| {
536        IdentityError::Validation(format!(
537            "DPoP private JWK does not form a valid RSA key: {e}. An RSA JWK must carry \
538             \"n\", \"e\", \"d\", \"p\", \"q\", \"dp\", \"dq\", and \"qi\" \
539             (RFC 7518 §6.3.2), and the components must be consistent"
540        ))
541    })?;
542    let der: Pkcs8V1Der<'static> = pair
543        .as_der()
544        .map_err(|e| IdentityError::Validation(format!("encode DPoP RS256 key as PKCS#8: {e}")))?;
545    Ok(Zeroizing::new(der.as_ref().to_vec()))
546}
547
548/// Decodes a base64url JWK member, naming it in the error. The result may be
549/// private key material, so it is zeroed on drop.
550fn decode_b64url(value: &str, member: &str) -> Result<Zeroizing<Vec<u8>>> {
551    if value.is_empty() {
552        return Err(IdentityError::Validation(format!(
553            "DPoP private JWK is missing required member {member:?}"
554        )));
555    }
556    URL_SAFE_NO_PAD
557        .decode(value)
558        .map(Zeroizing::new)
559        .map_err(|e| {
560            IdentityError::Validation(format!(
561                "DPoP private JWK member {member:?} is not valid base64url: {e}"
562            ))
563        })
564}
565
566/// Wraps DER in a PEM block with `label` (RFC 7468 §2): 64-character base64
567/// lines between the BEGIN/END markers.
568fn pem_encode(label: &str, der: &[u8]) -> Zeroizing<String> {
569    let body = Zeroizing::new(BASE64_PAD.encode(der));
570    let mut out = String::with_capacity(body.len() + body.len() / 64 + 2 * label.len() + 64);
571    out.push_str("-----BEGIN ");
572    out.push_str(label);
573    out.push_str("-----\n");
574    for line in body.as_bytes().chunks(64) {
575        // `chunks` of a base64 string always split on character boundaries.
576        out.push_str(std::str::from_utf8(line).unwrap_or_default());
577        out.push('\n');
578    }
579    out.push_str("-----END ");
580    out.push_str(label);
581    out.push_str("-----\n");
582    Zeroizing::new(out)
583}
584
585/// Extracts the DER from a PEM block, requiring it to carry `label`.
586fn pem_decode(pem: &str, label: &str) -> Result<Zeroizing<Vec<u8>>> {
587    let begin = format!("-----BEGIN {label}-----");
588    let end = format!("-----END {label}-----");
589    let start = pem
590        .find(&begin)
591        .ok_or_else(|| IdentityError::Validation(format!("PEM input has no {begin:?} block")))?;
592    let body_start = start + begin.len();
593    let body_end = pem[body_start..]
594        .find(&end)
595        .map(|i| body_start + i)
596        .ok_or_else(|| IdentityError::Validation(format!("PEM block is missing {end:?}")))?;
597    let body: Zeroizing<String> = Zeroizing::new(
598        pem[body_start..body_end]
599            .chars()
600            .filter(|c| !c.is_whitespace())
601            .collect(),
602    );
603    BASE64_PAD
604        .decode(body.as_bytes())
605        .map(Zeroizing::new)
606        .map_err(|e| IdentityError::Validation(format!("PEM body is not valid base64: {e}")))
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612
613    /// PEM encoding round-trips, wraps at 64 characters (RFC 7468 §2), and rejects
614    /// a block carrying the wrong label.
615    #[test]
616    fn pem_round_trips_and_checks_the_label() {
617        let der: Vec<u8> = (0u8..=255).collect();
618        let pem = pem_encode(PKCS8_PEM_LABEL, &der);
619        assert_eq!(*pem_decode(&pem, PKCS8_PEM_LABEL).expect("decode"), der);
620
621        for line in pem.lines().filter(|l| !l.starts_with("-----")) {
622            assert!(line.len() <= 64, "PEM body line too long: {line}");
623        }
624        assert!(pem.ends_with("-----END PRIVATE KEY-----\n"));
625
626        // A different label is not silently accepted.
627        assert!(pem_decode(&pem, "EC PRIVATE KEY").is_err());
628        // Neither is a truncated block or plain garbage.
629        assert!(pem_decode("-----BEGIN PRIVATE KEY-----\nAAAA\n", PKCS8_PEM_LABEL).is_err());
630        assert!(pem_decode("not a pem at all", PKCS8_PEM_LABEL).is_err());
631        assert!(
632            pem_decode(
633                "-----BEGIN PRIVATE KEY-----\n!!!!\n-----END PRIVATE KEY-----\n",
634                PKCS8_PEM_LABEL
635            )
636            .is_err(),
637            "a non-base64 body must be rejected"
638        );
639    }
640
641    /// An empty PEM body decodes to empty rather than erroring; the key parser
642    /// downstream is what rejects it. Pinned so the behaviour is deliberate.
643    #[test]
644    fn pem_decode_accepts_an_empty_body() {
645        let pem = "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n";
646        assert_eq!(
647            *pem_decode(pem, PKCS8_PEM_LABEL).expect("decode"),
648            Vec::<u8>::new()
649        );
650        assert!(DpopKey::from_pkcs8_pem(pem, DpopAlgorithm::Es256).is_err());
651    }
652
653    /// A deliberately weak 1024-bit RSA private key: throwaway test material
654    /// that exists only to prove the loader rejects it.
655    ///
656    /// This one is committed because it cannot be minted at run time — the
657    /// crate's RSA backend (`aws_lc_rs::rsa::KeySize`) offers no size below
658    /// 2048, which is the whole point of the check below, and the `rsa` crate
659    /// that could generate one is ruled out by RUSTSEC-2023-0071 (see the
660    /// dependency note in `Cargo.toml`). Its wrong-curve counterpart *is*
661    /// generated, by [`p384_pem`].
662    const RSA_1024_DER: &[u8] = include_bytes!("testdata/rsa-1024-too-small.pkcs8.der");
663
664    /// Mints an EC P-384 key in PKCS#8 PEM form — a curve ES256 must refuse.
665    ///
666    /// Generated per run rather than committed, so the only key material in the
667    /// tree is the RSA one that cannot be generated. The draw-and-retry mirrors
668    /// [`generate_p256_pkcs8`]: 48 uniform bytes from the OS CSPRNG, with
669    /// `from_slice` enforcing the valid scalar range.
670    fn p384_pem() -> String {
671        let mut seed = [0u8; 48];
672        for _ in 0..EC_SCALAR_DRAWS {
673            getrandom::fill(&mut seed).expect("system CSPRNG unavailable");
674            let secret = p384::SecretKey::from_slice(&seed);
675            seed.fill(0);
676            if let Ok(secret) = secret {
677                let der = secret.to_pkcs8_der().expect("encode P-384 PKCS#8");
678                return pem_encode(PKCS8_PEM_LABEL, der.as_bytes()).to_string();
679            }
680        }
681        panic!("{EC_SCALAR_DRAWS} draws all fell outside the P-384 scalar range");
682    }
683
684    /// DPOP-007: the key-strength rules RFC 9449 §4.1 and RFC 7518 §3.3 impose are
685    /// enforced — an RSA modulus below 2048 bits and an EC key on a curve other
686    /// than P-256 are both refused, as is either key type labelled with the other's
687    /// algorithm.
688    ///
689    /// The enforcement lives in the crypto backend rather than in a check of our
690    /// own (see [`DpopKey::from_pkcs8_der`]), which is why it is pinned here: a
691    /// backend release that started accepting one of these would otherwise widen
692    /// what this crate accepts with nothing failing.
693    #[test]
694    fn key_strength_is_enforced_by_the_backend() {
695        let too_small = DpopKey::from_pkcs8_der(RSA_1024_DER, DpopAlgorithm::Rs256)
696            .expect_err("a 1024-bit RSA key is below the RFC 7518 §3.3 minimum");
697        assert!(
698            matches!(too_small, IdentityError::Validation(_)),
699            "got {too_small:?}"
700        );
701
702        let wrong_curve = DpopKey::from_pkcs8_pem(&p384_pem(), DpopAlgorithm::Es256)
703            .expect_err("ES256 requires curve P-256");
704        assert!(
705            matches!(wrong_curve, IdentityError::Validation(_)),
706            "got {wrong_curve:?}"
707        );
708
709        // And the cross-labelled combinations, which would produce proofs whose
710        // `alg` header does not describe the signature.
711        let ec = DpopKey::generate(DpopAlgorithm::Es256).expect("generate ES256");
712        let rsa = DpopKey::generate(DpopAlgorithm::Rs256).expect("generate RS256");
713        assert!(DpopKey::from_pkcs8_der(ec.to_pkcs8_der(), DpopAlgorithm::Rs256).is_err());
714        assert!(DpopKey::from_pkcs8_der(rsa.to_pkcs8_der(), DpopAlgorithm::Es256).is_err());
715        // The correct labelling still loads, so the test is not simply rejecting
716        // everything.
717        assert!(DpopKey::from_pkcs8_der(ec.to_pkcs8_der(), DpopAlgorithm::Es256).is_ok());
718        assert!(DpopKey::from_pkcs8_der(rsa.to_pkcs8_der(), DpopAlgorithm::Rs256).is_ok());
719    }
720
721    /// Algorithm names round-trip through their JWA string form.
722    #[test]
723    fn algorithm_round_trips_through_its_jwa_name() {
724        for algorithm in [DpopAlgorithm::Es256, DpopAlgorithm::Rs256] {
725            assert_eq!(
726                algorithm.as_str().parse::<DpopAlgorithm>().expect("parses"),
727                algorithm
728            );
729            assert_eq!(algorithm.to_string(), algorithm.as_str());
730        }
731        assert_eq!(DpopAlgorithm::Es256.as_str(), "ES256");
732        assert_eq!(DpopAlgorithm::Rs256.as_str(), "RS256");
733    }
734
735    /// A curve name is returned for every variant, including a future one.
736    #[test]
737    fn curve_names_follow_rfc_7518() {
738        assert_eq!(curve_name(&EllipticCurve::P256), "P-256");
739        assert_eq!(curve_name(&EllipticCurve::P384), "P-384");
740        assert_eq!(curve_name(&EllipticCurve::P521), "P-521");
741    }
742
743    /// A base64url JWK member is decoded, and a missing or malformed one is
744    /// reported by name so a caller can fix the right member.
745    #[test]
746    fn jwk_members_are_decoded_and_named_in_errors() {
747        assert_eq!(*decode_b64url("AQAB", "e").expect("decode"), vec![1, 0, 1]);
748
749        let missing = decode_b64url("", "d").expect_err("missing member");
750        assert!(
751            missing.to_string().contains("\"d\""),
752            "error must name the member: {missing}"
753        );
754        let malformed = decode_b64url("not base64url!!", "n").expect_err("malformed");
755        assert!(
756            malformed.to_string().contains("\"n\""),
757            "error must name the member: {malformed}"
758        );
759        // Standard base64 padding is not base64url and is rejected.
760        assert!(decode_b64url("AQAB==", "e").is_err());
761    }
762
763    /// The derived public JWK carries the public members and nothing else — no
764    /// place for private material to hide.
765    #[test]
766    fn public_jwk_carries_only_public_members() {
767        let ec = DpopKey::generate(DpopAlgorithm::Es256).expect("generate ES256");
768        let jwk = ec.public_jwk();
769        assert_eq!(jwk.kty, "EC");
770        assert_eq!(jwk.crv, "P-256");
771        assert_eq!(jwk.use_, "sig");
772        assert_eq!(jwk.alg, "ES256");
773        assert!(!jwk.x.is_empty() && !jwk.y.is_empty());
774        assert!(jwk.n.is_empty() && jwk.e.is_empty());
775        assert!(jwk.extra.is_empty(), "no stray members: {:?}", jwk.extra);
776
777        // Serialized, it must contain no private member.
778        let json = serde_json::to_string(&jwk).expect("serialize");
779        for private in [
780            "\"d\"", "\"p\"", "\"q\"", "\"dp\"", "\"dq\"", "\"qi\"", "\"k\"",
781        ] {
782            assert!(
783                !json.contains(private),
784                "public JWK leaks {private}: {json}"
785            );
786        }
787
788        let rsa = DpopKey::generate(DpopAlgorithm::Rs256).expect("generate RS256");
789        let jwk = rsa.public_jwk();
790        assert_eq!(jwk.kty, "RSA");
791        assert!(!jwk.n.is_empty() && !jwk.e.is_empty());
792        assert!(jwk.crv.is_empty() && jwk.x.is_empty() && jwk.y.is_empty());
793    }
794
795    /// `jwk_thumbprint` ignores the members RFC 7638 §3.2 excludes, so two JWKs
796    /// describing one key agree however they are labelled.
797    #[test]
798    fn jwk_thumbprint_ignores_non_required_members() {
799        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate key");
800        let plain = key.public_jwk();
801        let expected = key.thumbprint().expect("thumbprint");
802        assert_eq!(jwk_thumbprint(&plain).expect("thumbprint"), expected);
803
804        let mut labelled = plain.clone();
805        labelled.kid = "rotated-2026".to_string();
806        labelled.use_ = String::new();
807        labelled.alg = String::new();
808        assert_eq!(
809            jwk_thumbprint(&labelled).expect("thumbprint"),
810            expected,
811            "kid/use/alg must not affect the thumbprint"
812        );
813    }
814
815    /// A JWK whose thumbprint is undefined is an error, not a panic or a bogus
816    /// value that would silently fail a `cnf.jkt` comparison.
817    #[test]
818    fn jwk_thumbprint_rejects_keys_it_cannot_hash() {
819        for json in [
820            r#"{"kty":"RSA"}"#,
821            r#"{"kty":"EC","crv":"P-256"}"#,
822            r#"{"kty":"unknown-kty"}"#,
823            r#"{}"#,
824        ] {
825            let key: JsonWebKey = serde_json::from_str(json).expect("parse");
826            assert!(
827                jwk_thumbprint(&key).is_err(),
828                "{json} has no defined thumbprint"
829            );
830        }
831    }
832
833    /// Generation draws fresh entropy per call: repeated ES256 keys differ. A
834    /// generator that returned a constant would sender-constrain every client to
835    /// the same key.
836    #[test]
837    fn generated_keys_are_distinct() {
838        let a = DpopKey::generate(DpopAlgorithm::Es256).expect("generate");
839        let b = DpopKey::generate(DpopAlgorithm::Es256).expect("generate");
840        assert_ne!(
841            a.thumbprint().expect("thumbprint"),
842            b.thumbprint().expect("thumbprint")
843        );
844        assert_ne!(a.to_pkcs8_der(), b.to_pkcs8_der());
845    }
846
847    /// A private JWK with no `alg` member infers the algorithm from `kty`, matching
848    /// `go/pkg/dpop`'s `algForJWK`.
849    #[test]
850    fn ec_private_jwk_requires_matching_public_members() {
851        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate");
852        let other = DpopKey::generate(DpopAlgorithm::Es256).expect("generate");
853        use p256::pkcs8::DecodePrivateKey;
854        let secret =
855            p256::SecretKey::from_pkcs8_der(key.to_pkcs8_der()).expect("parse generated PKCS#8");
856        let d = URL_SAFE_NO_PAD.encode(secret.to_bytes());
857        let (public, wrong) = (key.public_jwk(), other.public_jwk());
858        let jwk = |crv: &str, x: &str, y: &str| {
859            serde_json::json!({"kty": "EC", "crv": crv, "x": x, "y": y, "d": d}).to_string()
860        };
861
862        DpopKey::from_private_jwk(&jwk("P-256", &public.x, &public.y)).expect("consistent JWK");
863        for (label, document) in [
864            ("missing crv", jwk("", &public.x, &public.y)),
865            ("missing x", jwk("P-256", "", &public.y)),
866            ("missing y", jwk("P-256", &public.x, "")),
867            ("x from another key", jwk("P-256", &wrong.x, &public.y)),
868            ("y from another key", jwk("P-256", &public.x, &wrong.y)),
869        ] {
870            assert!(
871                matches!(
872                    DpopKey::from_private_jwk(&document),
873                    Err(IdentityError::Validation(_))
874                ),
875                "{label} must be rejected"
876            );
877        }
878    }
879
880    #[test]
881    fn private_jwk_infers_the_algorithm_from_kty() {
882        let key = DpopKey::generate(DpopAlgorithm::Es256).expect("generate");
883        // Rebuild the fixture-style JWK from the generated key's own scalar. The
884        // PKCS#8 holds it; round-trip through p256 to read it back out.
885        use p256::pkcs8::DecodePrivateKey;
886        let secret =
887            p256::SecretKey::from_pkcs8_der(key.to_pkcs8_der()).expect("parse generated PKCS#8");
888        let d = URL_SAFE_NO_PAD.encode(secret.to_bytes());
889        let public = key.public_jwk();
890        let jwk = serde_json::json!({
891            "kty": "EC", "crv": "P-256", "x": public.x, "y": public.y, "d": d,
892        });
893        let loaded = DpopKey::from_private_jwk(&jwk.to_string()).expect("load without alg");
894        assert_eq!(loaded.algorithm(), DpopAlgorithm::Es256);
895        assert_eq!(
896            loaded.thumbprint().expect("thumbprint"),
897            key.thumbprint().expect("thumbprint")
898        );
899    }
900}