1use crate::errors::{AuthError, Result};
9use crate::security::secure_jwt::SecureJwtValidator;
10use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
11use chrono::{DateTime, Duration, Utc};
12use jsonwebtoken::DecodingKey;
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct DpopProofClaims {
19 pub jti: String,
21
22 pub htm: String,
24
25 pub htu: String,
27
28 pub iat: i64,
30
31 #[serde(skip_serializing_if = "Option::is_none")]
33 pub ath: Option<String>,
34
35 #[serde(skip_serializing_if = "Option::is_none")]
37 pub nonce: Option<String>,
38}
39
40#[derive(Debug, Clone)]
42pub struct DpopKeyBinding {
43 pub public_key_jwk: serde_json::Value,
45
46 pub algorithm: String,
48
49 pub key_id: Option<String>,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
55pub struct DpopConfirmation {
56 pub jkt: String,
58}
59
60#[derive(Debug, Clone)]
62pub struct DpopValidationResult {
63 pub is_valid: bool,
65
66 pub errors: Vec<String>,
68
69 pub public_key_jwk: Option<serde_json::Value>,
71
72 pub jwk_thumbprint: Option<String>,
74}
75
76#[must_use = "a verified proof is not recorded until it is committed"]
82#[derive(Debug)]
83pub(crate) struct VerifiedDpopProof {
84 result: DpopValidationResult,
85 replay_id: String,
86 keep_until: DateTime<Utc>,
87}
88
89fn der_push_length(out: &mut Vec<u8>, len: usize) {
91 if len < 0x80 {
92 out.push(len as u8);
93 } else {
94 let bytes = len.to_be_bytes();
95 let skip = bytes.iter().take_while(|&&b| b == 0).count();
96 let significant = &bytes[skip..];
97 out.push(0x80 | significant.len() as u8);
98 out.extend_from_slice(significant);
99 }
100}
101
102fn der_unsigned_integer(value: &[u8]) -> Vec<u8> {
104 let mut body = Vec::with_capacity(value.len() + 1);
105 if value[0] & 0x80 != 0 {
106 body.push(0x00); }
108 body.extend_from_slice(value);
109 let mut out = vec![0x02];
110 der_push_length(&mut out, body.len());
111 out.extend(body);
112 out
113}
114
115pub struct DpopManager {
117 used_nonces: tokio::sync::RwLock<HashMap<String, DateTime<Utc>>>,
119
120 proof_expiration: Duration,
122
123 max_replay_entries: usize,
125
126 sweep_interval: Duration,
128
129 last_sweep: std::sync::Mutex<DateTime<Utc>>,
131
132 earliest_expiry: std::sync::Mutex<DateTime<Utc>>,
134
135 jwt_validator: SecureJwtValidator,
137
138 clock_skew: Duration,
140}
141
142impl std::fmt::Debug for DpopManager {
143 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144 let mut d = f.debug_struct("DpopManager");
145 d.field(
146 "used_nonces",
147 &crate::utils::redact::redacted(&self.used_nonces),
148 );
149 d.field("proof_expiration", &self.proof_expiration);
150 d.field("clock_skew", &self.clock_skew);
151 d.finish()
152 }
153}
154
155#[cfg(test)]
156impl DpopManager {
157 pub(crate) async fn insert_record_for_test(&self, key: &str, until: DateTime<Utc>) {
159 {
160 let mut earliest = self
161 .earliest_expiry
162 .lock()
163 .unwrap_or_else(|e| e.into_inner());
164 *earliest = (*earliest).min(until);
165 }
166 self.used_nonces
167 .write()
168 .await
169 .insert(key.to_string(), until);
170 }
171}
172
173impl DpopManager {
174 pub fn new(jwt_validator: SecureJwtValidator) -> Self {
176 Self {
177 used_nonces: tokio::sync::RwLock::new(HashMap::new()),
178 proof_expiration: Duration::seconds(60),
179 max_replay_entries: 100_000,
180 sweep_interval: Duration::seconds(1),
181 last_sweep: std::sync::Mutex::new(DateTime::<Utc>::UNIX_EPOCH),
182 earliest_expiry: std::sync::Mutex::new(DateTime::<Utc>::MAX_UTC),
183 jwt_validator,
184 clock_skew: Duration::seconds(30),
185 }
186 }
187
188 pub async fn validate_dpop_proof(
190 &self,
191 dpop_proof: &str,
192 http_method: &str,
193 http_uri: &str,
194 access_token: Option<&str>,
195 expected_nonce: Option<&str>,
196 ) -> Result<DpopValidationResult> {
197 self.validate_dpop_proof_for_key(
198 dpop_proof,
199 http_method,
200 http_uri,
201 access_token,
202 expected_nonce,
203 None,
204 )
205 .await
206 }
207
208 pub async fn validate_dpop_proof_for_key(
212 &self,
213 dpop_proof: &str,
214 http_method: &str,
215 http_uri: &str,
216 access_token: Option<&str>,
217 expected_nonce: Option<&str>,
218 expected_jkt: Option<&str>,
219 ) -> Result<DpopValidationResult> {
220 let verified = self
221 .verify_dpop_proof(
222 dpop_proof,
223 http_method,
224 http_uri,
225 access_token,
226 expected_nonce,
227 expected_jkt,
228 )
229 .await?;
230 self.commit_dpop_proof(verified).await
231 }
232
233 pub(crate) async fn verify_dpop_proof(
237 &self,
238 dpop_proof: &str,
239 http_method: &str,
240 http_uri: &str,
241 access_token: Option<&str>,
242 expected_nonce: Option<&str>,
243 expected_jkt: Option<&str>,
244 ) -> Result<VerifiedDpopProof> {
245 let mut errors = Vec::new();
246
247 let (header, claims) = self.parse_dpop_proof(dpop_proof).map_err(|e| {
249 errors.push(format!("Failed to parse DPoP proof: {}", e));
250 e
251 })?;
252
253 self.validate_dpop_header(&header, &mut errors)?;
255 if !errors.is_empty() {
256 return Err(Self::rejected(&errors));
257 }
258
259 let public_key_jwk = header
261 .get("jwk")
262 .ok_or_else(|| AuthError::auth_method("dpop", "Missing JWK in DPoP proof header"))?
263 .clone();
264
265 if let Some(obj) = public_key_jwk.as_object() {
267 for private_member in ["d", "p", "q", "dp", "dq", "qi", "oth", "k"] {
268 if obj.contains_key(private_member) {
269 return Err(AuthError::auth_method(
270 "dpop",
271 "DPoP proof jwk header contains private key material",
272 ));
273 }
274 }
275 }
276
277 let jwk_thumbprint = self.calculate_jwk_thumbprint(&public_key_jwk)?;
279
280 self.verify_dpop_signature(dpop_proof, &public_key_jwk, &mut errors)?;
282
283 if let Some(expected) = expected_jkt
285 && !bool::from(subtle::ConstantTimeEq::ct_eq(
286 jwk_thumbprint.as_bytes(),
287 expected.as_bytes(),
288 ))
289 {
290 return Err(AuthError::auth_method(
291 "dpop",
292 "DPoP proof key does not match the token's key binding",
293 ));
294 }
295
296 self.validate_dpop_claims(
298 &claims,
299 http_method,
300 http_uri,
301 access_token,
302 expected_nonce,
303 &mut errors,
304 )
305 .await?;
306
307 if claims.jti.is_empty() || claims.jti.len() > 256 {
309 errors.push("DPoP proof jti must be 1 to 256 bytes".to_string());
310 }
311
312 if !errors.is_empty() {
314 return Err(Self::rejected(&errors));
315 }
316
317 let keep_until = chrono::TimeZone::timestamp_opt(&Utc, claims.iat, 0)
319 .single()
320 .and_then(|iat| iat.checked_add_signed(self.proof_expiration + self.clock_skew))
321 .ok_or_else(|| AuthError::auth_method("dpop", "DPoP proof iat is out of range"))?;
322 let key = Self::replay_key(&jwk_thumbprint, &claims.jti);
323 if self.used_nonces.read().await.contains_key(&key) {
324 return Err(Self::rejected(&["DPoP proof JTI already used".to_string()]));
325 }
326
327 Ok(VerifiedDpopProof {
328 result: DpopValidationResult {
329 is_valid: true,
330 errors,
331 public_key_jwk: Some(public_key_jwk),
332 jwk_thumbprint: Some(jwk_thumbprint),
333 },
334 replay_id: key,
335 keep_until,
336 })
337 }
338
339 pub(crate) async fn commit_dpop_proof(
347 &self,
348 verified: VerifiedDpopProof,
349 ) -> Result<DpopValidationResult> {
350 let now = Utc::now();
351 let mut used = self.used_nonces.write().await;
352 let full = used.len() >= self.max_replay_entries;
353 if full || used.len().is_multiple_of(256) {
354 let due = {
355 let mut last = self.last_sweep.lock().unwrap_or_else(|e| e.into_inner());
356 if now - *last >= self.sweep_interval {
357 *last = now;
358 true
359 } else {
360 false
361 }
362 };
363 let expired_waiting = *self
366 .earliest_expiry
367 .lock()
368 .unwrap_or_else(|e| e.into_inner())
369 <= now;
370 if due || (full && expired_waiting) {
371 used.retain(|_, until| *until > now);
372 *self
373 .earliest_expiry
374 .lock()
375 .unwrap_or_else(|e| e.into_inner()) = used
376 .values()
377 .min()
378 .copied()
379 .unwrap_or(DateTime::<Utc>::MAX_UTC);
380 }
381 }
382 if used.contains_key(&verified.replay_id) {
383 return Err(Self::rejected(&["DPoP proof JTI already used".to_string()]));
384 }
385 if used.len() >= self.max_replay_entries {
386 return Err(Self::rejected(&["DPoP replay cache is full".to_string()]));
387 }
388 {
389 let mut earliest = self
390 .earliest_expiry
391 .lock()
392 .unwrap_or_else(|e| e.into_inner());
393 *earliest = (*earliest).min(verified.keep_until);
394 }
395 used.insert(verified.replay_id, verified.keep_until);
396 Ok(verified.result)
397 }
398
399 fn replay_key(jwk_thumbprint: &str, jti: &str) -> String {
401 use sha2::{Digest, Sha256};
402 let mut hasher = Sha256::new();
403 hasher.update(jwk_thumbprint.as_bytes());
404 hasher.update([0x1f]);
405 hasher.update(jti.as_bytes());
406 URL_SAFE_NO_PAD.encode(hasher.finalize())
407 }
408
409 fn rejected(errors: &[String]) -> AuthError {
411 AuthError::auth_method(
412 "dpop",
413 format!("DPoP proof rejected: {}", errors.join("; ")),
414 )
415 }
416
417 pub fn create_dpop_confirmation(
419 &self,
420 public_key_jwk: &serde_json::Value,
421 ) -> Result<DpopConfirmation> {
422 let jkt = self.calculate_jwk_thumbprint(public_key_jwk)?;
423
424 Ok(DpopConfirmation { jkt })
425 }
426
427 pub fn validate_dpop_bound_token(
429 &self,
430 token_confirmation: &DpopConfirmation,
431 dpop_proof_jwk: &serde_json::Value,
432 ) -> Result<bool> {
433 let proof_thumbprint = self.calculate_jwk_thumbprint(dpop_proof_jwk)?;
434
435 if bool::from(subtle::ConstantTimeEq::ct_eq(
436 token_confirmation.jkt.as_bytes(),
437 proof_thumbprint.as_bytes(),
438 )) {
439 Ok(true)
440 } else {
441 Err(AuthError::auth_method(
442 "dpop",
443 "DPoP proof key does not match the token's key binding",
444 ))
445 }
446 }
447
448 pub async fn validate_dpop_bound_jwt(
458 &self,
459 access_token: &str,
460 key: &DecodingKey,
461 audience: &str,
462 dpop_proof: &str,
463 http_method: &str,
464 http_uri: &str,
465 ) -> Result<()> {
466 if audience.is_empty() {
468 return Err(AuthError::InvalidToken(
469 "An audience is required".to_string(),
470 ));
471 }
472
473 let claims = self
474 .jwt_validator
475 .validate_token(access_token, key, true)
476 .map_err(|e| {
477 tracing::warn!("DPoP-bound access token refused: {e}");
478 AuthError::InvalidToken("Invalid DPoP-bound access token".to_string())
479 })?;
480
481 let now = Utc::now().timestamp();
486 let skew = self.clock_skew.num_seconds();
487 if claims.exp.saturating_add(skew) < now || claims.nbf.saturating_sub(skew) > now {
488 tracing::warn!("DPoP-bound access token outside its validity period");
489 return Err(AuthError::InvalidToken(
490 "Invalid DPoP-bound access token".to_string(),
491 ));
492 }
493
494 if claims.typ != "access" {
495 return Err(AuthError::InvalidToken("Not an access token".to_string()));
496 }
497 if claims.aud != audience {
499 return Err(AuthError::InvalidToken(
500 "Access token is for another audience".to_string(),
501 ));
502 }
503
504 let payload = access_token
506 .split('.')
507 .nth(1)
508 .and_then(|p| URL_SAFE_NO_PAD.decode(p).ok())
509 .and_then(|p| serde_json::from_slice::<serde_json::Value>(&p).ok())
510 .ok_or_else(|| AuthError::InvalidToken("Invalid access token payload".to_string()))?;
511 let jkt = payload
512 .get("cnf")
513 .and_then(|c| c.get("jkt"))
514 .and_then(|j| j.as_str())
515 .ok_or_else(|| {
516 AuthError::InvalidToken(
517 "Access token carries no DPoP key binding (cnf.jkt)".to_string(),
518 )
519 })?;
520
521 self.validate_dpop_proof_for_key(
522 dpop_proof,
523 http_method,
524 http_uri,
525 Some(access_token),
526 None,
527 Some(jkt),
528 )
529 .await?;
530 Ok(())
531 }
532
533 #[deprecated(
537 since = "0.6.0-rc202",
538 note = "it could not establish that the access token is genuine; use `validate_dpop_bound_jwt`, or validate the token yourself and call `validate_dpop_proof_for_key` with its `jkt`"
539 )]
540 pub async fn validate_dpop_bound_access_token(
541 &self,
542 _access_token: &str,
543 _token_confirmation: &DpopConfirmation,
544 _dpop_proof: &str,
545 _http_method: &str,
546 _http_uri: &str,
547 ) -> Result<bool> {
548 Err(AuthError::InvalidToken(
549 "validate_dpop_bound_access_token cannot establish that the access token is genuine; use validate_dpop_bound_jwt, or validate the token and call validate_dpop_proof_for_key"
550 .to_string(),
551 ))
552 }
553
554 pub fn generate_nonce(&self) -> String {
556 use rand::RngCore;
557 let mut rng = rand::rng();
558 let mut nonce = [0u8; 16];
559 rng.fill_bytes(&mut nonce);
560 URL_SAFE_NO_PAD.encode(nonce)
561 }
562
563 pub async fn cleanup_expired_nonces(&self) {
565 self.sweep(Utc::now()).await;
566 }
567
568 async fn sweep(&self, at: DateTime<Utc>) {
570 let mut nonces = self.used_nonces.write().await;
571 nonces.retain(|_, until| *until > at);
573 }
574
575 fn parse_dpop_proof(&self, dpop_proof: &str) -> Result<(serde_json::Value, DpopProofClaims)> {
577 if dpop_proof.len() > 16 * 1024 {
578 return Err(AuthError::auth_method("dpop", "DPoP proof is too large"));
579 }
580 let parts: Vec<&str> = dpop_proof.split('.').collect();
582 if parts.len() != 3 {
583 return Err(AuthError::auth_method("dpop", "Invalid JWT format"));
584 }
585
586 let header_bytes = URL_SAFE_NO_PAD
588 .decode(parts[0])
589 .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header encoding"))?;
590 let header: serde_json::Value = serde_json::from_slice(&header_bytes)
591 .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header JSON"))?;
592
593 let claims_bytes = URL_SAFE_NO_PAD
595 .decode(parts[1])
596 .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT claims encoding"))?;
597 let claims: DpopProofClaims = serde_json::from_slice(&claims_bytes)
598 .map_err(|_| AuthError::auth_method("dpop", "Invalid DPoP proof claims"))?;
599
600 Ok((header, claims))
601 }
602
603 fn validate_dpop_header(
605 &self,
606 header: &serde_json::Value,
607 errors: &mut Vec<String>,
608 ) -> Result<()> {
609 if header.get("typ").and_then(|v| v.as_str()) != Some("dpop+jwt") {
611 errors.push("DPoP proof must have 'typ' header value 'dpop+jwt'".to_string());
612 }
613
614 if header.get("alg").and_then(|v| v.as_str()).is_none() {
615 errors.push("DPoP proof missing 'alg' header".to_string());
616 }
617
618 if header.get("jwk").is_none() {
619 errors.push("DPoP proof missing 'jwk' header".to_string());
620 }
621
622 if let Some(alg) = header.get("alg").and_then(|v| v.as_str())
624 && alg == "none"
625 {
626 errors.push("DPoP proof algorithm cannot be 'none'".to_string());
627 }
628
629 Ok(())
630 }
631
632 async fn validate_dpop_claims(
634 &self,
635 claims: &DpopProofClaims,
636 http_method: &str,
637 http_uri: &str,
638 access_token: Option<&str>,
639 expected_nonce: Option<&str>,
640 errors: &mut Vec<String>,
641 ) -> Result<()> {
642 let now = Utc::now();
643 let iat =
644 DateTime::from_timestamp(claims.iat, 0).unwrap_or_else(|| now - Duration::hours(1));
645
646 let min_time = now - self.proof_expiration - self.clock_skew;
648 let max_time = now + self.clock_skew;
649
650 if iat < min_time {
651 errors.push("DPoP proof is too old".to_string());
652 }
653
654 if iat > max_time {
655 errors.push("DPoP proof timestamp is in the future".to_string());
656 }
657
658 if claims.htm != http_method {
660 errors.push(format!(
661 "DPoP proof HTTP method '{}' does not match request method '{}'",
662 claims.htm, http_method
663 ));
664 }
665
666 let expected_uri = self.normalize_uri(http_uri)?;
668 let proof_uri = self.normalize_uri(&claims.htu)?;
669
670 if proof_uri != expected_uri {
671 errors.push(format!(
672 "DPoP proof HTTP URI '{}' does not match request URI '{}'",
673 claims.htu, http_uri
674 ));
675 }
676
677 if let Some(token) = access_token {
679 let expected_ath = self.calculate_access_token_hash(token)?;
680 match &claims.ath {
681 Some(ath) => {
682 use subtle::ConstantTimeEq as _;
683 if !bool::from(ath.as_bytes().ct_eq(expected_ath.as_bytes())) {
684 errors.push("DPoP proof access token hash does not match".to_string());
685 }
686 }
687 None => errors.push(
688 "DPoP proof is missing the 'ath' claim required with an access token"
689 .to_string(),
690 ),
691 }
692 }
693
694 if let Some(expected) = expected_nonce {
696 match &claims.nonce {
697 Some(nonce) if nonce == expected => {}
698 Some(_) => {
699 errors.push("DPoP proof nonce does not match expected value".to_string());
700 }
701 None => {
702 errors.push("DPoP proof missing required nonce".to_string());
703 }
704 }
705 }
706
707 Ok(())
708 }
709
710 fn verify_dpop_signature(
712 &self,
713 dpop_proof: &str,
714 public_key_jwk: &serde_json::Value,
715 errors: &mut Vec<String>,
716 ) -> Result<()> {
717 use ring::signature;
718
719 let parts: Vec<&str> = dpop_proof.split('.').collect();
721 if parts.len() != 3 {
722 return Err(AuthError::validation("Invalid JWT format for DPoP proof"));
723 }
724
725 let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).map_err(|_| {
726 AuthError::validation("Invalid JWT header encoding for signature verification")
727 })?;
728 let header: serde_json::Value = serde_json::from_slice(&header_bytes)
729 .map_err(|_| AuthError::validation("Invalid JWT header JSON"))?;
730
731 let alg_str = header
732 .get("alg")
733 .and_then(|v| v.as_str())
734 .ok_or_else(|| AuthError::validation("Missing algorithm in JWT header"))?;
735
736 let signing_input = format!("{}.{}", parts[0], parts[1]);
738 let signature_bytes = URL_SAFE_NO_PAD
739 .decode(parts[2])
740 .map_err(|_| AuthError::validation("Invalid JWT signature encoding"))?;
741
742 let key_type = public_key_jwk
744 .get("kty")
745 .and_then(|v| v.as_str())
746 .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
747
748 match key_type {
750 "RSA" => {
751 let n = public_key_jwk
753 .get("n")
754 .and_then(|v| v.as_str())
755 .ok_or_else(|| AuthError::validation("Missing 'n' parameter in RSA JWK"))?;
756 let e = public_key_jwk
757 .get("e")
758 .and_then(|v| v.as_str())
759 .ok_or_else(|| AuthError::validation("Missing 'e' parameter in RSA JWK"))?;
760
761 let n_bytes = URL_SAFE_NO_PAD.decode(n.as_bytes()).map_err(|e| {
763 AuthError::validation(format!("Invalid base64url 'n' parameter: {}", e))
764 })?;
765 let e_bytes = URL_SAFE_NO_PAD.decode(e.as_bytes()).map_err(|e| {
766 AuthError::validation(format!("Invalid base64url 'e' parameter: {}", e))
767 })?;
768
769 if n_bytes.is_empty() || e_bytes.is_empty() {
770 return Err(AuthError::validation("Empty RSA JWK parameter"));
771 }
772
773 let mut content = der_unsigned_integer(&n_bytes);
776 content.extend(der_unsigned_integer(&e_bytes));
777 let mut public_key_der = vec![0x30];
778 der_push_length(&mut public_key_der, content.len());
779 public_key_der.extend_from_slice(&content);
780
781 let verification_algorithm = match alg_str {
783 "RS256" => &signature::RSA_PKCS1_2048_8192_SHA256,
784 "RS384" => &signature::RSA_PKCS1_2048_8192_SHA384,
785 "RS512" => &signature::RSA_PKCS1_2048_8192_SHA512,
786 "PS256" => &signature::RSA_PSS_2048_8192_SHA256,
787 "PS384" => &signature::RSA_PSS_2048_8192_SHA384,
788 "PS512" => &signature::RSA_PSS_2048_8192_SHA512,
789 _ => {
790 return Err(AuthError::validation(format!(
791 "Unsupported RSA algorithm: {}",
792 alg_str
793 )));
794 }
795 };
796
797 let public_key =
799 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_der);
800
801 match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
803 Ok(()) => {
804 let _ = std::hint::black_box(alg_str);
806 tracing::debug!(
807 "DPoP proof RSA signature successfully verified using Ring with algorithm {}",
808 alg_str
809 );
810 }
811 Err(_) => {
812 let _ = std::hint::black_box(alg_str);
814 let error_msg = format!(
815 "DPoP proof RSA signature verification failed with algorithm {}",
816 alg_str
817 );
818 errors.push(error_msg.clone());
819 tracing::warn!("{}", error_msg);
820 return Err(AuthError::validation(
821 "DPoP RSA signature verification failed",
822 ));
823 }
824 }
825 }
826 "EC" => {
827 let curve = public_key_jwk
829 .get("crv")
830 .and_then(|v| v.as_str())
831 .ok_or_else(|| AuthError::validation("Missing 'crv' parameter in EC JWK"))?;
832 let x = public_key_jwk
833 .get("x")
834 .and_then(|v| v.as_str())
835 .ok_or_else(|| AuthError::validation("Missing 'x' parameter in EC JWK"))?;
836 let y = public_key_jwk
837 .get("y")
838 .and_then(|v| v.as_str())
839 .ok_or_else(|| AuthError::validation("Missing 'y' parameter in EC JWK"))?;
840
841 let x_bytes = URL_SAFE_NO_PAD.decode(x.as_bytes()).map_err(|e| {
843 AuthError::validation(format!("Invalid base64url 'x' parameter: {}", e))
844 })?;
845 let y_bytes = URL_SAFE_NO_PAD.decode(y.as_bytes()).map_err(|e| {
846 AuthError::validation(format!("Invalid base64url 'y' parameter: {}", e))
847 })?;
848
849 let (verification_algorithm, expected_coord_len) = match (curve, alg_str) {
851 ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_FIXED, 32),
852 ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_FIXED, 48),
853 _ => {
854 return Err(AuthError::validation(format!(
855 "Unsupported EC curve/algorithm combination: {}/{}",
856 curve, alg_str
857 )));
858 }
859 };
860
861 if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
863 return Err(AuthError::validation(format!(
864 "Invalid coordinate length for curve {}: expected {}, got x={}, y={}",
865 curve,
866 expected_coord_len,
867 x_bytes.len(),
868 y_bytes.len()
869 )));
870 }
871
872 if signature_bytes.len() != expected_coord_len * 2 {
875 return Err(AuthError::validation(format!(
876 "DPoP {alg_str} signature must be the {}-byte r||s form (RFC 7518 section 3.4), got {} bytes",
877 expected_coord_len * 2,
878 signature_bytes.len()
879 )));
880 }
881
882 let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
884 public_key_bytes.push(0x04); public_key_bytes.extend_from_slice(&x_bytes);
886 public_key_bytes.extend_from_slice(&y_bytes);
887
888 let public_key =
890 signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
891
892 match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
894 Ok(()) => {
895 let _ = std::hint::black_box((curve, alg_str));
897 tracing::debug!(
898 "DPoP proof ECDSA signature successfully verified using Ring with curve {} and algorithm {}",
899 curve,
900 alg_str
901 );
902 }
903 Err(_) => {
904 let _ = std::hint::black_box((curve, alg_str));
906 let error_msg = format!(
907 "DPoP proof ECDSA signature verification failed with curve {} and algorithm {}",
908 curve, alg_str
909 );
910 errors.push(error_msg.clone());
911 tracing::warn!("{}", error_msg);
912 return Err(AuthError::validation(
913 "DPoP ECDSA signature verification failed",
914 ));
915 }
916 }
917 }
918 _ => {
919 return Err(AuthError::validation(format!(
920 "Unsupported key type for cryptographic verification: {}",
921 key_type
922 )));
923 }
924 }
925
926 let claims_bytes = URL_SAFE_NO_PAD
928 .decode(parts[1])
929 .map_err(|_| AuthError::validation("Invalid JWT claims encoding"))?;
930 let claims: serde_json::Value = serde_json::from_slice(&claims_bytes)
931 .map_err(|_| AuthError::validation("Invalid JWT claims JSON"))?;
932
933 if claims.get("htm").is_none() {
935 errors.push("DPoP proof missing 'htm' claim".to_string());
936 }
937 if claims.get("htu").is_none() {
938 errors.push("DPoP proof missing 'htu' claim".to_string());
939 }
940 if claims.get("jti").is_none() {
941 errors.push("DPoP proof missing 'jti' claim".to_string());
942 }
943 if claims.get("iat").is_none() {
944 errors.push("DPoP proof missing 'iat' claim".to_string());
945 }
946
947 Ok(())
948 }
949
950 fn calculate_jwk_thumbprint(&self, jwk: &serde_json::Value) -> Result<String> {
952 use sha2::{Digest, Sha256};
953
954 let text = |name: &str| -> Result<String> {
956 let value = jwk.get(name).and_then(|v| v.as_str()).ok_or_else(|| {
957 AuthError::auth_method("dpop", format!("JWK is missing the '{name}' member"))
958 })?;
959 Ok(serde_json::Value::String(value.to_string()).to_string())
960 };
961 let kty = jwk
962 .get("kty")
963 .and_then(|v| v.as_str())
964 .ok_or_else(|| AuthError::auth_method("dpop", "JWK is missing the 'kty' member"))?;
965 if kty == "RSA" {
966 for name in ["n", "e"] {
967 let raw = jwk
968 .get(name)
969 .and_then(|v| v.as_str())
970 .and_then(|s| URL_SAFE_NO_PAD.decode(s).ok());
971 if raw
973 .as_deref()
974 .is_none_or(|r| r.first().is_none_or(|&b| b == 0))
975 {
976 return Err(AuthError::auth_method(
977 "dpop",
978 format!("RSA JWK member '{name}' is not a minimal base64url integer"),
979 ));
980 }
981 }
982 }
983 let canonical_json = match kty {
984 "EC" => format!(
985 r#"{{"crv":{},"kty":"EC","x":{},"y":{}}}"#,
986 text("crv")?,
987 text("x")?,
988 text("y")?
989 ),
990 "RSA" => format!(r#"{{"e":{},"kty":"RSA","n":{}}}"#, text("e")?, text("n")?),
991 "OKP" => format!(
992 r#"{{"crv":{},"kty":"OKP","x":{}}}"#,
993 text("crv")?,
994 text("x")?
995 ),
996 other => {
997 return Err(AuthError::auth_method(
998 "dpop",
999 format!("Unsupported JWK key type for a thumbprint: {other}"),
1000 ));
1001 }
1002 };
1003
1004 let mut hasher = Sha256::new();
1006 hasher.update(canonical_json.as_bytes());
1007 let hash = hasher.finalize();
1008
1009 Ok(URL_SAFE_NO_PAD.encode(hash))
1010 }
1011
1012 fn calculate_access_token_hash(&self, access_token: &str) -> Result<String> {
1014 use sha2::{Digest, Sha256};
1015
1016 let mut hasher = Sha256::new();
1017 hasher.update(access_token.as_bytes());
1018 let hash = hasher.finalize();
1019
1020 Ok(URL_SAFE_NO_PAD.encode(hash))
1021 }
1022
1023 fn normalize_uri(&self, uri: &str) -> Result<String> {
1025 let url = url::Url::parse(uri)
1026 .map_err(|_| AuthError::auth_method("dpop", "Invalid URI format"))?;
1027
1028 let normalized = match url.port() {
1030 Some(port) => format!(
1031 "{}://{}:{}{}",
1032 url.scheme(),
1033 url.host_str().unwrap_or(""),
1034 port,
1035 url.path()
1036 ),
1037 None => format!(
1038 "{}://{}{}",
1039 url.scheme(),
1040 url.host_str().unwrap_or(""),
1041 url.path()
1042 ),
1043 };
1044
1045 Ok(normalized)
1046 }
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051 use super::*;
1052 use crate::security::secure_jwt::SecureJwtConfig;
1053
1054 fn create_test_dpop_manager() -> DpopManager {
1055 let jwt_config = SecureJwtConfig::default();
1056 let jwt_validator = SecureJwtValidator::new(jwt_config);
1057 DpopManager::new(jwt_validator)
1058 }
1059 fn create_test_jwk() -> serde_json::Value {
1060 serde_json::json!({
1061 "kty": "EC",
1062 "crv": "P-256",
1063 "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
1064 "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
1065 "use": "sig",
1066 "alg": "ES256"
1067 })
1068 }
1069
1070 #[tokio::test]
1071 async fn test_dpop_manager_creation() {
1072 let manager = create_test_dpop_manager();
1073 let nonce = manager.generate_nonce();
1074 assert!(!nonce.is_empty());
1075 }
1076
1077 #[test]
1078 fn test_jwk_thumbprint_calculation() {
1079 let manager = create_test_dpop_manager();
1080 let jwk = create_test_jwk();
1081
1082 let thumbprint = manager.calculate_jwk_thumbprint(&jwk).unwrap();
1083 assert!(!thumbprint.is_empty());
1084
1085 let thumbprint2 = manager.calculate_jwk_thumbprint(&jwk).unwrap();
1087 assert_eq!(thumbprint, thumbprint2);
1088 }
1089
1090 #[test]
1091 fn test_dpop_confirmation() {
1092 let manager = create_test_dpop_manager();
1093 let jwk = create_test_jwk();
1094
1095 let confirmation = manager.create_dpop_confirmation(&jwk).unwrap();
1096 assert!(!confirmation.jkt.is_empty());
1097
1098 let is_valid = manager
1100 .validate_dpop_bound_token(&confirmation, &jwk)
1101 .unwrap();
1102 assert!(is_valid);
1103
1104 let different_jwk = serde_json::json!({
1106 "kty": "EC",
1107 "crv": "P-256",
1108 "x": "different_x_value_here_for_testing_purposes",
1109 "y": "different_y_value_here_for_testing_purposes",
1110 "use": "sig",
1111 "alg": "ES256"
1112 });
1113
1114 let mismatch = manager.validate_dpop_bound_token(&confirmation, &different_jwk);
1115 assert!(mismatch.is_err(), "another key is an error, not Ok(false)");
1116 }
1117
1118 #[test]
1119 fn test_uri_normalization() {
1120 let manager = create_test_dpop_manager();
1121
1122 let uri = "https://example.com/api/resource?param=value#fragment";
1123 let normalized = manager.normalize_uri(uri).unwrap();
1124 assert_eq!(normalized, "https://example.com/api/resource");
1125
1126 let uri2 = "https://example.com/api/resource";
1127 let normalized2 = manager.normalize_uri(uri2).unwrap();
1128 assert_eq!(normalized2, "https://example.com/api/resource");
1129 }
1130
1131 #[test]
1132 fn test_access_token_hash() {
1133 let manager = create_test_dpop_manager();
1134
1135 let token = "test_access_token_value";
1136 let hash = manager.calculate_access_token_hash(token).unwrap();
1137 assert!(!hash.is_empty());
1138
1139 let hash2 = manager.calculate_access_token_hash(token).unwrap();
1141 assert_eq!(hash, hash2);
1142 }
1143
1144 #[tokio::test]
1145 async fn test_nonce_cleanup() {
1146 let manager = create_test_dpop_manager();
1147
1148 {
1150 let mut nonces = manager.used_nonces.write().await;
1151 nonces.insert("old_nonce".to_string(), Utc::now() - Duration::hours(1));
1152 nonces.insert(
1153 "recent_nonce".to_string(),
1154 Utc::now() + Duration::seconds(60),
1155 );
1156 }
1157
1158 manager.cleanup_expired_nonces().await;
1160
1161 let nonces = manager.used_nonces.read().await;
1162 assert!(!nonces.contains_key("old_nonce"));
1163 assert!(nonces.contains_key("recent_nonce"));
1164 }
1165}
1166
1167#[cfg(test)]
1168mod dpop_regression {
1169 use super::*;
1173 use crate::security::secure_jwt::{SecureJwtConfig, SecureJwtValidator};
1174 use jsonwebtoken::{Algorithm, EncodingKey};
1175 use serde_json::json;
1176 use sha2::{Digest, Sha256};
1177
1178 const URI: &str = "https://rs.example.com/resource";
1179 const TOKEN: &str = "access-token-1";
1180
1181 fn ec_key() -> (EncodingKey, serde_json::Value) {
1182 let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1183 let raw = key.public_key_raw();
1184 let point = &raw[raw.len() - 65..];
1185 let jwk = json!({
1186 "kty": "EC", "crv": "P-256",
1187 "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1188 "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1189 });
1190 (
1191 EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
1192 jwk,
1193 )
1194 }
1195
1196 fn ath_of(token: &str) -> String {
1197 URL_SAFE_NO_PAD.encode(Sha256::digest(token.as_bytes()))
1198 }
1199
1200 struct Proof<'a> {
1201 key: &'a (EncodingKey, serde_json::Value),
1202 htm: &'a str,
1203 htu: &'a str,
1204 iat: i64,
1205 jti: &'a str,
1206 ath: Option<String>,
1207 der: bool,
1208 jwk_extra: Option<(&'a str, &'a str)>,
1209 }
1210
1211 impl Proof<'_> {
1212 fn build(&self) -> String {
1213 let mut jwk = self.key.1.clone();
1214 if let Some((k, v)) = self.jwk_extra {
1215 jwk[k] = json!(v);
1216 }
1217 let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
1218 let mut claims =
1219 json!({"jti": self.jti, "htm": self.htm, "htu": self.htu, "iat": self.iat});
1220 if let Some(a) = &self.ath {
1221 claims["ath"] = json!(a);
1222 }
1223 let si = format!(
1224 "{}.{}",
1225 URL_SAFE_NO_PAD.encode(header.to_string()),
1226 URL_SAFE_NO_PAD.encode(claims.to_string())
1227 );
1228 let sig =
1230 jsonwebtoken::crypto::sign(si.as_bytes(), &self.key.0, Algorithm::ES256).unwrap();
1231 if !self.der {
1232 return format!("{si}.{sig}");
1233 }
1234 let raw = URL_SAFE_NO_PAD.decode(sig).unwrap();
1235 let int = |v: &[u8]| {
1236 let mut v: Vec<u8> = v.iter().copied().skip_while(|&x| x == 0).collect();
1237 if v.is_empty() || v[0] & 0x80 != 0 {
1238 v.insert(0, 0);
1239 }
1240 let mut o = vec![0x02, v.len() as u8];
1241 o.extend(v);
1242 o
1243 };
1244 let mut body = int(&raw[..32]);
1245 body.extend(int(&raw[32..]));
1246 let mut der = vec![0x30, body.len() as u8];
1247 der.extend(body);
1248 format!("{si}.{}", URL_SAFE_NO_PAD.encode(der))
1249 }
1250 }
1251
1252 struct Fixture {
1253 dpop: DpopManager,
1254 key: (EncodingKey, serde_json::Value),
1255 now: i64,
1256 }
1257
1258 impl Fixture {
1259 fn new() -> Self {
1260 Fixture {
1261 dpop: DpopManager::new(SecureJwtValidator::new(SecureJwtConfig::default())),
1262 key: ec_key(),
1263 now: Utc::now().timestamp(),
1264 }
1265 }
1266
1267 fn good<'a>(&'a self, jti: &'a str) -> Proof<'a> {
1268 Proof {
1269 key: &self.key,
1270 htm: "GET",
1271 htu: URI,
1272 iat: self.now,
1273 jti,
1274 ath: Some(ath_of(TOKEN)),
1275 der: false,
1276 jwk_extra: None,
1277 }
1278 }
1279
1280 async fn present(&self, proof: &str) -> Result<DpopValidationResult> {
1281 self.dpop
1282 .validate_dpop_proof(proof, "GET", URI, Some(TOKEN), None)
1283 .await
1284 }
1285 }
1286
1287 fn refused(r: Result<DpopValidationResult>, reason: &str, what: &str) {
1288 match r {
1289 Ok(v) => panic!(
1290 "{what}: ACCEPTED (is_valid={}, errors={:?})",
1291 v.is_valid, v.errors
1292 ),
1293 Err(e) => assert!(
1294 e.to_string().contains(reason),
1295 "{what}: refused with {e:?}, expected a reason containing {reason:?}"
1296 ),
1297 }
1298 }
1299
1300 #[tokio::test]
1301 async fn a_correct_proof_is_accepted() {
1302 let f = Fixture::new();
1303 let ok = f
1304 .present(&f.good("j-ok").build())
1305 .await
1306 .expect("a correct proof is accepted");
1307 assert!(ok.is_valid && ok.errors.is_empty());
1308 assert_eq!(
1309 ok.jwk_thumbprint.as_deref(),
1310 Some(
1311 f.dpop
1312 .create_dpop_confirmation(&f.key.1)
1313 .unwrap()
1314 .jkt
1315 .as_str()
1316 )
1317 );
1318 }
1319
1320 #[tokio::test]
1321 async fn a_proof_for_another_method_url_or_time_is_refused() {
1322 let f = Fixture::new();
1323 let p = Proof {
1324 htm: "DELETE",
1325 ..f.good("j-htm")
1326 }
1327 .build();
1328 refused(f.present(&p).await, "HTTP method", "wrong htm");
1329 let p = Proof {
1330 htu: "https://evil.example/x",
1331 ..f.good("j-htu")
1332 }
1333 .build();
1334 refused(f.present(&p).await, "HTTP URI", "wrong htu");
1335 let p = Proof {
1336 iat: f.now - 86_400,
1337 ..f.good("j-old")
1338 }
1339 .build();
1340 refused(f.present(&p).await, "too old", "one-day-old iat");
1341 let p = Proof {
1342 iat: f.now + 86_400,
1343 ..f.good("j-future")
1344 }
1345 .build();
1346 refused(f.present(&p).await, "in the future", "future iat");
1347 }
1348
1349 #[tokio::test]
1350 async fn a_proof_without_an_access_token_needs_no_ath() {
1351 let f = Fixture::new();
1353 let p = Proof {
1354 ath: None,
1355 ..f.good("j-endpoint")
1356 }
1357 .build();
1358 f.dpop
1359 .validate_dpop_proof(&p, "GET", URI, None, None)
1360 .await
1361 .expect("no access token, so no ath is required");
1362 }
1363
1364 #[tokio::test]
1365 async fn a_proof_used_twice_is_refused_the_second_time() {
1366 let f = Fixture::new();
1367 let once = f.good("j-replay").build();
1368 f.present(&once).await.expect("first use");
1369 refused(f.present(&once).await, "already used", "replayed proof");
1370 }
1371
1372 #[tokio::test]
1373 async fn a_proof_must_name_the_access_token() {
1374 let f = Fixture::new();
1375 let p = Proof {
1376 ath: None,
1377 ..f.good("j-no-ath")
1378 }
1379 .build();
1380 refused(f.present(&p).await, "'ath'", "no ath");
1381 let p = Proof {
1382 ath: Some(ath_of("another-token")),
1383 ..f.good("j-bad-ath")
1384 }
1385 .build();
1386 refused(f.present(&p).await, "access token hash", "wrong ath");
1387 }
1388
1389 #[tokio::test]
1390 async fn a_der_signature_or_a_private_key_in_the_header_is_refused() {
1391 let f = Fixture::new();
1392 let p = Proof {
1393 der: true,
1394 ..f.good("j-der")
1395 }
1396 .build();
1397 refused(f.present(&p).await, "r||s", "DER-encoded ES256 signature");
1398 let p = Proof {
1399 jwk_extra: Some(("d", "AAAA")),
1400 ..f.good("j-priv")
1401 }
1402 .build();
1403 refused(f.present(&p).await, "private key", "private key in jwk");
1404 }
1405
1406 #[tokio::test]
1407 async fn a_proof_refused_for_another_reason_does_not_use_up_its_jti() {
1408 let f = Fixture::new();
1409 let p = f.good("j-keep").build();
1410 refused(
1412 f.dpop
1413 .validate_dpop_proof(&p, "POST", URI, Some(TOKEN), None)
1414 .await,
1415 "HTTP method",
1416 "wrong method",
1417 );
1418 f.present(&p)
1420 .await
1421 .expect("a proof refused earlier for its method is not spent");
1422 }
1423
1424 #[tokio::test]
1425 async fn a_replay_record_outlives_the_proof_it_guards() {
1426 let f = Fixture::new();
1427 let p = Proof {
1430 iat: f.now + 25,
1431 ..f.good("j-late")
1432 }
1433 .build();
1434 f.present(&p).await.expect("within the clock skew");
1435 let acceptable_until = chrono::TimeZone::timestamp_opt(&Utc, f.now + 25 + 90, 0)
1436 .single()
1437 .unwrap();
1438 f.dpop.sweep(acceptable_until - Duration::seconds(1)).await;
1439 assert_eq!(
1440 f.dpop.used_nonces.read().await.len(),
1441 1,
1442 "record dropped while the proof could still be replayed"
1443 );
1444 f.dpop.sweep(acceptable_until + Duration::seconds(1)).await;
1445 assert!(
1446 f.dpop.used_nonces.read().await.is_empty(),
1447 "record kept after the proof can no longer be accepted"
1448 );
1449 }
1450
1451 #[tokio::test]
1452 async fn the_replay_cache_is_swept_and_bounded() {
1453 let mut f = Fixture::new();
1454 f.dpop.max_replay_entries = 4;
1455 let stale = Utc::now() - Duration::seconds(1);
1456 let live = Utc::now() + Duration::seconds(600);
1457 {
1458 let mut used = f.dpop.used_nonces.write().await;
1459 used.insert("stale-1".into(), stale);
1460 used.insert("stale-2".into(), stale);
1461 used.insert("live-1".into(), live);
1462 used.insert("live-2".into(), live);
1463 }
1464 f.present(&f.good("j-fits").build())
1466 .await
1467 .expect("a swept cache has room");
1468 {
1469 let used = f.dpop.used_nonces.read().await;
1470 assert!(
1471 !used.contains_key("stale-1") && !used.contains_key("stale-2"),
1472 "stale records survive a full cache"
1473 );
1474 assert_eq!(used.len(), 3);
1475 }
1476 f.dpop
1478 .used_nonces
1479 .write()
1480 .await
1481 .insert("live-3".into(), live);
1482 refused(
1483 f.present(&f.good("j-overflow").build()).await,
1484 "replay cache is full",
1485 "a full cache",
1486 );
1487 }
1488
1489 #[tokio::test]
1490 async fn one_key_cannot_spend_anothers_jti() {
1491 let f = Fixture::new();
1492 let other = ec_key();
1493 let mine = f.good("j-shared").build();
1494 let theirs = Proof {
1495 key: &other,
1496 ..f.good("j-shared")
1497 }
1498 .build();
1499 f.present(&mine).await.expect("first key");
1500 f.present(&theirs)
1501 .await
1502 .expect("a different key may use the same jti");
1503 refused(
1504 f.present(&mine).await,
1505 "already used",
1506 "the first key again",
1507 );
1508 }
1509
1510 #[tokio::test]
1511 async fn a_method_in_another_case_is_refused() {
1512 let f = Fixture::new();
1513 let p = f.good("j-case").build();
1514 refused(
1515 f.dpop
1516 .validate_dpop_proof(&p, "get", URI, Some(TOKEN), None)
1517 .await,
1518 "HTTP method",
1519 "lower-case method",
1520 );
1521 }
1522
1523 #[test]
1524 fn a_key_that_is_not_the_bound_key_is_an_error() {
1525 let f = Fixture::new();
1526 let other = ec_key();
1527 let bound = f.dpop.create_dpop_confirmation(&f.key.1).unwrap();
1528 assert!(f.dpop.validate_dpop_bound_token(&bound, &f.key.1).unwrap());
1529 assert!(
1530 f.dpop.validate_dpop_bound_token(&bound, &other.1).is_err(),
1531 "another key must be an error, not Ok(false)"
1532 );
1533 }
1534
1535 #[test]
1536 fn thumbprints_match_rfc_7638_and_an_independent_hash() {
1537 let f = Fixture::new();
1538 let rsa = json!({
1540 "kty": "RSA", "alg": "RS256", "kid": "2011-04-29", "e": "AQAB",
1541 "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"
1542 });
1543 assert_eq!(
1544 f.dpop.calculate_jwk_thumbprint(&rsa).unwrap(),
1545 "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs"
1546 );
1547 let ec = json!({
1549 "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256",
1550 "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
1551 "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"
1552 });
1553 assert_eq!(
1554 f.dpop.calculate_jwk_thumbprint(&ec).unwrap(),
1555 "cn-I_WNMClehiVp51i_0VpOENW1upEerA8sEam5hn-s"
1556 );
1557 assert!(
1559 f.dpop
1560 .calculate_jwk_thumbprint(&json!({"kty": "EC", "crv": "P-256", "x": "AA"}))
1561 .is_err()
1562 );
1563 }
1564
1565 #[tokio::test]
1566 async fn an_iat_at_the_end_of_time_is_refused_not_a_panic() {
1567 let f = Fixture::new();
1568 for iat in [8_210_298_412_799_i64, 8_210_298_412_740] {
1570 let p = Proof {
1571 iat,
1572 ..f.good("j-forever")
1573 }
1574 .build();
1575 refused(f.present(&p).await, "rejected", "iat at the end of time");
1578 }
1579 }
1580
1581 #[tokio::test]
1582 async fn a_jti_that_is_empty_or_too_long_is_refused() {
1583 let f = Fixture::new();
1584 let long = "a".repeat(257);
1585 for (jti, what) in [("", "empty jti"), (long.as_str(), "257-byte jti")] {
1586 let p = f.good(jti).build();
1587 refused(f.present(&p).await, "jti", what);
1588 }
1589 let ok = "a".repeat(256);
1590 f.present(&f.good(&ok).build())
1591 .await
1592 .expect("256 bytes is allowed");
1593 }
1594
1595 #[tokio::test]
1596 async fn replay_records_have_a_fixed_size() {
1597 let f = Fixture::new();
1598 let jti = "j".repeat(200);
1599 f.present(&f.good(&jti).build()).await.expect("a long jti");
1600 f.present(&f.good("short").build())
1601 .await
1602 .expect("a short jti");
1603 let used = f.dpop.used_nonces.read().await;
1604 assert_eq!(used.len(), 2);
1605 assert!(
1606 used.keys().all(|k| k.len() == 43),
1607 "record keys are not a fixed-size hash: {:?}",
1608 used.keys().map(String::len).collect::<Vec<_>>()
1609 );
1610 }
1611
1612 #[tokio::test]
1613 async fn a_full_cache_is_swept_at_most_once_per_interval() {
1614 let mut f = Fixture::new();
1615 f.dpop.max_replay_entries = 2;
1616 f.dpop.sweep_interval = Duration::hours(1);
1617 let stale = Utc::now() - Duration::seconds(1);
1618 {
1619 let mut used = f.dpop.used_nonces.write().await;
1620 used.insert("stale-1".into(), stale);
1621 used.insert("stale-2".into(), stale);
1622 }
1623 f.present(&f.good("j-first").build())
1624 .await
1625 .expect("the first full cache is swept");
1626 f.dpop
1627 .used_nonces
1628 .write()
1629 .await
1630 .insert("stale-3".into(), stale);
1631 refused(
1633 f.present(&f.good("j-second").build()).await,
1634 "replay cache is full",
1635 "a cache swept a moment ago",
1636 );
1637 }
1638
1639 #[test]
1640 fn an_rsa_jwk_with_a_leading_zero_octet_has_no_thumbprint() {
1641 let f = Fixture::new();
1642 for jwk in [
1644 json!({"kty": "RSA", "n": "AQAB", "e": "AAEAAQ"}),
1645 json!({"kty": "RSA", "n": "AP8", "e": "AQAB"}),
1646 ] {
1647 assert!(f.dpop.calculate_jwk_thumbprint(&jwk).is_err(), "{jwk}");
1648 }
1649 assert!(
1650 f.dpop
1651 .calculate_jwk_thumbprint(&json!({"kty": "RSA", "n": "_w", "e": "AQAB"}))
1652 .is_ok()
1653 );
1654 }
1655
1656 #[tokio::test]
1657 async fn a_full_cache_of_expired_records_does_not_refuse_a_proof() {
1658 let mut f = Fixture::new();
1659 f.dpop.max_replay_entries = 2;
1660 f.dpop.sweep_interval = Duration::hours(1);
1661 f.present(&f.good("j-warm").build()).await.expect("warm-up");
1663 f.dpop
1665 .insert_record_for_test("expired-1", Utc::now() - Duration::seconds(5))
1666 .await;
1667 f.present(&f.good("j-after").build())
1668 .await
1669 .expect("room taken by an expired record must not refuse a proof");
1670 assert!(
1671 !f.dpop.used_nonces.read().await.contains_key("expired-1"),
1672 "the expired record was not swept"
1673 );
1674 }
1675
1676 fn rsa_parts(key: &rcgen::KeyPair) -> (String, String) {
1679 fn int(b: &[u8]) -> (&[u8], &[u8]) {
1680 assert_eq!(b[0], 0x02);
1681 let (len, off) = if b[1] & 0x80 == 0 {
1682 (b[1] as usize, 2)
1683 } else {
1684 let n = (b[1] & 0x7f) as usize;
1685 let len = b[2..2 + n]
1686 .iter()
1687 .fold(0usize, |a, &x| (a << 8) | x as usize);
1688 (len, 2 + n)
1689 };
1690 let v = &b[off..off + len];
1691 (v.strip_prefix(&[0]).unwrap_or(v), &b[off + len..])
1692 }
1693 let raw = key.public_key_raw();
1694 let body = if raw[1] & 0x80 == 0 {
1695 &raw[2..]
1696 } else {
1697 &raw[2 + (raw[1] & 0x7f) as usize..]
1698 };
1699 let (n, rest) = int(body);
1700 let (e, _) = int(rest);
1701 (URL_SAFE_NO_PAD.encode(n), URL_SAFE_NO_PAD.encode(e))
1702 }
1703
1704 #[tokio::test]
1705 async fn rs256_and_ps256_proofs_from_a_2048_bit_key_are_accepted() {
1706 let f = Fixture::new();
1707 let key =
1708 rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
1709 .unwrap();
1710 let (n, e) = rsa_parts(&key);
1711 assert_eq!(URL_SAFE_NO_PAD.decode(&n).unwrap().len(), 256);
1712 let enc = EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap();
1713 for (alg, name) in [(Algorithm::RS256, "RS256"), (Algorithm::PS256, "PS256")] {
1714 let header = json!({
1715 "typ": "dpop+jwt", "alg": name,
1716 "jwk": {"kty": "RSA", "n": n, "e": e},
1717 });
1718 let claims = |htm: &str| {
1719 json!({
1720 "jti": format!("j-{name}-{htm}"), "htm": htm, "htu": URI,
1721 "iat": f.now, "ath": ath_of(TOKEN),
1722 })
1723 };
1724 let b64 = |v: &serde_json::Value| URL_SAFE_NO_PAD.encode(v.to_string());
1725 let si = format!("{}.{}", b64(&header), b64(&claims("GET")));
1726 let sig = jsonwebtoken::crypto::sign(si.as_bytes(), &enc, alg).unwrap();
1727 f.present(&format!("{si}.{sig}"))
1728 .await
1729 .unwrap_or_else(|err| panic!("{name}: a correct proof was refused: {err:?}"));
1730
1731 let forged = format!("{}.{}.{sig}", b64(&header), b64(&claims("POST")));
1733 let r = f
1734 .dpop
1735 .validate_dpop_proof(&forged, "POST", URI, Some(TOKEN), None)
1736 .await;
1737 refused(
1738 r,
1739 "signature",
1740 &format!("{name}: a signature over other claims"),
1741 );
1742 }
1743 }
1744
1745 #[tokio::test]
1746 #[allow(deprecated)]
1747 async fn the_deprecated_function_always_refuses_even_a_forged_jwt() {
1748 let f = Fixture::new();
1749 let confirmation = f.dpop.create_dpop_confirmation(&f.key.1).unwrap();
1750 let header = URL_SAFE_NO_PAD.encode(r#"{"alg":"HS256","typ":"JWT"}"#);
1752 let claims = URL_SAFE_NO_PAD
1753 .encode(json!({"sub": "admin", "cnf": {"jkt": confirmation.jkt}}).to_string());
1754 let forged = format!(
1755 "{header}.{claims}.{}",
1756 URL_SAFE_NO_PAD.encode(b"not a signature")
1757 );
1758 let p = Proof {
1759 ath: Some(ath_of(&forged)),
1760 ..f.good("j-forged")
1761 }
1762 .build();
1763 let r = f
1764 .dpop
1765 .validate_dpop_bound_access_token(&forged, &confirmation, &p, "GET", URI)
1766 .await;
1767 assert!(
1768 r.is_err(),
1769 "a forged JWT was reported as a valid bound token: {r:?}"
1770 );
1771 }
1772
1773 const AUD: &str = "https://api.example.com";
1774 const SECRET: &[u8] = b"0123456789abcdef0123456789abcdef";
1775
1776 fn jwt_with(secret: &[u8], jkt: &str, edit: impl FnOnce(&mut serde_json::Value)) -> String {
1778 let now = Utc::now().timestamp();
1779 let mut claims = json!({
1780 "iss": "auth-framework", "sub": "user-1", "aud": AUD, "exp": now + 300,
1781 "nbf": now - 1, "iat": now, "jti": uuid::Uuid::new_v4().to_string(),
1782 "scope": "read", "typ": "access", "cnf": {"jkt": jkt},
1783 });
1784 edit(&mut claims);
1785 jsonwebtoken::encode(
1786 &jsonwebtoken::Header::new(Algorithm::HS256),
1787 &claims,
1788 &EncodingKey::from_secret(secret),
1789 )
1790 .unwrap()
1791 }
1792
1793 fn jwt_manager() -> DpopManager {
1794 DpopManager::new(SecureJwtValidator::new(SecureJwtConfig::default()))
1795 }
1796
1797 #[tokio::test]
1798 async fn a_genuine_bound_jwt_is_accepted_once() {
1799 let key = jsonwebtoken::DecodingKey::from_secret(SECRET);
1800 let f = Fixture::new();
1801 let dpop = jwt_manager();
1802 let jkt = dpop.create_dpop_confirmation(&f.key.1).unwrap().jkt;
1803 let tok = jwt_with(SECRET, &jkt, |_| {});
1804 let p = Proof {
1805 ath: Some(ath_of(&tok)),
1806 ..f.good("j-genuine")
1807 }
1808 .build();
1809 dpop.validate_dpop_bound_jwt(&tok, &key, AUD, &p, "GET", URI)
1810 .await
1811 .expect("a genuine bound token with its key's proof");
1812 let again = dpop
1813 .validate_dpop_bound_jwt(&tok, &key, AUD, &p, "GET", URI)
1814 .await;
1815 assert!(again.unwrap_err().to_string().contains("already used"));
1816 assert_eq!(dpop.used_nonces.read().await.len(), 1);
1817 }
1818
1819 #[tokio::test]
1823 async fn a_bound_jwt_that_is_not_a_valid_access_token_for_this_request_is_refused() {
1824 let key = jsonwebtoken::DecodingKey::from_secret(SECRET);
1825 let f = Fixture::new();
1826 let dpop = jwt_manager();
1827 let jkt = dpop.create_dpop_confirmation(&f.key.1).unwrap().jkt;
1828 let other = ec_key();
1829 let now = Utc::now().timestamp();
1830
1831 let cases = vec![
1833 (
1834 "signed by someone else",
1835 jwt_with(b"another-secret-another-secret-1234", &jkt, |_| {}),
1836 &f.key,
1837 None,
1838 AUD,
1839 "Invalid DPoP-bound access token",
1840 ),
1841 (
1842 "expired",
1843 jwt_with(SECRET, &jkt, |c| {
1844 c["exp"] = json!(now - 3600);
1845 c["iat"] = json!(now - 3700);
1846 c["nbf"] = json!(now - 3700);
1847 }),
1848 &f.key,
1849 None,
1850 AUD,
1851 "Invalid DPoP-bound access token",
1852 ),
1853 (
1854 "a refresh token",
1855 jwt_with(SECRET, &jkt, |c| c["typ"] = json!("refresh")),
1856 &f.key,
1857 None,
1858 AUD,
1859 "Not an access token",
1860 ),
1861 (
1862 "an empty typ",
1863 jwt_with(SECRET, &jkt, |c| c["typ"] = json!("")),
1864 &f.key,
1865 None,
1866 AUD,
1867 "Not an access token",
1868 ),
1869 (
1870 "issued for another audience",
1871 jwt_with(SECRET, &jkt, |c| {
1872 c["aud"] = json!("https://other.example.com")
1873 }),
1874 &f.key,
1875 None,
1876 AUD,
1877 "another audience",
1878 ),
1879 (
1880 "no cnf.jkt",
1881 jwt_with(SECRET, &jkt, |c| {
1882 c.as_object_mut().unwrap().remove("cnf");
1883 }),
1884 &f.key,
1885 None,
1886 AUD,
1887 "no DPoP key binding",
1888 ),
1889 (
1890 "a proof from another key",
1891 jwt_with(SECRET, &jkt, |_| {}),
1892 &other,
1893 None,
1894 AUD,
1895 "key binding",
1896 ),
1897 (
1898 "a proof for another token",
1899 jwt_with(SECRET, &jkt, |_| {}),
1900 &f.key,
1901 Some(ath_of("another-token")),
1902 AUD,
1903 "access token hash",
1904 ),
1905 ];
1906 for (i, (what, tok, signer, ath, aud, reason)) in cases.into_iter().enumerate() {
1907 let jti = format!("j-case-{i}");
1908 let p = Proof {
1909 key: signer,
1910 ath: Some(ath.unwrap_or_else(|| ath_of(&tok))),
1911 ..f.good(&jti)
1912 }
1913 .build();
1914 match dpop
1915 .validate_dpop_bound_jwt(&tok, &key, aud, &p, "GET", URI)
1916 .await
1917 {
1918 Ok(()) => panic!("{what}: ACCEPTED"),
1919 Err(e) => assert!(
1920 e.to_string().contains(reason),
1921 "{what}: refused with {e:?}, expected {reason:?}"
1922 ),
1923 }
1924 }
1925 assert_eq!(
1926 dpop.used_nonces.read().await.len(),
1927 0,
1928 "a refused token must not use a replay-cache slot"
1929 );
1930
1931 let tok = jwt_with(SECRET, &jkt, |_| {});
1933 let p = Proof {
1934 ath: Some(ath_of(&tok)),
1935 ..f.good("j-after")
1936 }
1937 .build();
1938 dpop.validate_dpop_bound_jwt(&tok, &key, AUD, &p, "GET", URI)
1939 .await
1940 .expect("a genuine token after the refusals");
1941 assert_eq!(dpop.used_nonces.read().await.len(), 1);
1942 }
1943
1944 #[tokio::test]
1945 async fn an_empty_audience_is_refused() {
1946 let key = jsonwebtoken::DecodingKey::from_secret(SECRET);
1947 let f = Fixture::new();
1948 let dpop = jwt_manager();
1949 let jkt = dpop.create_dpop_confirmation(&f.key.1).unwrap().jkt;
1950 let tok = jwt_with(SECRET, &jkt, |c| c["aud"] = json!(""));
1952 let p = Proof {
1953 ath: Some(ath_of(&tok)),
1954 ..f.good("j-empty-aud")
1955 }
1956 .build();
1957 let r = dpop
1958 .validate_dpop_bound_jwt(&tok, &key, "", &p, "GET", URI)
1959 .await;
1960 assert!(
1961 r.unwrap_err().to_string().contains("audience is required"),
1962 "an empty audience was not refused for that reason"
1963 );
1964 assert_eq!(dpop.used_nonces.read().await.len(), 0);
1965 }
1966}