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