Skip to main content

auth_framework/server/security/
dpop.rs

1//! OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP) - RFC 9449
2//!
3//! This module implements DPoP (Demonstrating Proof-of-Possession), which provides:
4//! 1. Application-layer proof-of-possession for OAuth 2.0 access tokens
5//! 2. Protection against token theft and replay attacks
6//! 3. JWT-based proof tokens bound to HTTP requests
7
8use 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 serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15/// DPoP proof token claims
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct DpopProofClaims {
18    /// JWT ID - unique identifier for this proof
19    pub jti: String,
20
21    /// HTTP method of the request
22    pub htm: String,
23
24    /// HTTP URI of the request (without query and fragment)
25    pub htu: String,
26
27    /// Issued at time
28    pub iat: i64,
29
30    /// Access token hash (only for access token requests)
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub ath: Option<String>,
33
34    /// Nonce (for authorization server to prevent replay)
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub nonce: Option<String>,
37}
38
39/// DPoP key binding configuration
40#[derive(Debug, Clone)]
41pub struct DpopKeyBinding {
42    /// Public key in JWK format
43    pub public_key_jwk: serde_json::Value,
44
45    /// Key algorithm (ES256, RS256, etc.)
46    pub algorithm: String,
47
48    /// Key ID (optional)
49    pub key_id: Option<String>,
50}
51
52/// DPoP-bound access token confirmation
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct DpopConfirmation {
55    /// JWK thumbprint of the public key
56    pub jkt: String,
57}
58
59/// DPoP validation result
60#[derive(Debug, Clone)]
61pub struct DpopValidationResult {
62    /// Whether the DPoP proof is valid
63    pub is_valid: bool,
64
65    /// Validation errors (if any)
66    pub errors: Vec<String>,
67
68    /// Extracted public key JWK
69    pub public_key_jwk: Option<serde_json::Value>,
70
71    /// JWK thumbprint
72    pub jwk_thumbprint: Option<String>,
73}
74
75/// A DPoP proof that passed every check but has not been recorded yet.
76///
77/// Recording a proof's `jti` uses a cache slot, so a caller that still has to authenticate
78/// something else (the access token, the request) holds the proof here and commits it with
79/// `commit_dpop_proof` only once that has succeeded.
80#[must_use = "a verified proof is not recorded until it is committed"]
81#[derive(Debug)]
82pub(crate) struct VerifiedDpopProof {
83    result: DpopValidationResult,
84    replay_id: String,
85    keep_until: DateTime<Utc>,
86}
87
88impl VerifiedDpopProof {
89    /// What the proof established: the key it was signed with and its thumbprint.
90    pub(crate) fn result(&self) -> &DpopValidationResult {
91        &self.result
92    }
93}
94
95/// Append a DER length: one byte below 128, otherwise `0x80 | n` and the `n` length bytes.
96fn der_push_length(out: &mut Vec<u8>, len: usize) {
97    if len < 0x80 {
98        out.push(len as u8);
99    } else {
100        let bytes = len.to_be_bytes();
101        let skip = bytes.iter().take_while(|&&b| b == 0).count();
102        let significant = &bytes[skip..];
103        out.push(0x80 | significant.len() as u8);
104        out.extend_from_slice(significant);
105    }
106}
107
108/// A DER INTEGER holding the unsigned big-endian number `value` (not empty).
109fn der_unsigned_integer(value: &[u8]) -> Vec<u8> {
110    let mut body = Vec::with_capacity(value.len() + 1);
111    if value[0] & 0x80 != 0 {
112        body.push(0x00); // keep it positive
113    }
114    body.extend_from_slice(value);
115    let mut out = vec![0x02];
116    der_push_length(&mut out, body.len());
117    out.extend(body);
118    out
119}
120
121/// DPoP manager for handling proof-of-possession
122pub struct DpopManager {
123    /// Used nonces to prevent replay attacks
124    used_nonces: tokio::sync::RwLock<HashMap<String, DateTime<Utc>>>,
125
126    /// DPoP proof expiration time (default: 60 seconds)
127    proof_expiration: Duration,
128
129    /// Most replay records kept at once.
130    max_replay_entries: usize,
131
132    /// The shortest time between two sweeps of a full cache.
133    sweep_interval: Duration,
134
135    /// When the cache was last swept.
136    last_sweep: std::sync::Mutex<DateTime<Utc>>,
137
138    /// The earliest time any held record expires (the far future when none is held).
139    earliest_expiry: std::sync::Mutex<DateTime<Utc>>,
140
141    /// Maximum clock skew allowed (default: 30 seconds)
142    clock_skew: Duration,
143}
144
145impl std::fmt::Debug for DpopManager {
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        let mut d = f.debug_struct("DpopManager");
148        d.field(
149            "used_nonces",
150            &crate::utils::redact::redacted(&self.used_nonces),
151        );
152        d.field("proof_expiration", &self.proof_expiration);
153        d.field("clock_skew", &self.clock_skew);
154        d.finish()
155    }
156}
157
158#[cfg(test)]
159impl DpopManager {
160    /// Put a replay record in place, valid until `until` (tests).
161    pub(crate) async fn insert_record_for_test(&self, key: &str, until: DateTime<Utc>) {
162        {
163            let mut earliest = self
164                .earliest_expiry
165                .lock()
166                .unwrap_or_else(|e| e.into_inner());
167            *earliest = (*earliest).min(until);
168        }
169        self.used_nonces
170            .write()
171            .await
172            .insert(key.to_string(), until);
173    }
174}
175
176impl DpopManager {
177    /// Create a new DPoP manager
178    pub fn new(_jwt_validator: SecureJwtValidator) -> Self {
179        Self {
180            used_nonces: tokio::sync::RwLock::new(HashMap::new()),
181            proof_expiration: Duration::seconds(60),
182            max_replay_entries: 100_000,
183            sweep_interval: Duration::seconds(1),
184            last_sweep: std::sync::Mutex::new(DateTime::<Utc>::UNIX_EPOCH),
185            earliest_expiry: std::sync::Mutex::new(DateTime::<Utc>::MAX_UTC),
186            clock_skew: Duration::seconds(30),
187        }
188    }
189
190    /// Validate a DPoP proof JWT
191    pub async fn validate_dpop_proof(
192        &self,
193        dpop_proof: &str,
194        http_method: &str,
195        http_uri: &str,
196        access_token: Option<&str>,
197        expected_nonce: Option<&str>,
198    ) -> Result<DpopValidationResult> {
199        self.validate_dpop_proof_for_key(
200            dpop_proof,
201            http_method,
202            http_uri,
203            access_token,
204            expected_nonce,
205            None,
206        )
207        .await
208    }
209
210    /// Like [`Self::validate_dpop_proof`]; when `expected_jkt` is given, the proof must also be
211    /// signed by the key with that thumbprint. That is checked before the proof's `jti` is
212    /// recorded, so a proof from any other key leaves no record behind.
213    pub async fn validate_dpop_proof_for_key(
214        &self,
215        dpop_proof: &str,
216        http_method: &str,
217        http_uri: &str,
218        access_token: Option<&str>,
219        expected_nonce: Option<&str>,
220        expected_jkt: Option<&str>,
221    ) -> Result<DpopValidationResult> {
222        let verified = self
223            .verify_dpop_proof(
224                dpop_proof,
225                http_method,
226                http_uri,
227                access_token,
228                expected_nonce,
229                expected_jkt,
230            )
231            .await?;
232        self.commit_dpop_proof(verified).await
233    }
234
235    /// Check a proof without recording it: signature, key binding, claims and a read-only look
236    /// at the replay cache. The caller commits it with `commit_dpop_proof` after it has
237    /// authenticated whatever else the request carries.
238    pub(crate) async fn verify_dpop_proof(
239        &self,
240        dpop_proof: &str,
241        http_method: &str,
242        http_uri: &str,
243        access_token: Option<&str>,
244        expected_nonce: Option<&str>,
245        expected_jkt: Option<&str>,
246    ) -> Result<VerifiedDpopProof> {
247        let mut errors = Vec::new();
248
249        // Parse the DPoP proof JWT
250        let (header, claims) = self.parse_dpop_proof(dpop_proof).map_err(|e| {
251            errors.push(format!("Failed to parse DPoP proof: {}", e));
252            e
253        })?;
254
255        // Validate JWT header; a header that is not a DPoP header stops here.
256        self.validate_dpop_header(&header, &mut errors)?;
257        if !errors.is_empty() {
258            return Err(Self::rejected(&errors));
259        }
260
261        // Extract public key from header
262        let public_key_jwk = header
263            .get("jwk")
264            .ok_or_else(|| AuthError::auth_method("dpop", "Missing JWK in DPoP proof header"))?
265            .clone();
266
267        // RFC 9449 section 4.2: the jwk header MUST NOT contain a private key.
268        if let Some(obj) = public_key_jwk.as_object() {
269            for private_member in ["d", "p", "q", "dp", "dq", "qi", "oth", "k"] {
270                if obj.contains_key(private_member) {
271                    return Err(AuthError::auth_method(
272                        "dpop",
273                        "DPoP proof jwk header contains private key material",
274                    ));
275                }
276            }
277        }
278
279        // Calculate JWK thumbprint
280        let jwk_thumbprint = self.calculate_jwk_thumbprint(&public_key_jwk)?;
281
282        // Verify the signature first: nothing unsigned reaches the replay cache.
283        self.verify_dpop_signature(dpop_proof, &public_key_jwk, &mut errors)?;
284
285        // The key the token is bound to, compared before anything is recorded.
286        if let Some(expected) = expected_jkt
287            && !bool::from(subtle::ConstantTimeEq::ct_eq(
288                jwk_thumbprint.as_bytes(),
289                expected.as_bytes(),
290            ))
291        {
292            return Err(AuthError::auth_method(
293                "dpop",
294                "DPoP proof key does not match the token's key binding",
295            ));
296        }
297
298        // Validate DPoP proof claims
299        self.validate_dpop_claims(
300            &claims,
301            http_method,
302            http_uri,
303            access_token,
304            expected_nonce,
305            &mut errors,
306        )
307        .await?;
308
309        // The jti is the replay key: bound its size before it is used for anything.
310        if claims.jti.is_empty() || claims.jti.len() > 256 {
311            errors.push("DPoP proof jti must be 1 to 256 bytes".to_string());
312        }
313
314        // A claim that fails is a refusal, not a result for the caller to remember to read.
315        if !errors.is_empty() {
316            return Err(Self::rejected(&errors));
317        }
318
319        // Only now, with an iat inside the clock skew, is there arithmetic to do on it.
320        let keep_until = chrono::TimeZone::timestamp_opt(&Utc, claims.iat, 0)
321            .single()
322            .and_then(|iat| iat.checked_add_signed(self.proof_expiration + self.clock_skew))
323            .ok_or_else(|| AuthError::auth_method("dpop", "DPoP proof iat is out of range"))?;
324        let key = Self::replay_key(&jwk_thumbprint, &claims.jti);
325        if self.used_nonces.read().await.contains_key(&key) {
326            return Err(Self::rejected(&["DPoP proof JTI already used".to_string()]));
327        }
328
329        Ok(VerifiedDpopProof {
330            result: DpopValidationResult {
331                is_valid: true,
332                errors,
333                public_key_jwk: Some(public_key_jwk),
334                jwk_thumbprint: Some(jwk_thumbprint),
335            },
336            replay_id: key,
337            keep_until,
338        })
339    }
340
341    /// Record a verified proof so it cannot be used again.
342    ///
343    /// A record is kept until the proof could no longer be accepted (iat + lifetime + skew), is
344    /// keyed by a hash of the proof key and the jti (a fixed size, and one client cannot spend
345    /// another's jti), and the cache is bounded: when it is full of live records the proof is
346    /// refused rather than an older record evicted, since an evicted record could be replayed.
347    /// A full cache is swept at most once per sweep interval.
348    pub(crate) async fn commit_dpop_proof(
349        &self,
350        verified: VerifiedDpopProof,
351    ) -> Result<DpopValidationResult> {
352        let now = Utc::now();
353        let mut used = self.used_nonces.write().await;
354        let full = used.len() >= self.max_replay_entries;
355        if full || used.len().is_multiple_of(256) {
356            let due = {
357                let mut last = self.last_sweep.lock().unwrap_or_else(|e| e.into_inner());
358                if now - *last >= self.sweep_interval {
359                    *last = now;
360                    true
361                } else {
362                    false
363                }
364            };
365            // A full cache that holds an expired record is swept whatever the interval: the
366            // proof in hand must not be refused for room that expired records are taking.
367            let expired_waiting = *self
368                .earliest_expiry
369                .lock()
370                .unwrap_or_else(|e| e.into_inner())
371                <= now;
372            if due || (full && expired_waiting) {
373                used.retain(|_, until| *until > now);
374                *self
375                    .earliest_expiry
376                    .lock()
377                    .unwrap_or_else(|e| e.into_inner()) = used
378                    .values()
379                    .min()
380                    .copied()
381                    .unwrap_or(DateTime::<Utc>::MAX_UTC);
382            }
383        }
384        if used.contains_key(&verified.replay_id) {
385            return Err(Self::rejected(&["DPoP proof JTI already used".to_string()]));
386        }
387        if used.len() >= self.max_replay_entries {
388            return Err(Self::rejected(&["DPoP replay cache is full".to_string()]));
389        }
390        {
391            let mut earliest = self
392                .earliest_expiry
393                .lock()
394                .unwrap_or_else(|e| e.into_inner());
395            *earliest = (*earliest).min(verified.keep_until);
396        }
397        used.insert(verified.replay_id, verified.keep_until);
398        Ok(verified.result)
399    }
400
401    /// The replay record key: a fixed-size hash of the proof key and the jti.
402    fn replay_key(jwk_thumbprint: &str, jti: &str) -> String {
403        use sha2::{Digest, Sha256};
404        let mut hasher = Sha256::new();
405        hasher.update(jwk_thumbprint.as_bytes());
406        hasher.update([0x1f]);
407        hasher.update(jti.as_bytes());
408        URL_SAFE_NO_PAD.encode(hasher.finalize())
409    }
410
411    /// The error returned when a proof fails any check.
412    fn rejected(errors: &[String]) -> AuthError {
413        AuthError::auth_method(
414            "dpop",
415            format!("DPoP proof rejected: {}", errors.join("; ")),
416        )
417    }
418
419    /// Create DPoP confirmation for access token
420    pub fn create_dpop_confirmation(
421        &self,
422        public_key_jwk: &serde_json::Value,
423    ) -> Result<DpopConfirmation> {
424        let jkt = self.calculate_jwk_thumbprint(public_key_jwk)?;
425
426        Ok(DpopConfirmation { jkt })
427    }
428
429    /// Validate DPoP-bound access token
430    pub fn validate_dpop_bound_token(
431        &self,
432        token_confirmation: &DpopConfirmation,
433        dpop_proof_jwk: &serde_json::Value,
434    ) -> Result<bool> {
435        let proof_thumbprint = self.calculate_jwk_thumbprint(dpop_proof_jwk)?;
436
437        if bool::from(subtle::ConstantTimeEq::ct_eq(
438            token_confirmation.jkt.as_bytes(),
439            proof_thumbprint.as_bytes(),
440        )) {
441            Ok(true)
442        } else {
443            Err(AuthError::auth_method(
444                "dpop",
445                "DPoP proof key does not match the token's key binding",
446            ))
447        }
448    }
449
450    /// Comprehensive validation of DPoP-bound access token with JWT validation
451    pub async fn validate_dpop_bound_access_token(
452        &self,
453        access_token: &str,
454        token_confirmation: &DpopConfirmation,
455        dpop_proof: &str,
456        http_method: &str,
457        http_uri: &str,
458    ) -> Result<bool> {
459        // First verify the DPoP proof itself; it is recorded only once the token has passed too.
460        let verified = self
461            .verify_dpop_proof(
462                dpop_proof,
463                http_method,
464                http_uri,
465                Some(access_token),
466                None, // No nonce required for this validation
467                None,
468            )
469            .await?;
470        let dpop_result = verified.result();
471
472        if !dpop_result.is_valid {
473            return Err(Self::rejected(&dpop_result.errors));
474        }
475
476        // Validate that the DPoP proof JWK matches the token confirmation
477        if let Some(dpop_jwk) = &dpop_result.public_key_jwk {
478            let thumbprint_matches =
479                self.validate_dpop_bound_token(token_confirmation, dpop_jwk)?;
480            debug_assert!(thumbprint_matches, "a mismatch is an error above");
481        } else {
482            return Err(AuthError::auth_method(
483                "dpop",
484                "DPoP proof carried no public key",
485            ));
486        }
487
488        // Additional validation: if the access token is also a JWT, validate it too
489        // This demonstrates another use of the jwt_validator field
490        if access_token.contains('.') && access_token.split('.').count() == 3 {
491            tracing::debug!("Access token appears to be a JWT, validating structure");
492
493            // For a DPoP-bound JWT access token, validate with proper signing key
494            match self.validate_access_token_jwt(access_token, dpop_proof) {
495                Ok(token_claims) => {
496                    tracing::debug!(
497                        "Access token JWT validated successfully with DPoP binding: {:?}",
498                        token_claims
499                            .get("sub")
500                            .and_then(|s| s.as_str())
501                            .unwrap_or("unknown")
502                    );
503                    // Verify DPoP proof matches token binding
504                    self.verify_dpop_token_binding(&token_claims, dpop_proof)?;
505                }
506                Err(e) => {
507                    tracing::warn!("Access token JWT validation failed: {}", e);
508                    return Err(AuthError::InvalidToken(
509                        "Invalid DPoP-bound access token".to_string(),
510                    ));
511                }
512            }
513        } else {
514            // An opaque token can only be validated by introspection, which this function does
515            // not do: it must not report a token it never looked at as valid.
516            return Err(AuthError::token(
517                "An opaque access token cannot be validated here; introspect it before relying on its DPoP binding"
518                    .to_string(),
519            ));
520        }
521
522        self.commit_dpop_proof(verified).await?;
523        Ok(true)
524    }
525
526    /// Generate a nonce for DPoP proof
527    pub fn generate_nonce(&self) -> String {
528        use rand::RngCore;
529        let mut rng = rand::rng();
530        let mut nonce = [0u8; 16];
531        rng.fill_bytes(&mut nonce);
532        URL_SAFE_NO_PAD.encode(nonce)
533    }
534
535    /// Clean up expired nonces
536    pub async fn cleanup_expired_nonces(&self) {
537        self.sweep(Utc::now()).await;
538    }
539
540    /// Drop the replay records that no longer matter at time `at`.
541    async fn sweep(&self, at: DateTime<Utc>) {
542        let mut nonces = self.used_nonces.write().await;
543        // Each record is the time until which its proof could still be accepted.
544        nonces.retain(|_, until| *until > at);
545    }
546
547    /// Parse DPoP proof JWT and extract header and claims
548    fn parse_dpop_proof(&self, dpop_proof: &str) -> Result<(serde_json::Value, DpopProofClaims)> {
549        if dpop_proof.len() > 16 * 1024 {
550            return Err(AuthError::auth_method("dpop", "DPoP proof is too large"));
551        }
552        // Split JWT into parts
553        let parts: Vec<&str> = dpop_proof.split('.').collect();
554        if parts.len() != 3 {
555            return Err(AuthError::auth_method("dpop", "Invalid JWT format"));
556        }
557
558        // Decode header
559        let header_bytes = URL_SAFE_NO_PAD
560            .decode(parts[0])
561            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header encoding"))?;
562        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
563            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header JSON"))?;
564
565        // Decode claims
566        let claims_bytes = URL_SAFE_NO_PAD
567            .decode(parts[1])
568            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT claims encoding"))?;
569        let claims: DpopProofClaims = serde_json::from_slice(&claims_bytes)
570            .map_err(|_| AuthError::auth_method("dpop", "Invalid DPoP proof claims"))?;
571
572        Ok((header, claims))
573    }
574
575    /// Validate DPoP JWT header
576    fn validate_dpop_header(
577        &self,
578        header: &serde_json::Value,
579        errors: &mut Vec<String>,
580    ) -> Result<()> {
581        // Check required fields
582        if header.get("typ").and_then(|v| v.as_str()) != Some("dpop+jwt") {
583            errors.push("DPoP proof must have 'typ' header value 'dpop+jwt'".to_string());
584        }
585
586        if header.get("alg").and_then(|v| v.as_str()).is_none() {
587            errors.push("DPoP proof missing 'alg' header".to_string());
588        }
589
590        if header.get("jwk").is_none() {
591            errors.push("DPoP proof missing 'jwk' header".to_string());
592        }
593
594        // Validate algorithm is not 'none'
595        if let Some(alg) = header.get("alg").and_then(|v| v.as_str())
596            && alg == "none"
597        {
598            errors.push("DPoP proof algorithm cannot be 'none'".to_string());
599        }
600
601        Ok(())
602    }
603
604    /// Validate DPoP proof claims
605    async fn validate_dpop_claims(
606        &self,
607        claims: &DpopProofClaims,
608        http_method: &str,
609        http_uri: &str,
610        access_token: Option<&str>,
611        expected_nonce: Option<&str>,
612        errors: &mut Vec<String>,
613    ) -> Result<()> {
614        let now = Utc::now();
615        let iat =
616            DateTime::from_timestamp(claims.iat, 0).unwrap_or_else(|| now - Duration::hours(1));
617
618        // Validate timestamp
619        let min_time = now - self.proof_expiration - self.clock_skew;
620        let max_time = now + self.clock_skew;
621
622        if iat < min_time {
623            errors.push("DPoP proof is too old".to_string());
624        }
625
626        if iat > max_time {
627            errors.push("DPoP proof timestamp is in the future".to_string());
628        }
629
630        // Validate HTTP method and URI
631        if claims.htm != http_method {
632            errors.push(format!(
633                "DPoP proof HTTP method '{}' does not match request method '{}'",
634                claims.htm, http_method
635            ));
636        }
637
638        // Parse and compare URIs (normalize by removing query and fragment)
639        let expected_uri = self.normalize_uri(http_uri)?;
640        let proof_uri = self.normalize_uri(&claims.htu)?;
641
642        if proof_uri != expected_uri {
643            errors.push(format!(
644                "DPoP proof HTTP URI '{}' does not match request URI '{}'",
645                claims.htu, http_uri
646            ));
647        }
648
649        // RFC 9449 section 4.2/7.1: a proof presented with an access token MUST carry its hash.
650        if let Some(token) = access_token {
651            let expected_ath = self.calculate_access_token_hash(token)?;
652            match &claims.ath {
653                Some(ath) => {
654                    use subtle::ConstantTimeEq as _;
655                    if !bool::from(ath.as_bytes().ct_eq(expected_ath.as_bytes())) {
656                        errors.push("DPoP proof access token hash does not match".to_string());
657                    }
658                }
659                None => errors.push(
660                    "DPoP proof is missing the 'ath' claim required with an access token"
661                        .to_string(),
662                ),
663            }
664        }
665
666        // Validate nonce if expected
667        if let Some(expected) = expected_nonce {
668            match &claims.nonce {
669                Some(nonce) if nonce == expected => {}
670                Some(_) => {
671                    errors.push("DPoP proof nonce does not match expected value".to_string());
672                }
673                None => {
674                    errors.push("DPoP proof missing required nonce".to_string());
675                }
676            }
677        }
678
679        Ok(())
680    }
681
682    /// Verify DPoP JWT signature with REAL cryptographic validation using Ring
683    fn verify_dpop_signature(
684        &self,
685        dpop_proof: &str,
686        public_key_jwk: &serde_json::Value,
687        errors: &mut Vec<String>,
688    ) -> Result<()> {
689        use ring::signature;
690
691        // Extract algorithm from JWT header
692        let parts: Vec<&str> = dpop_proof.split('.').collect();
693        if parts.len() != 3 {
694            return Err(AuthError::validation("Invalid JWT format for DPoP proof"));
695        }
696
697        let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).map_err(|_| {
698            AuthError::validation("Invalid JWT header encoding for signature verification")
699        })?;
700        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
701            .map_err(|_| AuthError::validation("Invalid JWT header JSON"))?;
702
703        let alg_str = header
704            .get("alg")
705            .and_then(|v| v.as_str())
706            .ok_or_else(|| AuthError::validation("Missing algorithm in JWT header"))?;
707
708        // Prepare JWT signature verification data
709        let signing_input = format!("{}.{}", parts[0], parts[1]);
710        let signature_bytes = URL_SAFE_NO_PAD
711            .decode(parts[2])
712            .map_err(|_| AuthError::validation("Invalid JWT signature encoding"))?;
713
714        // Extract key material from JWK for direct Ring cryptographic validation
715        let key_type = public_key_jwk
716            .get("kty")
717            .and_then(|v| v.as_str())
718            .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
719
720        // Perform REAL cryptographic validation using Ring
721        match key_type {
722            "RSA" => {
723                // Extract RSA public key components
724                let n = public_key_jwk
725                    .get("n")
726                    .and_then(|v| v.as_str())
727                    .ok_or_else(|| AuthError::validation("Missing 'n' parameter in RSA JWK"))?;
728                let e = public_key_jwk
729                    .get("e")
730                    .and_then(|v| v.as_str())
731                    .ok_or_else(|| AuthError::validation("Missing 'e' parameter in RSA JWK"))?;
732
733                // Decode RSA components
734                let n_bytes = URL_SAFE_NO_PAD.decode(n.as_bytes()).map_err(|e| {
735                    AuthError::validation(format!("Invalid base64url 'n' parameter: {}", e))
736                })?;
737                let e_bytes = URL_SAFE_NO_PAD.decode(e.as_bytes()).map_err(|e| {
738                    AuthError::validation(format!("Invalid base64url 'e' parameter: {}", e))
739                })?;
740
741                if n_bytes.is_empty() || e_bytes.is_empty() {
742                    return Err(AuthError::validation("Empty RSA JWK parameter"));
743                }
744
745                // The key as a DER RSAPublicKey: SEQUENCE { modulus INTEGER, exponent INTEGER },
746                // lengths in the long form when they need it (a 2048-bit modulus does).
747                let mut content = der_unsigned_integer(&n_bytes);
748                content.extend(der_unsigned_integer(&e_bytes));
749                let mut public_key_der = vec![0x30];
750                der_push_length(&mut public_key_der, content.len());
751                public_key_der.extend_from_slice(&content);
752
753                // Select Ring verification algorithm
754                let verification_algorithm = match alg_str {
755                    "RS256" => &signature::RSA_PKCS1_2048_8192_SHA256,
756                    "RS384" => &signature::RSA_PKCS1_2048_8192_SHA384,
757                    "RS512" => &signature::RSA_PKCS1_2048_8192_SHA512,
758                    "PS256" => &signature::RSA_PSS_2048_8192_SHA256,
759                    "PS384" => &signature::RSA_PSS_2048_8192_SHA384,
760                    "PS512" => &signature::RSA_PSS_2048_8192_SHA512,
761                    _ => {
762                        return Err(AuthError::validation(format!(
763                            "Unsupported RSA algorithm: {}",
764                            alg_str
765                        )));
766                    }
767                };
768
769                // Create public key and verify with timing-safe operations
770                let public_key =
771                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_der);
772
773                // Use constant-time verification to prevent timing attacks
774                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
775                    Ok(()) => {
776                        // Add timing protection: always do the same amount of work
777                        let _ = std::hint::black_box(alg_str);
778                        tracing::debug!(
779                            "DPoP proof RSA signature successfully verified using Ring with algorithm {}",
780                            alg_str
781                        );
782                    }
783                    Err(_) => {
784                        // Add timing protection: always do the same amount of work
785                        let _ = std::hint::black_box(alg_str);
786                        let error_msg = format!(
787                            "DPoP proof RSA signature verification failed with algorithm {}",
788                            alg_str
789                        );
790                        errors.push(error_msg.clone());
791                        tracing::warn!("{}", error_msg);
792                        return Err(AuthError::validation(
793                            "DPoP RSA signature verification failed",
794                        ));
795                    }
796                }
797            }
798            "EC" => {
799                // Extract elliptic curve public key components
800                let curve = public_key_jwk
801                    .get("crv")
802                    .and_then(|v| v.as_str())
803                    .ok_or_else(|| AuthError::validation("Missing 'crv' parameter in EC JWK"))?;
804                let x = public_key_jwk
805                    .get("x")
806                    .and_then(|v| v.as_str())
807                    .ok_or_else(|| AuthError::validation("Missing 'x' parameter in EC JWK"))?;
808                let y = public_key_jwk
809                    .get("y")
810                    .and_then(|v| v.as_str())
811                    .ok_or_else(|| AuthError::validation("Missing 'y' parameter in EC JWK"))?;
812
813                // Decode EC coordinates
814                let x_bytes = URL_SAFE_NO_PAD.decode(x.as_bytes()).map_err(|e| {
815                    AuthError::validation(format!("Invalid base64url 'x' parameter: {}", e))
816                })?;
817                let y_bytes = URL_SAFE_NO_PAD.decode(y.as_bytes()).map_err(|e| {
818                    AuthError::validation(format!("Invalid base64url 'y' parameter: {}", e))
819                })?;
820
821                // Select verification algorithm and coordinate length
822                let (verification_algorithm, expected_coord_len) = match (curve, alg_str) {
823                    ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_FIXED, 32),
824                    ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_FIXED, 48),
825                    _ => {
826                        return Err(AuthError::validation(format!(
827                            "Unsupported EC curve/algorithm combination: {}/{}",
828                            curve, alg_str
829                        )));
830                    }
831                };
832
833                // Validate coordinate lengths
834                if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
835                    return Err(AuthError::validation(format!(
836                        "Invalid coordinate length for curve {}: expected {}, got x={}, y={}",
837                        curve,
838                        expected_coord_len,
839                        x_bytes.len(),
840                        y_bytes.len()
841                    )));
842                }
843
844                // A JWS ECDSA signature is exactly r || s, two coordinates wide (RFC 7518 3.4);
845                // a DER-encoded signature is not one.
846                if signature_bytes.len() != expected_coord_len * 2 {
847                    return Err(AuthError::validation(format!(
848                        "DPoP {alg_str} signature must be the {}-byte r||s form (RFC 7518 section 3.4), got {} bytes",
849                        expected_coord_len * 2,
850                        signature_bytes.len()
851                    )));
852                }
853
854                // Create uncompressed point format (0x04 || x || y)
855                let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
856                public_key_bytes.push(0x04); // Uncompressed point indicator
857                public_key_bytes.extend_from_slice(&x_bytes);
858                public_key_bytes.extend_from_slice(&y_bytes);
859
860                // Create public key for verification
861                let public_key =
862                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
863
864                // Verify ECDSA signature with timing protection
865                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
866                    Ok(()) => {
867                        // Add timing protection: always do the same amount of work
868                        let _ = std::hint::black_box((curve, alg_str));
869                        tracing::debug!(
870                            "DPoP proof ECDSA signature successfully verified using Ring with curve {} and algorithm {}",
871                            curve,
872                            alg_str
873                        );
874                    }
875                    Err(_) => {
876                        // Add timing protection: always do the same amount of work
877                        let _ = std::hint::black_box((curve, alg_str));
878                        let error_msg = format!(
879                            "DPoP proof ECDSA signature verification failed with curve {} and algorithm {}",
880                            curve, alg_str
881                        );
882                        errors.push(error_msg.clone());
883                        tracing::warn!("{}", error_msg);
884                        return Err(AuthError::validation(
885                            "DPoP ECDSA signature verification failed",
886                        ));
887                    }
888                }
889            }
890            _ => {
891                return Err(AuthError::validation(format!(
892                    "Unsupported key type for cryptographic verification: {}",
893                    key_type
894                )));
895            }
896        }
897
898        // Additional validation: verify that the JWT contains required DPoP claims
899        let claims_bytes = URL_SAFE_NO_PAD
900            .decode(parts[1])
901            .map_err(|_| AuthError::validation("Invalid JWT claims encoding"))?;
902        let claims: serde_json::Value = serde_json::from_slice(&claims_bytes)
903            .map_err(|_| AuthError::validation("Invalid JWT claims JSON"))?;
904
905        // Check for required DPoP claims
906        if claims.get("htm").is_none() {
907            errors.push("DPoP proof missing 'htm' claim".to_string());
908        }
909        if claims.get("htu").is_none() {
910            errors.push("DPoP proof missing 'htu' claim".to_string());
911        }
912        if claims.get("jti").is_none() {
913            errors.push("DPoP proof missing 'jti' claim".to_string());
914        }
915        if claims.get("iat").is_none() {
916            errors.push("DPoP proof missing 'iat' claim".to_string());
917        }
918
919        Ok(())
920    }
921
922    /// Calculate JWK thumbprint (RFC 7638)
923    fn calculate_jwk_thumbprint(&self, jwk: &serde_json::Value) -> Result<String> {
924        use sha2::{Digest, Sha256};
925
926        // RFC 7638 section 3: only the required members, in lexicographic order, no whitespace.
927        let text = |name: &str| -> Result<String> {
928            let value = jwk.get(name).and_then(|v| v.as_str()).ok_or_else(|| {
929                AuthError::auth_method("dpop", format!("JWK is missing the '{name}' member"))
930            })?;
931            Ok(serde_json::Value::String(value.to_string()).to_string())
932        };
933        let kty = jwk
934            .get("kty")
935            .and_then(|v| v.as_str())
936            .ok_or_else(|| AuthError::auth_method("dpop", "JWK is missing the 'kty' member"))?;
937        if kty == "RSA" {
938            for name in ["n", "e"] {
939                let raw = jwk
940                    .get(name)
941                    .and_then(|v| v.as_str())
942                    .and_then(|s| URL_SAFE_NO_PAD.decode(s).ok());
943                // A leading zero octet would give the same key a second thumbprint.
944                if raw
945                    .as_deref()
946                    .is_none_or(|r| r.first().is_none_or(|&b| b == 0))
947                {
948                    return Err(AuthError::auth_method(
949                        "dpop",
950                        format!("RSA JWK member '{name}' is not a minimal base64url integer"),
951                    ));
952                }
953            }
954        }
955        let canonical_json = match kty {
956            "EC" => format!(
957                r#"{{"crv":{},"kty":"EC","x":{},"y":{}}}"#,
958                text("crv")?,
959                text("x")?,
960                text("y")?
961            ),
962            "RSA" => format!(r#"{{"e":{},"kty":"RSA","n":{}}}"#, text("e")?, text("n")?),
963            "OKP" => format!(
964                r#"{{"crv":{},"kty":"OKP","x":{}}}"#,
965                text("crv")?,
966                text("x")?
967            ),
968            other => {
969                return Err(AuthError::auth_method(
970                    "dpop",
971                    format!("Unsupported JWK key type for a thumbprint: {other}"),
972                ));
973            }
974        };
975
976        // Calculate SHA-256 hash
977        let mut hasher = Sha256::new();
978        hasher.update(canonical_json.as_bytes());
979        let hash = hasher.finalize();
980
981        Ok(URL_SAFE_NO_PAD.encode(hash))
982    }
983
984    /// Calculate access token hash for DPoP proof
985    fn calculate_access_token_hash(&self, access_token: &str) -> Result<String> {
986        use sha2::{Digest, Sha256};
987
988        let mut hasher = Sha256::new();
989        hasher.update(access_token.as_bytes());
990        let hash = hasher.finalize();
991
992        Ok(URL_SAFE_NO_PAD.encode(hash))
993    }
994
995    /// Normalize URI by removing query and fragment components
996    fn normalize_uri(&self, uri: &str) -> Result<String> {
997        let url = url::Url::parse(uri)
998            .map_err(|_| AuthError::auth_method("dpop", "Invalid URI format"))?;
999
1000        // Reconstruct URL without query and fragment
1001        let normalized = match url.port() {
1002            Some(port) => format!(
1003                "{}://{}:{}{}",
1004                url.scheme(),
1005                url.host_str().unwrap_or(""),
1006                port,
1007                url.path()
1008            ),
1009            None => format!(
1010                "{}://{}{}",
1011                url.scheme(),
1012                url.host_str().unwrap_or(""),
1013                url.path()
1014            ),
1015        };
1016
1017        Ok(normalized)
1018    }
1019
1020    /// Validate JWT access token with DPoP binding
1021    fn validate_access_token_jwt(
1022        &self,
1023        access_token: &str,
1024        dpop_proof_jwt: &str,
1025    ) -> Result<serde_json::Value> {
1026        // Parse the access token as a JWT to extract claims
1027        let token_parts: Vec<&str> = access_token.split('.').collect();
1028        if token_parts.len() != 3 {
1029            return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
1030        }
1031
1032        // Decode the payload (claims) section
1033        let payload = URL_SAFE_NO_PAD
1034            .decode(token_parts[1])
1035            .map_err(|_| AuthError::InvalidToken("Invalid JWT payload encoding".to_string()))?;
1036
1037        let claims: serde_json::Value = serde_json::from_slice(&payload)
1038            .map_err(|_| AuthError::InvalidToken("Invalid JWT claims format".to_string()))?;
1039
1040        // Parse the DPoP proof to get the JWK
1041        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
1042
1043        // Verify the access token is properly bound to the DPoP proof
1044        if let Some(cnf) = claims.get("cnf").and_then(|c| c.as_object())
1045            && let Some(jkt) = cnf.get("jkt").and_then(|j| j.as_str())
1046            && let Some(jwk) = dpop_header.get("jwk")
1047        {
1048            let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
1049            if jkt == dpop_jkt {
1050                tracing::debug!(
1051                    "Access token DPoP binding verified for subject: {:?}",
1052                    claims
1053                        .get("sub")
1054                        .and_then(|s| s.as_str())
1055                        .unwrap_or("unknown")
1056                );
1057                return Ok(claims);
1058            }
1059        }
1060
1061        Err(AuthError::InvalidToken(
1062            "Access token not bound to DPoP key".to_string(),
1063        ))
1064    }
1065
1066    /// Verify DPoP proof matches token binding
1067    fn verify_dpop_token_binding(
1068        &self,
1069        token_claims: &serde_json::Value,
1070        dpop_proof_jwt: &str,
1071    ) -> Result<()> {
1072        // Extract confirmation claim from access token
1073        let cnf = token_claims
1074            .get("cnf")
1075            .and_then(|c| c.as_object())
1076            .ok_or_else(|| {
1077                AuthError::InvalidToken("Access token missing confirmation claim".to_string())
1078            })?;
1079
1080        let token_jkt = cnf.get("jkt").and_then(|j| j.as_str()).ok_or_else(|| {
1081            AuthError::InvalidToken("Access token missing JWK thumbprint".to_string())
1082        })?;
1083
1084        // Calculate thumbprint from DPoP proof JWK
1085        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
1086        let jwk = dpop_header
1087            .get("jwk")
1088            .ok_or_else(|| AuthError::InvalidToken("DPoP proof missing JWK".to_string()))?;
1089        let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
1090
1091        if token_jkt != dpop_jkt {
1092            return Err(AuthError::InvalidToken(
1093                "DPoP proof JWK does not match access token binding".to_string(),
1094            ));
1095        }
1096
1097        Ok(())
1098    }
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103    use super::*;
1104    use crate::security::secure_jwt::SecureJwtConfig;
1105
1106    fn create_test_dpop_manager() -> DpopManager {
1107        let jwt_config = SecureJwtConfig::default();
1108        let jwt_validator = SecureJwtValidator::new(jwt_config);
1109        DpopManager::new(jwt_validator)
1110    }
1111    fn create_test_jwk() -> serde_json::Value {
1112        serde_json::json!({
1113            "kty": "EC",
1114            "crv": "P-256",
1115            "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
1116            "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
1117            "use": "sig",
1118            "alg": "ES256"
1119        })
1120    }
1121
1122    #[tokio::test]
1123    async fn test_dpop_manager_creation() {
1124        let manager = create_test_dpop_manager();
1125        let nonce = manager.generate_nonce();
1126        assert!(!nonce.is_empty());
1127    }
1128
1129    #[test]
1130    fn test_jwk_thumbprint_calculation() {
1131        let manager = create_test_dpop_manager();
1132        let jwk = create_test_jwk();
1133
1134        let thumbprint = manager.calculate_jwk_thumbprint(&jwk).unwrap();
1135        assert!(!thumbprint.is_empty());
1136
1137        // Same JWK should produce same thumbprint
1138        let thumbprint2 = manager.calculate_jwk_thumbprint(&jwk).unwrap();
1139        assert_eq!(thumbprint, thumbprint2);
1140    }
1141
1142    #[test]
1143    fn test_dpop_confirmation() {
1144        let manager = create_test_dpop_manager();
1145        let jwk = create_test_jwk();
1146
1147        let confirmation = manager.create_dpop_confirmation(&jwk).unwrap();
1148        assert!(!confirmation.jkt.is_empty());
1149
1150        // Validate with same JWK
1151        let is_valid = manager
1152            .validate_dpop_bound_token(&confirmation, &jwk)
1153            .unwrap();
1154        assert!(is_valid);
1155
1156        // Validate with different JWK (should fail)
1157        let different_jwk = serde_json::json!({
1158            "kty": "EC",
1159            "crv": "P-256",
1160            "x": "different_x_value_here_for_testing_purposes",
1161            "y": "different_y_value_here_for_testing_purposes",
1162            "use": "sig",
1163            "alg": "ES256"
1164        });
1165
1166        let mismatch = manager.validate_dpop_bound_token(&confirmation, &different_jwk);
1167        assert!(mismatch.is_err(), "another key is an error, not Ok(false)");
1168    }
1169
1170    #[test]
1171    fn test_uri_normalization() {
1172        let manager = create_test_dpop_manager();
1173
1174        let uri = "https://example.com/api/resource?param=value#fragment";
1175        let normalized = manager.normalize_uri(uri).unwrap();
1176        assert_eq!(normalized, "https://example.com/api/resource");
1177
1178        let uri2 = "https://example.com/api/resource";
1179        let normalized2 = manager.normalize_uri(uri2).unwrap();
1180        assert_eq!(normalized2, "https://example.com/api/resource");
1181    }
1182
1183    #[test]
1184    fn test_access_token_hash() {
1185        let manager = create_test_dpop_manager();
1186
1187        let token = "test_access_token_value";
1188        let hash = manager.calculate_access_token_hash(token).unwrap();
1189        assert!(!hash.is_empty());
1190
1191        // Same token should produce same hash
1192        let hash2 = manager.calculate_access_token_hash(token).unwrap();
1193        assert_eq!(hash, hash2);
1194    }
1195
1196    #[tokio::test]
1197    async fn test_nonce_cleanup() {
1198        let manager = create_test_dpop_manager();
1199
1200        // Add some test nonces
1201        {
1202            let mut nonces = manager.used_nonces.write().await;
1203            nonces.insert("old_nonce".to_string(), Utc::now() - Duration::hours(1));
1204            nonces.insert(
1205                "recent_nonce".to_string(),
1206                Utc::now() + Duration::seconds(60),
1207            );
1208        }
1209
1210        // Cleanup should remove old nonces
1211        manager.cleanup_expired_nonces().await;
1212
1213        let nonces = manager.used_nonces.read().await;
1214        assert!(!nonces.contains_key("old_nonce"));
1215        assert!(nonces.contains_key("recent_nonce"));
1216    }
1217}
1218
1219#[cfg(test)]
1220mod dpop_regression {
1221    //! `validate_dpop_proof` refuses every wrong proof, with its own reason, and accepts the right
1222    //! one. Each refusal is paired with the accepted case built the same way, so a test cannot
1223    //! pass because every proof fails for one shared reason.
1224    use super::*;
1225    use crate::security::secure_jwt::{SecureJwtConfig, SecureJwtValidator};
1226    use jsonwebtoken::{Algorithm, EncodingKey};
1227    use serde_json::json;
1228    use sha2::{Digest, Sha256};
1229
1230    const URI: &str = "https://rs.example.com/resource";
1231    const TOKEN: &str = "access-token-1";
1232
1233    fn ec_key() -> (EncodingKey, serde_json::Value) {
1234        let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256).unwrap();
1235        let raw = key.public_key_raw();
1236        let point = &raw[raw.len() - 65..];
1237        let jwk = json!({
1238            "kty": "EC", "crv": "P-256",
1239            "x": URL_SAFE_NO_PAD.encode(&point[1..33]),
1240            "y": URL_SAFE_NO_PAD.encode(&point[33..65]),
1241        });
1242        (
1243            EncodingKey::from_ec_pem(key.serialize_pem().as_bytes()).unwrap(),
1244            jwk,
1245        )
1246    }
1247
1248    fn ath_of(token: &str) -> String {
1249        URL_SAFE_NO_PAD.encode(Sha256::digest(token.as_bytes()))
1250    }
1251
1252    struct Proof<'a> {
1253        key: &'a (EncodingKey, serde_json::Value),
1254        htm: &'a str,
1255        htu: &'a str,
1256        iat: i64,
1257        jti: &'a str,
1258        ath: Option<String>,
1259        der: bool,
1260        jwk_extra: Option<(&'a str, &'a str)>,
1261    }
1262
1263    impl Proof<'_> {
1264        fn build(&self) -> String {
1265            let mut jwk = self.key.1.clone();
1266            if let Some((k, v)) = self.jwk_extra {
1267                jwk[k] = json!(v);
1268            }
1269            let header = json!({"typ": "dpop+jwt", "alg": "ES256", "jwk": jwk});
1270            let mut claims =
1271                json!({"jti": self.jti, "htm": self.htm, "htu": self.htu, "iat": self.iat});
1272            if let Some(a) = &self.ath {
1273                claims["ath"] = json!(a);
1274            }
1275            let si = format!(
1276                "{}.{}",
1277                URL_SAFE_NO_PAD.encode(header.to_string()),
1278                URL_SAFE_NO_PAD.encode(claims.to_string())
1279            );
1280            // jsonwebtoken signs in the JWS form: r || s.
1281            let sig =
1282                jsonwebtoken::crypto::sign(si.as_bytes(), &self.key.0, Algorithm::ES256).unwrap();
1283            if !self.der {
1284                return format!("{si}.{sig}");
1285            }
1286            let raw = URL_SAFE_NO_PAD.decode(sig).unwrap();
1287            let int = |v: &[u8]| {
1288                let mut v: Vec<u8> = v.iter().copied().skip_while(|&x| x == 0).collect();
1289                if v.is_empty() || v[0] & 0x80 != 0 {
1290                    v.insert(0, 0);
1291                }
1292                let mut o = vec![0x02, v.len() as u8];
1293                o.extend(v);
1294                o
1295            };
1296            let mut body = int(&raw[..32]);
1297            body.extend(int(&raw[32..]));
1298            let mut der = vec![0x30, body.len() as u8];
1299            der.extend(body);
1300            format!("{si}.{}", URL_SAFE_NO_PAD.encode(der))
1301        }
1302    }
1303
1304    struct Fixture {
1305        dpop: DpopManager,
1306        key: (EncodingKey, serde_json::Value),
1307        now: i64,
1308    }
1309
1310    impl Fixture {
1311        fn new() -> Self {
1312            Fixture {
1313                dpop: DpopManager::new(SecureJwtValidator::new(SecureJwtConfig::default())),
1314                key: ec_key(),
1315                now: Utc::now().timestamp(),
1316            }
1317        }
1318
1319        fn good<'a>(&'a self, jti: &'a str) -> Proof<'a> {
1320            Proof {
1321                key: &self.key,
1322                htm: "GET",
1323                htu: URI,
1324                iat: self.now,
1325                jti,
1326                ath: Some(ath_of(TOKEN)),
1327                der: false,
1328                jwk_extra: None,
1329            }
1330        }
1331
1332        async fn present(&self, proof: &str) -> Result<DpopValidationResult> {
1333            self.dpop
1334                .validate_dpop_proof(proof, "GET", URI, Some(TOKEN), None)
1335                .await
1336        }
1337    }
1338
1339    fn refused(r: Result<DpopValidationResult>, reason: &str, what: &str) {
1340        match r {
1341            Ok(v) => panic!(
1342                "{what}: ACCEPTED (is_valid={}, errors={:?})",
1343                v.is_valid, v.errors
1344            ),
1345            Err(e) => assert!(
1346                e.to_string().contains(reason),
1347                "{what}: refused with {e:?}, expected a reason containing {reason:?}"
1348            ),
1349        }
1350    }
1351
1352    #[tokio::test]
1353    async fn a_correct_proof_is_accepted() {
1354        let f = Fixture::new();
1355        let ok = f
1356            .present(&f.good("j-ok").build())
1357            .await
1358            .expect("a correct proof is accepted");
1359        assert!(ok.is_valid && ok.errors.is_empty());
1360        assert_eq!(
1361            ok.jwk_thumbprint.as_deref(),
1362            Some(
1363                f.dpop
1364                    .create_dpop_confirmation(&f.key.1)
1365                    .unwrap()
1366                    .jkt
1367                    .as_str()
1368            )
1369        );
1370    }
1371
1372    #[tokio::test]
1373    async fn a_proof_for_another_method_url_or_time_is_refused() {
1374        let f = Fixture::new();
1375        let p = Proof {
1376            htm: "DELETE",
1377            ..f.good("j-htm")
1378        }
1379        .build();
1380        refused(f.present(&p).await, "HTTP method", "wrong htm");
1381        let p = Proof {
1382            htu: "https://evil.example/x",
1383            ..f.good("j-htu")
1384        }
1385        .build();
1386        refused(f.present(&p).await, "HTTP URI", "wrong htu");
1387        let p = Proof {
1388            iat: f.now - 86_400,
1389            ..f.good("j-old")
1390        }
1391        .build();
1392        refused(f.present(&p).await, "too old", "one-day-old iat");
1393        let p = Proof {
1394            iat: f.now + 86_400,
1395            ..f.good("j-future")
1396        }
1397        .build();
1398        refused(f.present(&p).await, "in the future", "future iat");
1399    }
1400
1401    #[tokio::test]
1402    async fn a_proof_without_an_access_token_needs_no_ath() {
1403        // The token endpoint: a proof is presented before any access token exists.
1404        let f = Fixture::new();
1405        let p = Proof {
1406            ath: None,
1407            ..f.good("j-endpoint")
1408        }
1409        .build();
1410        f.dpop
1411            .validate_dpop_proof(&p, "GET", URI, None, None)
1412            .await
1413            .expect("no access token, so no ath is required");
1414    }
1415
1416    #[tokio::test]
1417    async fn a_proof_used_twice_is_refused_the_second_time() {
1418        let f = Fixture::new();
1419        let once = f.good("j-replay").build();
1420        f.present(&once).await.expect("first use");
1421        refused(f.present(&once).await, "already used", "replayed proof");
1422    }
1423
1424    #[tokio::test]
1425    async fn a_proof_must_name_the_access_token() {
1426        let f = Fixture::new();
1427        let p = Proof {
1428            ath: None,
1429            ..f.good("j-no-ath")
1430        }
1431        .build();
1432        refused(f.present(&p).await, "'ath'", "no ath");
1433        let p = Proof {
1434            ath: Some(ath_of("another-token")),
1435            ..f.good("j-bad-ath")
1436        }
1437        .build();
1438        refused(f.present(&p).await, "access token hash", "wrong ath");
1439    }
1440
1441    #[tokio::test]
1442    async fn a_der_signature_or_a_private_key_in_the_header_is_refused() {
1443        let f = Fixture::new();
1444        let p = Proof {
1445            der: true,
1446            ..f.good("j-der")
1447        }
1448        .build();
1449        refused(f.present(&p).await, "r||s", "DER-encoded ES256 signature");
1450        let p = Proof {
1451            jwk_extra: Some(("d", "AAAA")),
1452            ..f.good("j-priv")
1453        }
1454        .build();
1455        refused(f.present(&p).await, "private key", "private key in jwk");
1456    }
1457
1458    #[tokio::test]
1459    async fn a_proof_refused_for_another_reason_does_not_use_up_its_jti() {
1460        let f = Fixture::new();
1461        let p = f.good("j-keep").build();
1462        // Presented for the wrong method: refused.
1463        refused(
1464            f.dpop
1465                .validate_dpop_proof(&p, "POST", URI, Some(TOKEN), None)
1466                .await,
1467            "HTTP method",
1468            "wrong method",
1469        );
1470        // The same proof, presented correctly afterwards, has not been spent.
1471        f.present(&p)
1472            .await
1473            .expect("a proof refused earlier for its method is not spent");
1474    }
1475
1476    #[tokio::test]
1477    async fn a_replay_record_outlives_the_proof_it_guards() {
1478        let f = Fixture::new();
1479        // An iat 25 s ahead is inside the 30 s skew: the proof stays acceptable until
1480        // iat + 60 s lifetime + 30 s skew.
1481        let p = Proof {
1482            iat: f.now + 25,
1483            ..f.good("j-late")
1484        }
1485        .build();
1486        f.present(&p).await.expect("within the clock skew");
1487        let acceptable_until = chrono::TimeZone::timestamp_opt(&Utc, f.now + 25 + 90, 0)
1488            .single()
1489            .unwrap();
1490        f.dpop.sweep(acceptable_until - Duration::seconds(1)).await;
1491        assert_eq!(
1492            f.dpop.used_nonces.read().await.len(),
1493            1,
1494            "record dropped while the proof could still be replayed"
1495        );
1496        f.dpop.sweep(acceptable_until + Duration::seconds(1)).await;
1497        assert!(
1498            f.dpop.used_nonces.read().await.is_empty(),
1499            "record kept after the proof can no longer be accepted"
1500        );
1501    }
1502
1503    #[tokio::test]
1504    async fn the_replay_cache_is_swept_and_bounded() {
1505        let mut f = Fixture::new();
1506        f.dpop.max_replay_entries = 4;
1507        let stale = Utc::now() - Duration::seconds(1);
1508        let live = Utc::now() + Duration::seconds(600);
1509        {
1510            let mut used = f.dpop.used_nonces.write().await;
1511            used.insert("stale-1".into(), stale);
1512            used.insert("stale-2".into(), stale);
1513            used.insert("live-1".into(), live);
1514            used.insert("live-2".into(), live);
1515        }
1516        // Two stale and two live records fill it: the stale ones are swept and the proof fits.
1517        f.present(&f.good("j-fits").build())
1518            .await
1519            .expect("a swept cache has room");
1520        {
1521            let used = f.dpop.used_nonces.read().await;
1522            assert!(
1523                !used.contains_key("stale-1") && !used.contains_key("stale-2"),
1524                "stale records survive a full cache"
1525            );
1526            assert_eq!(used.len(), 3);
1527        }
1528        // Filled with live records, a further proof is refused rather than recorded past the bound.
1529        f.dpop
1530            .used_nonces
1531            .write()
1532            .await
1533            .insert("live-3".into(), live);
1534        refused(
1535            f.present(&f.good("j-overflow").build()).await,
1536            "replay cache is full",
1537            "a full cache",
1538        );
1539    }
1540
1541    #[tokio::test]
1542    async fn one_key_cannot_spend_anothers_jti() {
1543        let f = Fixture::new();
1544        let other = ec_key();
1545        let mine = f.good("j-shared").build();
1546        let theirs = Proof {
1547            key: &other,
1548            ..f.good("j-shared")
1549        }
1550        .build();
1551        f.present(&mine).await.expect("first key");
1552        f.present(&theirs)
1553            .await
1554            .expect("a different key may use the same jti");
1555        refused(
1556            f.present(&mine).await,
1557            "already used",
1558            "the first key again",
1559        );
1560    }
1561
1562    #[tokio::test]
1563    async fn a_method_in_another_case_is_refused() {
1564        let f = Fixture::new();
1565        let p = f.good("j-case").build();
1566        refused(
1567            f.dpop
1568                .validate_dpop_proof(&p, "get", URI, Some(TOKEN), None)
1569                .await,
1570            "HTTP method",
1571            "lower-case method",
1572        );
1573    }
1574
1575    #[test]
1576    fn a_key_that_is_not_the_bound_key_is_an_error() {
1577        let f = Fixture::new();
1578        let other = ec_key();
1579        let bound = f.dpop.create_dpop_confirmation(&f.key.1).unwrap();
1580        assert!(f.dpop.validate_dpop_bound_token(&bound, &f.key.1).unwrap());
1581        assert!(
1582            f.dpop.validate_dpop_bound_token(&bound, &other.1).is_err(),
1583            "another key must be an error, not Ok(false)"
1584        );
1585    }
1586
1587    #[test]
1588    fn thumbprints_match_rfc_7638_and_an_independent_hash() {
1589        let f = Fixture::new();
1590        // RFC 7638 section 3.1.
1591        let rsa = json!({
1592            "kty": "RSA", "alg": "RS256", "kid": "2011-04-29", "e": "AQAB",
1593            "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw"
1594        });
1595        assert_eq!(
1596            f.dpop.calculate_jwk_thumbprint(&rsa).unwrap(),
1597            "NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs"
1598        );
1599        // SHA-256 of {"crv":"P-256","kty":"EC","x":...,"y":...}, computed with Python's hashlib.
1600        let ec = json!({
1601            "kty": "EC", "crv": "P-256", "use": "sig", "alg": "ES256",
1602            "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
1603            "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"
1604        });
1605        assert_eq!(
1606            f.dpop.calculate_jwk_thumbprint(&ec).unwrap(),
1607            "cn-I_WNMClehiVp51i_0VpOENW1upEerA8sEam5hn-s"
1608        );
1609        // A key without all its required members has no thumbprint.
1610        assert!(
1611            f.dpop
1612                .calculate_jwk_thumbprint(&json!({"kty": "EC", "crv": "P-256", "x": "AA"}))
1613                .is_err()
1614        );
1615    }
1616
1617    #[tokio::test]
1618    async fn an_iat_at_the_end_of_time_is_refused_not_a_panic() {
1619        let f = Fixture::new();
1620        // The largest timestamp chrono can represent, and one a minute short of it.
1621        for iat in [8_210_298_412_799_i64, 8_210_298_412_740] {
1622            let p = Proof {
1623                iat,
1624                ..f.good("j-forever")
1625            }
1626            .build();
1627            // Out of chrono's range counts as too old, in range but far ahead as in the future:
1628            // either way it is refused, and nothing panics on the way.
1629            refused(f.present(&p).await, "rejected", "iat at the end of time");
1630        }
1631    }
1632
1633    #[tokio::test]
1634    async fn a_jti_that_is_empty_or_too_long_is_refused() {
1635        let f = Fixture::new();
1636        let long = "a".repeat(257);
1637        for (jti, what) in [("", "empty jti"), (long.as_str(), "257-byte jti")] {
1638            let p = f.good(jti).build();
1639            refused(f.present(&p).await, "jti", what);
1640        }
1641        let ok = "a".repeat(256);
1642        f.present(&f.good(&ok).build())
1643            .await
1644            .expect("256 bytes is allowed");
1645    }
1646
1647    #[tokio::test]
1648    async fn replay_records_have_a_fixed_size() {
1649        let f = Fixture::new();
1650        let jti = "j".repeat(200);
1651        f.present(&f.good(&jti).build()).await.expect("a long jti");
1652        f.present(&f.good("short").build())
1653            .await
1654            .expect("a short jti");
1655        let used = f.dpop.used_nonces.read().await;
1656        assert_eq!(used.len(), 2);
1657        assert!(
1658            used.keys().all(|k| k.len() == 43),
1659            "record keys are not a fixed-size hash: {:?}",
1660            used.keys().map(String::len).collect::<Vec<_>>()
1661        );
1662    }
1663
1664    #[tokio::test]
1665    async fn a_full_cache_is_swept_at_most_once_per_interval() {
1666        let mut f = Fixture::new();
1667        f.dpop.max_replay_entries = 2;
1668        f.dpop.sweep_interval = Duration::hours(1);
1669        let stale = Utc::now() - Duration::seconds(1);
1670        {
1671            let mut used = f.dpop.used_nonces.write().await;
1672            used.insert("stale-1".into(), stale);
1673            used.insert("stale-2".into(), stale);
1674        }
1675        f.present(&f.good("j-first").build())
1676            .await
1677            .expect("the first full cache is swept");
1678        f.dpop
1679            .used_nonces
1680            .write()
1681            .await
1682            .insert("stale-3".into(), stale);
1683        // Full again, and the last sweep was moments ago: no new sweep, so the proof is refused.
1684        refused(
1685            f.present(&f.good("j-second").build()).await,
1686            "replay cache is full",
1687            "a cache swept a moment ago",
1688        );
1689    }
1690
1691    #[tokio::test]
1692    async fn a_proof_is_recorded_only_after_the_token_is_accepted() {
1693        let f = Fixture::new();
1694        let confirmation = f.dpop.create_dpop_confirmation(&f.key.1).unwrap();
1695        // An opaque token this function cannot validate: refused, and nothing recorded.
1696        let opaque = "opaque-token-1";
1697        let p = Proof {
1698            ath: Some(ath_of(opaque)),
1699            ..f.good("j-opaque")
1700        }
1701        .build();
1702        let r = f
1703            .dpop
1704            .validate_dpop_bound_access_token(opaque, &confirmation, &p, "GET", URI)
1705            .await;
1706        assert!(r.is_err(), "an opaque token was reported valid: {r:?}");
1707        assert_eq!(
1708            f.dpop.used_nonces.read().await.len(),
1709            0,
1710            "a proof was recorded although its token was refused"
1711        );
1712    }
1713
1714    #[test]
1715    fn an_rsa_jwk_with_a_leading_zero_octet_has_no_thumbprint() {
1716        let f = Fixture::new();
1717        // "AAEAAQ" is 00 01 00 01: the exponent 65537 with a leading zero.
1718        for jwk in [
1719            json!({"kty": "RSA", "n": "AQAB", "e": "AAEAAQ"}),
1720            json!({"kty": "RSA", "n": "AP8", "e": "AQAB"}),
1721        ] {
1722            assert!(f.dpop.calculate_jwk_thumbprint(&jwk).is_err(), "{jwk}");
1723        }
1724        assert!(
1725            f.dpop
1726                .calculate_jwk_thumbprint(&json!({"kty": "RSA", "n": "_w", "e": "AQAB"}))
1727                .is_ok()
1728        );
1729    }
1730
1731    #[tokio::test]
1732    async fn a_full_cache_of_expired_records_does_not_refuse_a_proof() {
1733        let mut f = Fixture::new();
1734        f.dpop.max_replay_entries = 2;
1735        f.dpop.sweep_interval = Duration::hours(1);
1736        // The first proof uses the sweep that has been due since the epoch.
1737        f.present(&f.good("j-warm").build()).await.expect("warm-up");
1738        // The cache is now full, one record of it expired, and the next sweep is an hour away.
1739        f.dpop
1740            .insert_record_for_test("expired-1", Utc::now() - Duration::seconds(5))
1741            .await;
1742        f.present(&f.good("j-after").build())
1743            .await
1744            .expect("room taken by an expired record must not refuse a proof");
1745        assert!(
1746            !f.dpop.used_nonces.read().await.contains_key("expired-1"),
1747            "the expired record was not swept"
1748        );
1749    }
1750
1751    /// The modulus and exponent (base64url, no leading zero) of an RSA key, read from its DER
1752    /// `RSAPublicKey`.
1753    fn rsa_parts(key: &rcgen::KeyPair) -> (String, String) {
1754        fn int(b: &[u8]) -> (&[u8], &[u8]) {
1755            assert_eq!(b[0], 0x02);
1756            let (len, off) = if b[1] & 0x80 == 0 {
1757                (b[1] as usize, 2)
1758            } else {
1759                let n = (b[1] & 0x7f) as usize;
1760                let len = b[2..2 + n]
1761                    .iter()
1762                    .fold(0usize, |a, &x| (a << 8) | x as usize);
1763                (len, 2 + n)
1764            };
1765            let v = &b[off..off + len];
1766            (v.strip_prefix(&[0]).unwrap_or(v), &b[off + len..])
1767        }
1768        let raw = key.public_key_raw();
1769        let body = if raw[1] & 0x80 == 0 {
1770            &raw[2..]
1771        } else {
1772            &raw[2 + (raw[1] & 0x7f) as usize..]
1773        };
1774        let (n, rest) = int(body);
1775        let (e, _) = int(rest);
1776        (URL_SAFE_NO_PAD.encode(n), URL_SAFE_NO_PAD.encode(e))
1777    }
1778
1779    #[tokio::test]
1780    async fn rs256_and_ps256_proofs_from_a_2048_bit_key_are_accepted() {
1781        let f = Fixture::new();
1782        let key =
1783            rcgen::KeyPair::generate_rsa_for(&rcgen::PKCS_RSA_SHA256, rcgen::RsaKeySize::_2048)
1784                .unwrap();
1785        let (n, e) = rsa_parts(&key);
1786        assert_eq!(URL_SAFE_NO_PAD.decode(&n).unwrap().len(), 256);
1787        let enc = EncodingKey::from_rsa_pem(key.serialize_pem().as_bytes()).unwrap();
1788        for (alg, name) in [(Algorithm::RS256, "RS256"), (Algorithm::PS256, "PS256")] {
1789            let header = json!({
1790                "typ": "dpop+jwt", "alg": name,
1791                "jwk": {"kty": "RSA", "n": n, "e": e},
1792            });
1793            let claims = |htm: &str| {
1794                json!({
1795                    "jti": format!("j-{name}-{htm}"), "htm": htm, "htu": URI,
1796                    "iat": f.now, "ath": ath_of(TOKEN),
1797                })
1798            };
1799            let b64 = |v: &serde_json::Value| URL_SAFE_NO_PAD.encode(v.to_string());
1800            let si = format!("{}.{}", b64(&header), b64(&claims("GET")));
1801            let sig = jsonwebtoken::crypto::sign(si.as_bytes(), &enc, alg).unwrap();
1802            f.present(&format!("{si}.{sig}"))
1803                .await
1804                .unwrap_or_else(|err| panic!("{name}: a correct proof was refused: {err:?}"));
1805
1806            // The same signature over different claims is refused.
1807            let forged = format!("{}.{}.{sig}", b64(&header), b64(&claims("POST")));
1808            let r = f
1809                .dpop
1810                .validate_dpop_proof(&forged, "POST", URI, Some(TOKEN), None)
1811                .await;
1812            refused(
1813                r,
1814                "signature",
1815                &format!("{name}: a signature over other claims"),
1816            );
1817        }
1818    }
1819}