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