1use 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
18const EC_SCALAR_DRAWS: usize = 8;
23
24const PKCS8_PEM_LABEL: &str = "PRIVATE KEY";
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
34pub enum DpopAlgorithm {
35 Es256,
37 Rs256,
40}
41
42impl DpopAlgorithm {
43 pub const fn as_str(self) -> &'static str {
46 match self {
47 Self::Es256 => "ES256",
48 Self::Rs256 => "RS256",
49 }
50 }
51
52 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 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#[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 #[serde(default)]
105 x: String,
106 #[serde(default)]
107 y: String,
108 #[serde(default)]
109 d: String,
110 #[serde(default)]
112 n: String,
113 #[serde(default)]
114 e: String,
115 #[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#[derive(Clone)]
144pub struct DpopKey {
145 algorithm: DpopAlgorithm,
146 encoding: EncodingKey,
148 public: Jwk,
150 pkcs8: Zeroizing<Vec<u8>>,
152}
153
154impl 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 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 pub fn from_pkcs8_der(der: &[u8], algorithm: DpopAlgorithm) -> Result<Self> {
196 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 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 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 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 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 pub const fn algorithm(&self) -> DpopAlgorithm {
314 self.algorithm
315 }
316
317 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 _ => {}
348 }
349 key
350 }
351
352 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 pub fn to_pkcs8_der(&self) -> &[u8] {
370 &self.pkcs8
371 }
372
373 pub fn to_pkcs8_pem(&self) -> Zeroizing<String> {
377 pem_encode(PKCS8_PEM_LABEL, &self.pkcs8)
378 }
379
380 pub(crate) const fn encoding_key(&self) -> &EncodingKey {
382 &self.encoding
383 }
384
385 pub(crate) const fn embedded_jwk(&self) -> &Jwk {
388 &self.public
389 }
390}
391
392pub fn jwk_thumbprint(key: &JsonWebKey) -> Result<String> {
427 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
441pub(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
459fn generate_p256_pkcs8() -> Result<Zeroizing<Vec<u8>>> {
461 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
488fn 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
501fn 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
521fn 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
548fn 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
566fn 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 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
585fn 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 #[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 assert!(pem_decode(&pem, "EC PRIVATE KEY").is_err());
628 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 #[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 const RSA_1024_DER: &[u8] = include_bytes!("testdata/rsa-1024-too-small.pkcs8.der");
663
664 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 #[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 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 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 #[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 #[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 #[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 assert!(decode_b64url("AQAB==", "e").is_err());
761 }
762
763 #[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 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 #[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 #[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 #[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 #[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 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}