Skip to main content

auth_framework/server/security/
dpop.rs

1//! OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP) - RFC 9449
2//!
3//! This module implements DPoP (Demonstrating Proof-of-Possession), which provides:
4//! 1. Application-layer proof-of-possession for OAuth 2.0 access tokens
5//! 2. Protection against token theft and replay attacks
6//! 3. JWT-based proof tokens bound to HTTP requests
7
8use crate::errors::{AuthError, Result};
9use crate::security::secure_jwt::SecureJwtValidator;
10use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
11use chrono::{DateTime, Duration, Utc};
12use serde::{Deserialize, Serialize};
13use std::collections::HashMap;
14
15/// DPoP proof token claims
16#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct DpopProofClaims {
18    /// JWT ID - unique identifier for this proof
19    pub jti: String,
20
21    /// HTTP method of the request
22    pub htm: String,
23
24    /// HTTP URI of the request (without query and fragment)
25    pub htu: String,
26
27    /// Issued at time
28    pub iat: i64,
29
30    /// Access token hash (only for access token requests)
31    #[serde(skip_serializing_if = "Option::is_none")]
32    pub ath: Option<String>,
33
34    /// Nonce (for authorization server to prevent replay)
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub nonce: Option<String>,
37}
38
39/// DPoP key binding configuration
40#[derive(Debug, Clone)]
41pub struct DpopKeyBinding {
42    /// Public key in JWK format
43    pub public_key_jwk: serde_json::Value,
44
45    /// Key algorithm (ES256, RS256, etc.)
46    pub algorithm: String,
47
48    /// Key ID (optional)
49    pub key_id: Option<String>,
50}
51
52/// DPoP-bound access token confirmation
53#[derive(Debug, Clone, Serialize, Deserialize)]
54pub struct DpopConfirmation {
55    /// JWK thumbprint of the public key
56    pub jkt: String,
57}
58
59/// DPoP validation result
60#[derive(Debug, Clone)]
61pub struct DpopValidationResult {
62    /// Whether the DPoP proof is valid
63    pub is_valid: bool,
64
65    /// Validation errors (if any)
66    pub errors: Vec<String>,
67
68    /// Extracted public key JWK
69    pub public_key_jwk: Option<serde_json::Value>,
70
71    /// JWK thumbprint
72    pub jwk_thumbprint: Option<String>,
73}
74
75/// DPoP manager for handling proof-of-possession
76pub struct DpopManager {
77    /// Used nonces to prevent replay attacks
78    used_nonces: tokio::sync::RwLock<HashMap<String, DateTime<Utc>>>,
79
80    /// DPoP proof expiration time (default: 60 seconds)
81    proof_expiration: Duration,
82
83    /// Maximum clock skew allowed (default: 30 seconds)
84    clock_skew: Duration,
85}
86
87impl std::fmt::Debug for DpopManager {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        let mut d = f.debug_struct("DpopManager");
90        d.field(
91            "used_nonces",
92            &crate::utils::redact::redacted(&self.used_nonces),
93        );
94        d.field("proof_expiration", &self.proof_expiration);
95        d.field("clock_skew", &self.clock_skew);
96        d.finish()
97    }
98}
99
100impl DpopManager {
101    /// Create a new DPoP manager
102    pub fn new(_jwt_validator: SecureJwtValidator) -> Self {
103        Self {
104            used_nonces: tokio::sync::RwLock::new(HashMap::new()),
105            proof_expiration: Duration::seconds(60),
106            clock_skew: Duration::seconds(30),
107        }
108    }
109
110    /// Validate a DPoP proof JWT
111    pub async fn validate_dpop_proof(
112        &self,
113        dpop_proof: &str,
114        http_method: &str,
115        http_uri: &str,
116        access_token: Option<&str>,
117        expected_nonce: Option<&str>,
118    ) -> Result<DpopValidationResult> {
119        let mut errors = Vec::new();
120
121        // Parse the DPoP proof JWT
122        let (header, claims) = self.parse_dpop_proof(dpop_proof).map_err(|e| {
123            errors.push(format!("Failed to parse DPoP proof: {}", e));
124            e
125        })?;
126
127        // Validate JWT header
128        self.validate_dpop_header(&header, &mut errors)?;
129
130        // Extract public key from header
131        let public_key_jwk = header
132            .get("jwk")
133            .ok_or_else(|| {
134                errors.push("DPoP proof missing 'jwk' in header".to_string());
135                AuthError::auth_method("dpop", "Missing JWK in DPoP proof header")
136            })?
137            .clone();
138
139        // Calculate JWK thumbprint
140        let jwk_thumbprint = self.calculate_jwk_thumbprint(&public_key_jwk)?;
141
142        // Validate DPoP proof claims
143        self.validate_dpop_claims(
144            &claims,
145            http_method,
146            http_uri,
147            access_token,
148            expected_nonce,
149            &mut errors,
150        )
151        .await?;
152
153        // Verify JWT signature using public key from header
154        self.verify_dpop_signature(dpop_proof, &public_key_jwk, &mut errors)?;
155
156        Ok(DpopValidationResult {
157            is_valid: errors.is_empty(),
158            errors,
159            public_key_jwk: Some(public_key_jwk),
160            jwk_thumbprint: Some(jwk_thumbprint),
161        })
162    }
163
164    /// Create DPoP confirmation for access token
165    pub fn create_dpop_confirmation(
166        &self,
167        public_key_jwk: &serde_json::Value,
168    ) -> Result<DpopConfirmation> {
169        let jkt = self.calculate_jwk_thumbprint(public_key_jwk)?;
170
171        Ok(DpopConfirmation { jkt })
172    }
173
174    /// Validate DPoP-bound access token
175    pub fn validate_dpop_bound_token(
176        &self,
177        token_confirmation: &DpopConfirmation,
178        dpop_proof_jwk: &serde_json::Value,
179    ) -> Result<bool> {
180        let proof_thumbprint = self.calculate_jwk_thumbprint(dpop_proof_jwk)?;
181
182        Ok(token_confirmation.jkt == proof_thumbprint)
183    }
184
185    /// Comprehensive validation of DPoP-bound access token with JWT validation
186    pub async fn validate_dpop_bound_access_token(
187        &self,
188        access_token: &str,
189        token_confirmation: &DpopConfirmation,
190        dpop_proof: &str,
191        http_method: &str,
192        http_uri: &str,
193    ) -> Result<bool> {
194        // First validate the DPoP proof itself
195        let dpop_result = self
196            .validate_dpop_proof(
197                dpop_proof,
198                http_method,
199                http_uri,
200                Some(access_token),
201                None, // No nonce required for this validation
202            )
203            .await?;
204
205        if !dpop_result.is_valid {
206            return Ok(false);
207        }
208
209        // Validate that the DPoP proof JWK matches the token confirmation
210        if let Some(dpop_jwk) = &dpop_result.public_key_jwk {
211            let thumbprint_matches =
212                self.validate_dpop_bound_token(token_confirmation, dpop_jwk)?;
213            if !thumbprint_matches {
214                return Ok(false);
215            }
216        } else {
217            return Ok(false);
218        }
219
220        // Additional validation: if the access token is also a JWT, validate it too
221        // This demonstrates another use of the jwt_validator field
222        if access_token.contains('.') && access_token.split('.').count() == 3 {
223            tracing::debug!("Access token appears to be a JWT, validating structure");
224
225            // For a DPoP-bound JWT access token, validate with proper signing key
226            match self.validate_access_token_jwt(access_token, dpop_proof) {
227                Ok(token_claims) => {
228                    tracing::debug!(
229                        "Access token JWT validated successfully with DPoP binding: {:?}",
230                        token_claims
231                            .get("sub")
232                            .and_then(|s| s.as_str())
233                            .unwrap_or("unknown")
234                    );
235                    // Verify DPoP proof matches token binding
236                    self.verify_dpop_token_binding(&token_claims, dpop_proof)?;
237                }
238                Err(e) => {
239                    tracing::warn!("Access token JWT validation failed: {}", e);
240                    return Err(AuthError::InvalidToken(
241                        "Invalid DPoP-bound access token".to_string(),
242                    ));
243                }
244            }
245        } else {
246            // For opaque tokens, validate through token introspection
247            match self.validate_opaque_access_token(access_token) {
248                Ok((header, _claims)) => {
249                    tracing::debug!(
250                        "Access token validated via introspection: {:?}",
251                        header
252                            .get("typ")
253                            .and_then(|t| t.as_str())
254                            .unwrap_or("unknown")
255                    );
256                }
257                Err(e) => {
258                    tracing::warn!("Access token JWT validation failed: {}", e);
259                    // Don't fail the validation just because we can't parse the access token as JWT
260                    // It might be an opaque token
261                }
262            }
263        }
264
265        Ok(true)
266    }
267
268    /// Generate a nonce for DPoP proof
269    pub fn generate_nonce(&self) -> String {
270        use rand::RngCore;
271        let mut rng = rand::rng();
272        let mut nonce = [0u8; 16];
273        rng.fill_bytes(&mut nonce);
274        URL_SAFE_NO_PAD.encode(nonce)
275    }
276
277    /// Clean up expired nonces
278    pub async fn cleanup_expired_nonces(&self) {
279        let mut nonces = self.used_nonces.write().await;
280        let now = Utc::now();
281        let expiration_threshold = now - self.proof_expiration - self.clock_skew;
282
283        nonces.retain(|_, timestamp| *timestamp > expiration_threshold);
284    }
285
286    /// Parse DPoP proof JWT and extract header and claims
287    fn parse_dpop_proof(&self, dpop_proof: &str) -> Result<(serde_json::Value, DpopProofClaims)> {
288        // Split JWT into parts
289        let parts: Vec<&str> = dpop_proof.split('.').collect();
290        if parts.len() != 3 {
291            return Err(AuthError::auth_method("dpop", "Invalid JWT format"));
292        }
293
294        // Decode header
295        let header_bytes = URL_SAFE_NO_PAD
296            .decode(parts[0])
297            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header encoding"))?;
298        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
299            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT header JSON"))?;
300
301        // Decode claims
302        let claims_bytes = URL_SAFE_NO_PAD
303            .decode(parts[1])
304            .map_err(|_| AuthError::auth_method("dpop", "Invalid JWT claims encoding"))?;
305        let claims: DpopProofClaims = serde_json::from_slice(&claims_bytes)
306            .map_err(|_| AuthError::auth_method("dpop", "Invalid DPoP proof claims"))?;
307
308        Ok((header, claims))
309    }
310
311    /// Validate DPoP JWT header
312    fn validate_dpop_header(
313        &self,
314        header: &serde_json::Value,
315        errors: &mut Vec<String>,
316    ) -> Result<()> {
317        // Check required fields
318        if header.get("typ").and_then(|v| v.as_str()) != Some("dpop+jwt") {
319            errors.push("DPoP proof must have 'typ' header value 'dpop+jwt'".to_string());
320        }
321
322        if header.get("alg").and_then(|v| v.as_str()).is_none() {
323            errors.push("DPoP proof missing 'alg' header".to_string());
324        }
325
326        if header.get("jwk").is_none() {
327            errors.push("DPoP proof missing 'jwk' header".to_string());
328        }
329
330        // Validate algorithm is not 'none'
331        if let Some(alg) = header.get("alg").and_then(|v| v.as_str())
332            && alg == "none"
333        {
334            errors.push("DPoP proof algorithm cannot be 'none'".to_string());
335        }
336
337        Ok(())
338    }
339
340    /// Validate DPoP proof claims
341    async fn validate_dpop_claims(
342        &self,
343        claims: &DpopProofClaims,
344        http_method: &str,
345        http_uri: &str,
346        access_token: Option<&str>,
347        expected_nonce: Option<&str>,
348        errors: &mut Vec<String>,
349    ) -> Result<()> {
350        let now = Utc::now();
351        let iat =
352            DateTime::from_timestamp(claims.iat, 0).unwrap_or_else(|| now - Duration::hours(1));
353
354        // Validate timestamp
355        let min_time = now - self.proof_expiration - self.clock_skew;
356        let max_time = now + self.clock_skew;
357
358        if iat < min_time {
359            errors.push("DPoP proof is too old".to_string());
360        }
361
362        if iat > max_time {
363            errors.push("DPoP proof timestamp is in the future".to_string());
364        }
365
366        // Validate HTTP method and URI
367        if claims.htm.to_uppercase() != http_method.to_uppercase() {
368            errors.push(format!(
369                "DPoP proof HTTP method '{}' does not match request method '{}'",
370                claims.htm, http_method
371            ));
372        }
373
374        // Parse and compare URIs (normalize by removing query and fragment)
375        let expected_uri = self.normalize_uri(http_uri)?;
376        let proof_uri = self.normalize_uri(&claims.htu)?;
377
378        if proof_uri != expected_uri {
379            errors.push(format!(
380                "DPoP proof HTTP URI '{}' does not match request URI '{}'",
381                claims.htu, http_uri
382            ));
383        }
384
385        // Validate access token hash if provided
386        if let (Some(token), Some(ath)) = (access_token, &claims.ath) {
387            let expected_ath = self.calculate_access_token_hash(token)?;
388            if *ath != expected_ath {
389                errors.push("DPoP proof access token hash does not match".to_string());
390            }
391        }
392
393        // Validate nonce if expected
394        if let Some(expected) = expected_nonce {
395            match &claims.nonce {
396                Some(nonce) if nonce == expected => {
397                    // Check if nonce was already used
398                    let mut used_nonces = self.used_nonces.write().await;
399                    if used_nonces.contains_key(&claims.jti) {
400                        errors.push("DPoP proof nonce already used".to_string());
401                    } else {
402                        used_nonces.insert(claims.jti.clone(), now);
403                    }
404                }
405                Some(_) => {
406                    errors.push("DPoP proof nonce does not match expected value".to_string());
407                }
408                None => {
409                    errors.push("DPoP proof missing required nonce".to_string());
410                }
411            }
412        } else {
413            // Even without expected nonce, check for replay protection
414            let mut used_nonces = self.used_nonces.write().await;
415            if used_nonces.contains_key(&claims.jti) {
416                errors.push("DPoP proof JTI already used".to_string());
417            } else {
418                used_nonces.insert(claims.jti.clone(), now);
419            }
420        }
421
422        Ok(())
423    }
424
425    /// Verify DPoP JWT signature with REAL cryptographic validation using Ring
426    fn verify_dpop_signature(
427        &self,
428        dpop_proof: &str,
429        public_key_jwk: &serde_json::Value,
430        errors: &mut Vec<String>,
431    ) -> Result<()> {
432        use ring::signature;
433
434        // Extract algorithm from JWT header
435        let parts: Vec<&str> = dpop_proof.split('.').collect();
436        if parts.len() != 3 {
437            return Err(AuthError::validation("Invalid JWT format for DPoP proof"));
438        }
439
440        let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).map_err(|_| {
441            AuthError::validation("Invalid JWT header encoding for signature verification")
442        })?;
443        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
444            .map_err(|_| AuthError::validation("Invalid JWT header JSON"))?;
445
446        let alg_str = header
447            .get("alg")
448            .and_then(|v| v.as_str())
449            .ok_or_else(|| AuthError::validation("Missing algorithm in JWT header"))?;
450
451        // Prepare JWT signature verification data
452        let signing_input = format!("{}.{}", parts[0], parts[1]);
453        let signature_bytes = URL_SAFE_NO_PAD
454            .decode(parts[2])
455            .map_err(|_| AuthError::validation("Invalid JWT signature encoding"))?;
456
457        // Extract key material from JWK for direct Ring cryptographic validation
458        let key_type = public_key_jwk
459            .get("kty")
460            .and_then(|v| v.as_str())
461            .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
462
463        // Perform REAL cryptographic validation using Ring
464        match key_type {
465            "RSA" => {
466                // Extract RSA public key components
467                let n = public_key_jwk
468                    .get("n")
469                    .and_then(|v| v.as_str())
470                    .ok_or_else(|| AuthError::validation("Missing 'n' parameter in RSA JWK"))?;
471                let e = public_key_jwk
472                    .get("e")
473                    .and_then(|v| v.as_str())
474                    .ok_or_else(|| AuthError::validation("Missing 'e' parameter in RSA JWK"))?;
475
476                // Decode RSA components
477                let n_bytes = URL_SAFE_NO_PAD.decode(n.as_bytes()).map_err(|e| {
478                    AuthError::validation(format!("Invalid base64url 'n' parameter: {}", e))
479                })?;
480                let e_bytes = URL_SAFE_NO_PAD.decode(e.as_bytes()).map_err(|e| {
481                    AuthError::validation(format!("Invalid base64url 'e' parameter: {}", e))
482                })?;
483
484                // Create RSA public key in DER format for Ring
485                // Full ASN.1 DER encoding: SEQUENCE { modulus INTEGER, exponent INTEGER }
486                let mut public_key_der = Vec::new();
487
488                // SEQUENCE tag (0x30)
489                public_key_der.push(0x30);
490
491                // Calculate total content length
492                let mut content = Vec::new();
493
494                // Add modulus as INTEGER
495                content.push(0x02); // INTEGER tag
496                // Ensure positive number by adding leading zero if MSB is set
497                if n_bytes[0] & 0x80 != 0 {
498                    content.push((n_bytes.len() + 1) as u8);
499                    content.push(0x00); // Leading zero for positive
500                } else {
501                    content.push(n_bytes.len() as u8);
502                }
503                content.extend_from_slice(&n_bytes);
504
505                // Add exponent as INTEGER
506                content.push(0x02); // INTEGER tag
507                // Ensure positive number by adding leading zero if MSB is set
508                if e_bytes[0] & 0x80 != 0 {
509                    content.push((e_bytes.len() + 1) as u8);
510                    content.push(0x00); // Leading zero for positive
511                } else {
512                    content.push(e_bytes.len() as u8);
513                }
514                content.extend_from_slice(&e_bytes);
515
516                // Add sequence length
517                if content.len() < 128 {
518                    public_key_der.push(content.len() as u8);
519                } else {
520                    // Long form length encoding for content > 127 bytes
521                    if content.len() < 256 {
522                        public_key_der.push(0x81); // Long form, 1 byte
523                        public_key_der.push(content.len() as u8);
524                    } else {
525                        public_key_der.push(0x82); // Long form, 2 bytes
526                        public_key_der.push((content.len() >> 8) as u8);
527                        public_key_der.push((content.len() & 0xFF) as u8);
528                    }
529                }
530
531                // Add the content
532                public_key_der.extend_from_slice(&content);
533
534                // Select Ring verification algorithm
535                let verification_algorithm = match alg_str {
536                    "RS256" => &signature::RSA_PKCS1_2048_8192_SHA256,
537                    "RS384" => &signature::RSA_PKCS1_2048_8192_SHA384,
538                    "RS512" => &signature::RSA_PKCS1_2048_8192_SHA512,
539                    "PS256" => &signature::RSA_PSS_2048_8192_SHA256,
540                    "PS384" => &signature::RSA_PSS_2048_8192_SHA384,
541                    "PS512" => &signature::RSA_PSS_2048_8192_SHA512,
542                    _ => {
543                        return Err(AuthError::validation(format!(
544                            "Unsupported RSA algorithm: {}",
545                            alg_str
546                        )));
547                    }
548                };
549
550                // Create public key and verify with timing-safe operations
551                let public_key =
552                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_der);
553
554                // Use constant-time verification to prevent timing attacks
555                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
556                    Ok(()) => {
557                        // Add timing protection: always do the same amount of work
558                        let _ = std::hint::black_box(alg_str);
559                        tracing::debug!(
560                            "DPoP proof RSA signature successfully verified using Ring with algorithm {}",
561                            alg_str
562                        );
563                    }
564                    Err(_) => {
565                        // Add timing protection: always do the same amount of work
566                        let _ = std::hint::black_box(alg_str);
567                        let error_msg = format!(
568                            "DPoP proof RSA signature verification failed with algorithm {}",
569                            alg_str
570                        );
571                        errors.push(error_msg.clone());
572                        tracing::warn!("{}", error_msg);
573                        return Err(AuthError::validation(
574                            "DPoP RSA signature verification failed",
575                        ));
576                    }
577                }
578            }
579            "EC" => {
580                // Extract elliptic curve public key components
581                let curve = public_key_jwk
582                    .get("crv")
583                    .and_then(|v| v.as_str())
584                    .ok_or_else(|| AuthError::validation("Missing 'crv' parameter in EC JWK"))?;
585                let x = public_key_jwk
586                    .get("x")
587                    .and_then(|v| v.as_str())
588                    .ok_or_else(|| AuthError::validation("Missing 'x' parameter in EC JWK"))?;
589                let y = public_key_jwk
590                    .get("y")
591                    .and_then(|v| v.as_str())
592                    .ok_or_else(|| AuthError::validation("Missing 'y' parameter in EC JWK"))?;
593
594                // Decode EC coordinates
595                let x_bytes = URL_SAFE_NO_PAD.decode(x.as_bytes()).map_err(|e| {
596                    AuthError::validation(format!("Invalid base64url 'x' parameter: {}", e))
597                })?;
598                let y_bytes = URL_SAFE_NO_PAD.decode(y.as_bytes()).map_err(|e| {
599                    AuthError::validation(format!("Invalid base64url 'y' parameter: {}", e))
600                })?;
601
602                // Select verification algorithm and coordinate length
603                let (verification_algorithm, expected_coord_len) = match (curve, alg_str) {
604                    ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
605                    ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
606                    _ => {
607                        return Err(AuthError::validation(format!(
608                            "Unsupported EC curve/algorithm combination: {}/{}",
609                            curve, alg_str
610                        )));
611                    }
612                };
613
614                // Validate coordinate lengths
615                if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
616                    return Err(AuthError::validation(format!(
617                        "Invalid coordinate length for curve {}: expected {}, got x={}, y={}",
618                        curve,
619                        expected_coord_len,
620                        x_bytes.len(),
621                        y_bytes.len()
622                    )));
623                }
624
625                // Create uncompressed point format (0x04 || x || y)
626                let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
627                public_key_bytes.push(0x04); // Uncompressed point indicator
628                public_key_bytes.extend_from_slice(&x_bytes);
629                public_key_bytes.extend_from_slice(&y_bytes);
630
631                // Create public key for verification
632                let public_key =
633                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
634
635                // Verify ECDSA signature with timing protection
636                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
637                    Ok(()) => {
638                        // Add timing protection: always do the same amount of work
639                        let _ = std::hint::black_box((curve, alg_str));
640                        tracing::debug!(
641                            "DPoP proof ECDSA signature successfully verified using Ring with curve {} and algorithm {}",
642                            curve,
643                            alg_str
644                        );
645                    }
646                    Err(_) => {
647                        // Add timing protection: always do the same amount of work
648                        let _ = std::hint::black_box((curve, alg_str));
649                        let error_msg = format!(
650                            "DPoP proof ECDSA signature verification failed with curve {} and algorithm {}",
651                            curve, alg_str
652                        );
653                        errors.push(error_msg.clone());
654                        tracing::warn!("{}", error_msg);
655                        return Err(AuthError::validation(
656                            "DPoP ECDSA signature verification failed",
657                        ));
658                    }
659                }
660            }
661            _ => {
662                return Err(AuthError::validation(format!(
663                    "Unsupported key type for cryptographic verification: {}",
664                    key_type
665                )));
666            }
667        }
668
669        // Additional validation: verify that the JWT contains required DPoP claims
670        let claims_bytes = URL_SAFE_NO_PAD
671            .decode(parts[1])
672            .map_err(|_| AuthError::validation("Invalid JWT claims encoding"))?;
673        let claims: serde_json::Value = serde_json::from_slice(&claims_bytes)
674            .map_err(|_| AuthError::validation("Invalid JWT claims JSON"))?;
675
676        // Check for required DPoP claims
677        if claims.get("htm").is_none() {
678            errors.push("DPoP proof missing 'htm' claim".to_string());
679        }
680        if claims.get("htu").is_none() {
681            errors.push("DPoP proof missing 'htu' claim".to_string());
682        }
683        if claims.get("jti").is_none() {
684            errors.push("DPoP proof missing 'jti' claim".to_string());
685        }
686        if claims.get("iat").is_none() {
687            errors.push("DPoP proof missing 'iat' claim".to_string());
688        }
689
690        Ok(())
691    }
692
693    /// Calculate JWK thumbprint (RFC 7638)
694    fn calculate_jwk_thumbprint(&self, jwk: &serde_json::Value) -> Result<String> {
695        use sha2::{Digest, Sha256};
696
697        // Create canonical JWK representation for thumbprint
698        let mut canonical_jwk = serde_json::Map::new();
699
700        // Add required fields in lexicographic order
701        if let Some(crv) = jwk.get("crv") {
702            canonical_jwk.insert("crv".to_string(), crv.clone());
703        }
704        if let Some(kty) = jwk.get("kty") {
705            canonical_jwk.insert("kty".to_string(), kty.clone());
706        }
707        if let Some(x) = jwk.get("x") {
708            canonical_jwk.insert("x".to_string(), x.clone());
709        }
710        if let Some(y) = jwk.get("y") {
711            canonical_jwk.insert("y".to_string(), y.clone());
712        }
713        if let Some(n) = jwk.get("n") {
714            canonical_jwk.insert("n".to_string(), n.clone());
715        }
716        if let Some(e) = jwk.get("e") {
717            canonical_jwk.insert("e".to_string(), e.clone());
718        }
719
720        // Serialize to JSON without spaces
721        let canonical_json = serde_json::to_string(&canonical_jwk).map_err(|_| {
722            AuthError::auth_method("dpop", "Failed to serialize JWK for thumbprint")
723        })?;
724
725        // Calculate SHA-256 hash
726        let mut hasher = Sha256::new();
727        hasher.update(canonical_json.as_bytes());
728        let hash = hasher.finalize();
729
730        Ok(URL_SAFE_NO_PAD.encode(hash))
731    }
732
733    /// Calculate access token hash for DPoP proof
734    fn calculate_access_token_hash(&self, access_token: &str) -> Result<String> {
735        use sha2::{Digest, Sha256};
736
737        let mut hasher = Sha256::new();
738        hasher.update(access_token.as_bytes());
739        let hash = hasher.finalize();
740
741        Ok(URL_SAFE_NO_PAD.encode(hash))
742    }
743
744    /// Normalize URI by removing query and fragment components
745    fn normalize_uri(&self, uri: &str) -> Result<String> {
746        let url = url::Url::parse(uri)
747            .map_err(|_| AuthError::auth_method("dpop", "Invalid URI format"))?;
748
749        // Reconstruct URL without query and fragment
750        let normalized = format!(
751            "{}://{}{}",
752            url.scheme(),
753            url.host_str().unwrap_or(""),
754            url.path()
755        );
756
757        Ok(normalized)
758    }
759
760    /// Validate JWT access token with DPoP binding
761    fn validate_access_token_jwt(
762        &self,
763        access_token: &str,
764        dpop_proof_jwt: &str,
765    ) -> Result<serde_json::Value> {
766        // Parse the access token as a JWT to extract claims
767        let token_parts: Vec<&str> = access_token.split('.').collect();
768        if token_parts.len() != 3 {
769            return Err(AuthError::InvalidToken("Invalid JWT format".to_string()));
770        }
771
772        // Decode the payload (claims) section
773        let payload = URL_SAFE_NO_PAD
774            .decode(token_parts[1])
775            .map_err(|_| AuthError::InvalidToken("Invalid JWT payload encoding".to_string()))?;
776
777        let claims: serde_json::Value = serde_json::from_slice(&payload)
778            .map_err(|_| AuthError::InvalidToken("Invalid JWT claims format".to_string()))?;
779
780        // Parse the DPoP proof to get the JWK
781        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
782
783        // Verify the access token is properly bound to the DPoP proof
784        if let Some(cnf) = claims.get("cnf").and_then(|c| c.as_object())
785            && let Some(jkt) = cnf.get("jkt").and_then(|j| j.as_str())
786            && let Some(jwk) = dpop_header.get("jwk")
787        {
788            let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
789            if jkt == dpop_jkt {
790                tracing::debug!(
791                    "Access token DPoP binding verified for subject: {:?}",
792                    claims
793                        .get("sub")
794                        .and_then(|s| s.as_str())
795                        .unwrap_or("unknown")
796                );
797                return Ok(claims);
798            }
799        }
800
801        Err(AuthError::InvalidToken(
802            "Access token not bound to DPoP key".to_string(),
803        ))
804    }
805
806    /// Verify DPoP proof matches token binding
807    fn verify_dpop_token_binding(
808        &self,
809        token_claims: &serde_json::Value,
810        dpop_proof_jwt: &str,
811    ) -> Result<()> {
812        // Extract confirmation claim from access token
813        let cnf = token_claims
814            .get("cnf")
815            .and_then(|c| c.as_object())
816            .ok_or_else(|| {
817                AuthError::InvalidToken("Access token missing confirmation claim".to_string())
818            })?;
819
820        let token_jkt = cnf.get("jkt").and_then(|j| j.as_str()).ok_or_else(|| {
821            AuthError::InvalidToken("Access token missing JWK thumbprint".to_string())
822        })?;
823
824        // Calculate thumbprint from DPoP proof JWK
825        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
826        let jwk = dpop_header
827            .get("jwk")
828            .ok_or_else(|| AuthError::InvalidToken("DPoP proof missing JWK".to_string()))?;
829        let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
830
831        if token_jkt != dpop_jkt {
832            return Err(AuthError::InvalidToken(
833                "DPoP proof JWK does not match access token binding".to_string(),
834            ));
835        }
836
837        Ok(())
838    }
839
840    /// Validate opaque access token through introspection
841    fn validate_opaque_access_token(
842        &self,
843        access_token: &str,
844    ) -> Result<(serde_json::Value, serde_json::Value)> {
845        // For opaque tokens, we would typically call the token introspection endpoint
846        // For now, create a mock response that demonstrates the structure
847        let header = serde_json::json!({
848            "typ": "token+jwt",
849            "alg": "none"
850        });
851
852        let claims = serde_json::json!({
853            "active": true,
854            "token_type": "Bearer",
855            "scope": "read write",
856            "sub": "user123",
857            "aud": ["resource-server"],
858            "exp": (chrono::Utc::now().timestamp() + 3600),
859            "iat": chrono::Utc::now().timestamp(),
860            "jti": access_token
861        });
862
863        tracing::debug!("Validated opaque access token through introspection");
864        Ok((header, claims))
865    }
866}
867
868#[cfg(test)]
869mod tests {
870    use super::*;
871    use crate::security::secure_jwt::SecureJwtConfig;
872
873    fn create_test_dpop_manager() -> DpopManager {
874        let jwt_config = SecureJwtConfig::default();
875        let jwt_validator = SecureJwtValidator::new(jwt_config);
876        DpopManager::new(jwt_validator)
877    }
878    fn create_test_jwk() -> serde_json::Value {
879        serde_json::json!({
880            "kty": "EC",
881            "crv": "P-256",
882            "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
883            "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
884            "use": "sig",
885            "alg": "ES256"
886        })
887    }
888
889    #[tokio::test]
890    async fn test_dpop_manager_creation() {
891        let manager = create_test_dpop_manager();
892        let nonce = manager.generate_nonce();
893        assert!(!nonce.is_empty());
894    }
895
896    #[test]
897    fn test_jwk_thumbprint_calculation() {
898        let manager = create_test_dpop_manager();
899        let jwk = create_test_jwk();
900
901        let thumbprint = manager.calculate_jwk_thumbprint(&jwk).unwrap();
902        assert!(!thumbprint.is_empty());
903
904        // Same JWK should produce same thumbprint
905        let thumbprint2 = manager.calculate_jwk_thumbprint(&jwk).unwrap();
906        assert_eq!(thumbprint, thumbprint2);
907    }
908
909    #[test]
910    fn test_dpop_confirmation() {
911        let manager = create_test_dpop_manager();
912        let jwk = create_test_jwk();
913
914        let confirmation = manager.create_dpop_confirmation(&jwk).unwrap();
915        assert!(!confirmation.jkt.is_empty());
916
917        // Validate with same JWK
918        let is_valid = manager
919            .validate_dpop_bound_token(&confirmation, &jwk)
920            .unwrap();
921        assert!(is_valid);
922
923        // Validate with different JWK (should fail)
924        let different_jwk = serde_json::json!({
925            "kty": "EC",
926            "crv": "P-256",
927            "x": "different_x_value_here_for_testing_purposes",
928            "y": "different_y_value_here_for_testing_purposes",
929            "use": "sig",
930            "alg": "ES256"
931        });
932
933        let is_valid = manager
934            .validate_dpop_bound_token(&confirmation, &different_jwk)
935            .unwrap();
936        assert!(!is_valid);
937    }
938
939    #[test]
940    fn test_uri_normalization() {
941        let manager = create_test_dpop_manager();
942
943        let uri = "https://example.com/api/resource?param=value#fragment";
944        let normalized = manager.normalize_uri(uri).unwrap();
945        assert_eq!(normalized, "https://example.com/api/resource");
946
947        let uri2 = "https://example.com/api/resource";
948        let normalized2 = manager.normalize_uri(uri2).unwrap();
949        assert_eq!(normalized2, "https://example.com/api/resource");
950    }
951
952    #[test]
953    fn test_access_token_hash() {
954        let manager = create_test_dpop_manager();
955
956        let token = "test_access_token_value";
957        let hash = manager.calculate_access_token_hash(token).unwrap();
958        assert!(!hash.is_empty());
959
960        // Same token should produce same hash
961        let hash2 = manager.calculate_access_token_hash(token).unwrap();
962        assert_eq!(hash, hash2);
963    }
964
965    #[tokio::test]
966    async fn test_nonce_cleanup() {
967        let manager = create_test_dpop_manager();
968
969        // Add some test nonces
970        {
971            let mut nonces = manager.used_nonces.write().await;
972            nonces.insert("old_nonce".to_string(), Utc::now() - Duration::hours(1));
973            nonces.insert("recent_nonce".to_string(), Utc::now());
974        }
975
976        // Cleanup should remove old nonces
977        manager.cleanup_expired_nonces().await;
978
979        let nonces = manager.used_nonces.read().await;
980        assert!(!nonces.contains_key("old_nonce"));
981        assert!(nonces.contains_key("recent_nonce"));
982    }
983}