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/// 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::token(
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::Rng;
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 = Utc
352            .timestamp_opt(claims.iat, 0)
353            .single()
354            .unwrap_or_else(|| now - Duration::hours(1));
355
356        // Validate timestamp
357        let min_time = now - self.proof_expiration - self.clock_skew;
358        let max_time = now + self.clock_skew;
359
360        if iat < min_time {
361            errors.push("DPoP proof is too old".to_string());
362        }
363
364        if iat > max_time {
365            errors.push("DPoP proof timestamp is in the future".to_string());
366        }
367
368        // Validate HTTP method and URI
369        if claims.htm.to_uppercase() != http_method.to_uppercase() {
370            errors.push(format!(
371                "DPoP proof HTTP method '{}' does not match request method '{}'",
372                claims.htm, http_method
373            ));
374        }
375
376        // Parse and compare URIs (normalize by removing query and fragment)
377        let expected_uri = self.normalize_uri(http_uri)?;
378        let proof_uri = self.normalize_uri(&claims.htu)?;
379
380        if proof_uri != expected_uri {
381            errors.push(format!(
382                "DPoP proof HTTP URI '{}' does not match request URI '{}'",
383                claims.htu, http_uri
384            ));
385        }
386
387        // Validate access token hash if provided
388        if let (Some(token), Some(ath)) = (access_token, &claims.ath) {
389            let expected_ath = self.calculate_access_token_hash(token)?;
390            if *ath != expected_ath {
391                errors.push("DPoP proof access token hash does not match".to_string());
392            }
393        }
394
395        // Validate nonce if expected
396        if let Some(expected) = expected_nonce {
397            match &claims.nonce {
398                Some(nonce) if nonce == expected => {
399                    // Check if nonce was already used
400                    let mut used_nonces = self.used_nonces.write().await;
401                    if used_nonces.contains_key(&claims.jti) {
402                        errors.push("DPoP proof nonce already used".to_string());
403                    } else {
404                        used_nonces.insert(claims.jti.clone(), now);
405                    }
406                }
407                Some(_) => {
408                    errors.push("DPoP proof nonce does not match expected value".to_string());
409                }
410                None => {
411                    errors.push("DPoP proof missing required nonce".to_string());
412                }
413            }
414        } else {
415            // Even without expected nonce, check for replay protection
416            let mut used_nonces = self.used_nonces.write().await;
417            if used_nonces.contains_key(&claims.jti) {
418                errors.push("DPoP proof JTI already used".to_string());
419            } else {
420                used_nonces.insert(claims.jti.clone(), now);
421            }
422        }
423
424        Ok(())
425    }
426
427    /// Verify DPoP JWT signature with REAL cryptographic validation using Ring
428    fn verify_dpop_signature(
429        &self,
430        dpop_proof: &str,
431        public_key_jwk: &serde_json::Value,
432        errors: &mut Vec<String>,
433    ) -> Result<()> {
434        use ring::signature;
435
436        // Extract algorithm from JWT header
437        let parts: Vec<&str> = dpop_proof.split('.').collect();
438        if parts.len() != 3 {
439            return Err(AuthError::validation("Invalid JWT format for DPoP proof"));
440        }
441
442        let header_bytes = URL_SAFE_NO_PAD.decode(parts[0]).map_err(|_| {
443            AuthError::validation("Invalid JWT header encoding for signature verification")
444        })?;
445        let header: serde_json::Value = serde_json::from_slice(&header_bytes)
446            .map_err(|_| AuthError::validation("Invalid JWT header JSON"))?;
447
448        let alg_str = header
449            .get("alg")
450            .and_then(|v| v.as_str())
451            .ok_or_else(|| AuthError::validation("Missing algorithm in JWT header"))?;
452
453        // Prepare JWT signature verification data
454        let signing_input = format!("{}.{}", parts[0], parts[1]);
455        let signature_bytes = URL_SAFE_NO_PAD
456            .decode(parts[2])
457            .map_err(|_| AuthError::validation("Invalid JWT signature encoding"))?;
458
459        // Extract key material from JWK for direct Ring cryptographic validation
460        let key_type = public_key_jwk
461            .get("kty")
462            .and_then(|v| v.as_str())
463            .ok_or_else(|| AuthError::validation("Missing key type in JWK"))?;
464
465        // Perform REAL cryptographic validation using Ring
466        match key_type {
467            "RSA" => {
468                // Extract RSA public key components
469                let n = public_key_jwk
470                    .get("n")
471                    .and_then(|v| v.as_str())
472                    .ok_or_else(|| AuthError::validation("Missing 'n' parameter in RSA JWK"))?;
473                let e = public_key_jwk
474                    .get("e")
475                    .and_then(|v| v.as_str())
476                    .ok_or_else(|| AuthError::validation("Missing 'e' parameter in RSA JWK"))?;
477
478                // Decode RSA components
479                let n_bytes = URL_SAFE_NO_PAD.decode(n.as_bytes()).map_err(|e| {
480                    AuthError::validation(format!("Invalid base64url 'n' parameter: {}", e))
481                })?;
482                let e_bytes = URL_SAFE_NO_PAD.decode(e.as_bytes()).map_err(|e| {
483                    AuthError::validation(format!("Invalid base64url 'e' parameter: {}", e))
484                })?;
485
486                // Create RSA public key in DER format for Ring
487                // Full ASN.1 DER encoding: SEQUENCE { modulus INTEGER, exponent INTEGER }
488                let mut public_key_der = Vec::new();
489
490                // SEQUENCE tag (0x30)
491                public_key_der.push(0x30);
492
493                // Calculate total content length
494                let mut content = Vec::new();
495
496                // Add modulus as INTEGER
497                content.push(0x02); // INTEGER tag
498                // Ensure positive number by adding leading zero if MSB is set
499                if n_bytes[0] & 0x80 != 0 {
500                    content.push((n_bytes.len() + 1) as u8);
501                    content.push(0x00); // Leading zero for positive
502                } else {
503                    content.push(n_bytes.len() as u8);
504                }
505                content.extend_from_slice(&n_bytes);
506
507                // Add exponent as INTEGER
508                content.push(0x02); // INTEGER tag
509                // Ensure positive number by adding leading zero if MSB is set
510                if e_bytes[0] & 0x80 != 0 {
511                    content.push((e_bytes.len() + 1) as u8);
512                    content.push(0x00); // Leading zero for positive
513                } else {
514                    content.push(e_bytes.len() as u8);
515                }
516                content.extend_from_slice(&e_bytes);
517
518                // Add sequence length
519                if content.len() < 128 {
520                    public_key_der.push(content.len() as u8);
521                } else {
522                    // Long form length encoding for content > 127 bytes
523                    if content.len() < 256 {
524                        public_key_der.push(0x81); // Long form, 1 byte
525                        public_key_der.push(content.len() as u8);
526                    } else {
527                        public_key_der.push(0x82); // Long form, 2 bytes
528                        public_key_der.push((content.len() >> 8) as u8);
529                        public_key_der.push((content.len() & 0xFF) as u8);
530                    }
531                }
532
533                // Add the content
534                public_key_der.extend_from_slice(&content);
535
536                // Select Ring verification algorithm
537                let verification_algorithm = match alg_str {
538                    "RS256" => &signature::RSA_PKCS1_2048_8192_SHA256,
539                    "RS384" => &signature::RSA_PKCS1_2048_8192_SHA384,
540                    "RS512" => &signature::RSA_PKCS1_2048_8192_SHA512,
541                    "PS256" => &signature::RSA_PSS_2048_8192_SHA256,
542                    "PS384" => &signature::RSA_PSS_2048_8192_SHA384,
543                    "PS512" => &signature::RSA_PSS_2048_8192_SHA512,
544                    _ => {
545                        return Err(AuthError::validation(format!(
546                            "Unsupported RSA algorithm: {}",
547                            alg_str
548                        )));
549                    }
550                };
551
552                // Create public key and verify with timing-safe operations
553                let public_key =
554                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_der);
555
556                // Use constant-time verification to prevent timing attacks
557                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
558                    Ok(()) => {
559                        // Add timing protection: always do the same amount of work
560                        let _ = std::hint::black_box(alg_str);
561                        tracing::debug!(
562                            "DPoP proof RSA signature successfully verified using Ring with algorithm {}",
563                            alg_str
564                        );
565                    }
566                    Err(_) => {
567                        // Add timing protection: always do the same amount of work
568                        let _ = std::hint::black_box(alg_str);
569                        let error_msg = format!(
570                            "DPoP proof RSA signature verification failed with algorithm {}",
571                            alg_str
572                        );
573                        errors.push(error_msg.clone());
574                        tracing::warn!("{}", error_msg);
575                        return Err(AuthError::validation(
576                            "DPoP RSA signature verification failed",
577                        ));
578                    }
579                }
580            }
581            "EC" => {
582                // Extract elliptic curve public key components
583                let curve = public_key_jwk
584                    .get("crv")
585                    .and_then(|v| v.as_str())
586                    .ok_or_else(|| AuthError::validation("Missing 'crv' parameter in EC JWK"))?;
587                let x = public_key_jwk
588                    .get("x")
589                    .and_then(|v| v.as_str())
590                    .ok_or_else(|| AuthError::validation("Missing 'x' parameter in EC JWK"))?;
591                let y = public_key_jwk
592                    .get("y")
593                    .and_then(|v| v.as_str())
594                    .ok_or_else(|| AuthError::validation("Missing 'y' parameter in EC JWK"))?;
595
596                // Decode EC coordinates
597                let x_bytes = URL_SAFE_NO_PAD.decode(x.as_bytes()).map_err(|e| {
598                    AuthError::validation(format!("Invalid base64url 'x' parameter: {}", e))
599                })?;
600                let y_bytes = URL_SAFE_NO_PAD.decode(y.as_bytes()).map_err(|e| {
601                    AuthError::validation(format!("Invalid base64url 'y' parameter: {}", e))
602                })?;
603
604                // Select verification algorithm and coordinate length
605                let (verification_algorithm, expected_coord_len) = match (curve, alg_str) {
606                    ("P-256", "ES256") => (&signature::ECDSA_P256_SHA256_ASN1, 32),
607                    ("P-384", "ES384") => (&signature::ECDSA_P384_SHA384_ASN1, 48),
608                    _ => {
609                        return Err(AuthError::validation(format!(
610                            "Unsupported EC curve/algorithm combination: {}/{}",
611                            curve, alg_str
612                        )));
613                    }
614                };
615
616                // Validate coordinate lengths
617                if x_bytes.len() != expected_coord_len || y_bytes.len() != expected_coord_len {
618                    return Err(AuthError::validation(format!(
619                        "Invalid coordinate length for curve {}: expected {}, got x={}, y={}",
620                        curve,
621                        expected_coord_len,
622                        x_bytes.len(),
623                        y_bytes.len()
624                    )));
625                }
626
627                // Create uncompressed point format (0x04 || x || y)
628                let mut public_key_bytes = Vec::with_capacity(1 + expected_coord_len * 2);
629                public_key_bytes.push(0x04); // Uncompressed point indicator
630                public_key_bytes.extend_from_slice(&x_bytes);
631                public_key_bytes.extend_from_slice(&y_bytes);
632
633                // Create public key for verification
634                let public_key =
635                    signature::UnparsedPublicKey::new(verification_algorithm, &public_key_bytes);
636
637                // Verify ECDSA signature with timing protection
638                match public_key.verify(signing_input.as_bytes(), &signature_bytes) {
639                    Ok(()) => {
640                        // Add timing protection: always do the same amount of work
641                        let _ = std::hint::black_box((curve, alg_str));
642                        tracing::debug!(
643                            "DPoP proof ECDSA signature successfully verified using Ring with curve {} and algorithm {}",
644                            curve,
645                            alg_str
646                        );
647                    }
648                    Err(_) => {
649                        // Add timing protection: always do the same amount of work
650                        let _ = std::hint::black_box((curve, alg_str));
651                        let error_msg = format!(
652                            "DPoP proof ECDSA signature verification failed with curve {} and algorithm {}",
653                            curve, alg_str
654                        );
655                        errors.push(error_msg.clone());
656                        tracing::warn!("{}", error_msg);
657                        return Err(AuthError::validation(
658                            "DPoP ECDSA signature verification failed",
659                        ));
660                    }
661                }
662            }
663            _ => {
664                return Err(AuthError::validation(format!(
665                    "Unsupported key type for cryptographic verification: {}",
666                    key_type
667                )));
668            }
669        }
670
671        // Additional validation: verify that the JWT contains required DPoP claims
672        let claims_bytes = URL_SAFE_NO_PAD
673            .decode(parts[1])
674            .map_err(|_| AuthError::validation("Invalid JWT claims encoding"))?;
675        let claims: serde_json::Value = serde_json::from_slice(&claims_bytes)
676            .map_err(|_| AuthError::validation("Invalid JWT claims JSON"))?;
677
678        // Check for required DPoP claims
679        if claims.get("htm").is_none() {
680            errors.push("DPoP proof missing 'htm' claim".to_string());
681        }
682        if claims.get("htu").is_none() {
683            errors.push("DPoP proof missing 'htu' claim".to_string());
684        }
685        if claims.get("jti").is_none() {
686            errors.push("DPoP proof missing 'jti' claim".to_string());
687        }
688        if claims.get("iat").is_none() {
689            errors.push("DPoP proof missing 'iat' claim".to_string());
690        }
691
692        Ok(())
693    }
694
695    /// Calculate JWK thumbprint (RFC 7638)
696    fn calculate_jwk_thumbprint(&self, jwk: &serde_json::Value) -> Result<String> {
697        use sha2::{Digest, Sha256};
698
699        // Create canonical JWK representation for thumbprint
700        let mut canonical_jwk = serde_json::Map::new();
701
702        // Add required fields in lexicographic order
703        if let Some(crv) = jwk.get("crv") {
704            canonical_jwk.insert("crv".to_string(), crv.clone());
705        }
706        if let Some(kty) = jwk.get("kty") {
707            canonical_jwk.insert("kty".to_string(), kty.clone());
708        }
709        if let Some(x) = jwk.get("x") {
710            canonical_jwk.insert("x".to_string(), x.clone());
711        }
712        if let Some(y) = jwk.get("y") {
713            canonical_jwk.insert("y".to_string(), y.clone());
714        }
715        if let Some(n) = jwk.get("n") {
716            canonical_jwk.insert("n".to_string(), n.clone());
717        }
718        if let Some(e) = jwk.get("e") {
719            canonical_jwk.insert("e".to_string(), e.clone());
720        }
721
722        // Serialize to JSON without spaces
723        let canonical_json = serde_json::to_string(&canonical_jwk).map_err(|_| {
724            AuthError::auth_method("dpop", "Failed to serialize JWK for thumbprint")
725        })?;
726
727        // Calculate SHA-256 hash
728        let mut hasher = Sha256::new();
729        hasher.update(canonical_json.as_bytes());
730        let hash = hasher.finalize();
731
732        Ok(URL_SAFE_NO_PAD.encode(hash))
733    }
734
735    /// Calculate access token hash for DPoP proof
736    fn calculate_access_token_hash(&self, access_token: &str) -> Result<String> {
737        use sha2::{Digest, Sha256};
738
739        let mut hasher = Sha256::new();
740        hasher.update(access_token.as_bytes());
741        let hash = hasher.finalize();
742
743        Ok(URL_SAFE_NO_PAD.encode(hash))
744    }
745
746    /// Normalize URI by removing query and fragment components
747    fn normalize_uri(&self, uri: &str) -> Result<String> {
748        let url = url::Url::parse(uri)
749            .map_err(|_| AuthError::auth_method("dpop", "Invalid URI format"))?;
750
751        // Reconstruct URL without query and fragment
752        let normalized = format!(
753            "{}://{}{}",
754            url.scheme(),
755            url.host_str().unwrap_or(""),
756            url.path()
757        );
758
759        Ok(normalized)
760    }
761
762    /// Validate JWT access token with DPoP binding
763    fn validate_access_token_jwt(
764        &self,
765        access_token: &str,
766        dpop_proof_jwt: &str,
767    ) -> Result<serde_json::Value> {
768        // Parse the access token as a JWT to extract claims
769        let token_parts: Vec<&str> = access_token.split('.').collect();
770        if token_parts.len() != 3 {
771            return Err(AuthError::token("Invalid JWT format".to_string()));
772        }
773
774        // Decode the payload (claims) section
775        let payload = URL_SAFE_NO_PAD
776            .decode(token_parts[1])
777            .map_err(|_| AuthError::token("Invalid JWT payload encoding".to_string()))?;
778
779        let claims: serde_json::Value = serde_json::from_slice(&payload)
780            .map_err(|_| AuthError::token("Invalid JWT claims format".to_string()))?;
781
782        // Parse the DPoP proof to get the JWK
783        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
784
785        // Verify the access token is properly bound to the DPoP proof
786        if let Some(cnf) = claims.get("cnf").and_then(|c| c.as_object())
787            && let Some(jkt) = cnf.get("jkt").and_then(|j| j.as_str())
788            && let Some(jwk) = dpop_header.get("jwk")
789        {
790            let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
791            if jkt == dpop_jkt {
792                tracing::debug!(
793                    "Access token DPoP binding verified for subject: {:?}",
794                    claims
795                        .get("sub")
796                        .and_then(|s| s.as_str())
797                        .unwrap_or("unknown")
798                );
799                return Ok(claims);
800            }
801        }
802
803        Err(AuthError::token(
804            "Access token not bound to DPoP key".to_string(),
805        ))
806    }
807
808    /// Verify DPoP proof matches token binding
809    fn verify_dpop_token_binding(
810        &self,
811        token_claims: &serde_json::Value,
812        dpop_proof_jwt: &str,
813    ) -> Result<()> {
814        // Extract confirmation claim from access token
815        let cnf = token_claims
816            .get("cnf")
817            .and_then(|c| c.as_object())
818            .ok_or_else(|| {
819                AuthError::token("Access token missing confirmation claim".to_string())
820            })?;
821
822        let token_jkt = cnf
823            .get("jkt")
824            .and_then(|j| j.as_str())
825            .ok_or_else(|| AuthError::token("Access token missing JWK thumbprint".to_string()))?;
826
827        // Calculate thumbprint from DPoP proof JWK
828        let (dpop_header, _dpop_claims) = self.parse_dpop_proof(dpop_proof_jwt)?;
829        let jwk = dpop_header
830            .get("jwk")
831            .ok_or_else(|| AuthError::token("DPoP proof missing JWK".to_string()))?;
832        let dpop_jkt = self.calculate_jwk_thumbprint(jwk)?;
833
834        if token_jkt != dpop_jkt {
835            return Err(AuthError::token(
836                "DPoP proof JWK does not match access token binding".to_string(),
837            ));
838        }
839
840        Ok(())
841    }
842
843    /// Validate opaque access token through introspection
844    fn validate_opaque_access_token(
845        &self,
846        access_token: &str,
847    ) -> Result<(serde_json::Value, serde_json::Value)> {
848        // For opaque tokens, we would typically call the token introspection endpoint
849        // For now, create a mock response that demonstrates the structure
850        let header = serde_json::json!({
851            "typ": "token+jwt",
852            "alg": "none"
853        });
854
855        let claims = serde_json::json!({
856            "active": true,
857            "token_type": "Bearer",
858            "scope": "read write",
859            "sub": "user123",
860            "aud": ["resource-server"],
861            "exp": (chrono::Utc::now().timestamp() + 3600),
862            "iat": chrono::Utc::now().timestamp(),
863            "jti": access_token
864        });
865
866        tracing::debug!("Validated opaque access token through introspection");
867        Ok((header, claims))
868    }
869}
870
871#[cfg(test)]
872mod tests {
873    use super::*;
874    use crate::security::secure_jwt::SecureJwtConfig;
875
876    fn create_test_dpop_manager() -> DpopManager {
877        let jwt_config = SecureJwtConfig::default();
878        let jwt_validator = SecureJwtValidator::new(jwt_config).expect("test JWT config");
879        DpopManager::new(jwt_validator)
880    }
881    fn create_test_jwk() -> serde_json::Value {
882        serde_json::json!({
883            "kty": "EC",
884            "crv": "P-256",
885            "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
886            "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
887            "use": "sig",
888            "alg": "ES256"
889        })
890    }
891
892    #[tokio::test]
893    async fn test_dpop_manager_creation() {
894        let manager = create_test_dpop_manager();
895        let nonce = manager.generate_nonce();
896        assert!(!nonce.is_empty());
897    }
898
899    #[test]
900    fn test_jwk_thumbprint_calculation() {
901        let manager = create_test_dpop_manager();
902        let jwk = create_test_jwk();
903
904        let thumbprint = manager.calculate_jwk_thumbprint(&jwk).unwrap();
905        assert!(!thumbprint.is_empty());
906
907        // Same JWK should produce same thumbprint
908        let thumbprint2 = manager.calculate_jwk_thumbprint(&jwk).unwrap();
909        assert_eq!(thumbprint, thumbprint2);
910    }
911
912    #[test]
913    fn test_dpop_confirmation() {
914        let manager = create_test_dpop_manager();
915        let jwk = create_test_jwk();
916
917        let confirmation = manager.create_dpop_confirmation(&jwk).unwrap();
918        assert!(!confirmation.jkt.is_empty());
919
920        // Validate with same JWK
921        let is_valid = manager
922            .validate_dpop_bound_token(&confirmation, &jwk)
923            .unwrap();
924        assert!(is_valid);
925
926        // Validate with different JWK (should fail)
927        let different_jwk = serde_json::json!({
928            "kty": "EC",
929            "crv": "P-256",
930            "x": "different_x_value_here_for_testing_purposes",
931            "y": "different_y_value_here_for_testing_purposes",
932            "use": "sig",
933            "alg": "ES256"
934        });
935
936        let is_valid = manager
937            .validate_dpop_bound_token(&confirmation, &different_jwk)
938            .unwrap();
939        assert!(!is_valid);
940    }
941
942    #[test]
943    fn test_uri_normalization() {
944        let manager = create_test_dpop_manager();
945
946        let uri = "https://example.com/api/resource?param=value#fragment";
947        let normalized = manager.normalize_uri(uri).unwrap();
948        assert_eq!(normalized, "https://example.com/api/resource");
949
950        let uri2 = "https://example.com/api/resource";
951        let normalized2 = manager.normalize_uri(uri2).unwrap();
952        assert_eq!(normalized2, "https://example.com/api/resource");
953    }
954
955    #[test]
956    fn test_access_token_hash() {
957        let manager = create_test_dpop_manager();
958
959        let token = "test_access_token_value";
960        let hash = manager.calculate_access_token_hash(token).unwrap();
961        assert!(!hash.is_empty());
962
963        // Same token should produce same hash
964        let hash2 = manager.calculate_access_token_hash(token).unwrap();
965        assert_eq!(hash, hash2);
966    }
967
968    #[tokio::test]
969    async fn test_nonce_cleanup() {
970        let manager = create_test_dpop_manager();
971
972        // Add some test nonces
973        {
974            let mut nonces = manager.used_nonces.write().await;
975            nonces.insert("old_nonce".to_string(), Utc::now() - Duration::hours(1));
976            nonces.insert("recent_nonce".to_string(), Utc::now());
977        }
978
979        // Cleanup should remove old nonces
980        manager.cleanup_expired_nonces().await;
981
982        let nonces = manager.used_nonces.read().await;
983        assert!(!nonces.contains_key("old_nonce"));
984        assert!(nonces.contains_key("recent_nonce"));
985    }
986}