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