Skip to main content

auth_framework/server/core/
common_jwt.rs

1//! Common JWT Operations
2//!
3//! This module provides shared JWT functionality to eliminate
4//! duplication across server modules.
5
6use crate::errors::{AuthError, Result};
7use crate::server::core::common_validation;
8use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::time::{SystemTime, UNIX_EPOCH};
12
13/// Common JWT configuration
14#[derive(Clone)]
15pub struct JwtConfig {
16    /// Signing algorithm
17    pub algorithm: Algorithm,
18    /// Signing key
19    pub signing_key: EncodingKey,
20    /// Verification key
21    pub verification_key: DecodingKey,
22    /// Default expiration time in seconds
23    pub default_expiration: u64,
24    /// Issuer
25    pub issuer: String,
26    /// Audiences
27    pub audiences: Vec<String>,
28}
29
30impl JwtConfig {
31    /// Create new JWT config with symmetric key
32    pub fn with_symmetric_key(secret: &[u8], issuer: String) -> Self {
33        Self {
34            algorithm: Algorithm::HS256,
35            signing_key: EncodingKey::from_secret(secret),
36            verification_key: DecodingKey::from_secret(secret),
37            default_expiration: 3600, // 1 hour
38            issuer,
39            audiences: vec![],
40        }
41    }
42
43    /// Create new JWT config with RSA keys
44    pub fn with_rsa_keys(private_key: &[u8], public_key: &[u8], issuer: String) -> Result<Self> {
45        let signing_key = EncodingKey::from_rsa_pem(private_key)
46            .map_err(|e| AuthError::validation(format!("Invalid private key: {}", e)))?;
47
48        let verification_key = DecodingKey::from_rsa_pem(public_key)
49            .map_err(|e| AuthError::validation(format!("Invalid public key: {}", e)))?;
50
51        Ok(Self {
52            algorithm: Algorithm::RS256,
53            signing_key,
54            verification_key,
55            default_expiration: 3600, // 1 hour
56            issuer,
57            audiences: vec![],
58        })
59    }
60
61    /// Add audience
62    pub fn with_audience(mut self, audience: String) -> Self {
63        self.audiences.push(audience);
64        self
65    }
66
67    /// Set expiration time
68    pub fn with_expiration(mut self, expiration: u64) -> Self {
69        self.default_expiration = expiration;
70        self
71    }
72}
73
74/// Common JWT claims structure
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct CommonJwtClaims {
77    /// Issuer
78    pub iss: String,
79    /// Subject
80    pub sub: String,
81    /// Audience
82    pub aud: Vec<String>,
83    /// Expiration time
84    pub exp: i64,
85    /// Issued at
86    pub iat: i64,
87    /// Not before
88    pub nbf: Option<i64>,
89    /// JWT ID
90    pub jti: Option<String>,
91    /// Custom claims
92    #[serde(flatten)]
93    pub custom: HashMap<String, serde_json::Value>,
94}
95
96impl CommonJwtClaims {
97    /// Create new claims with required fields
98    pub fn new(issuer: String, subject: String, audiences: Vec<String>, expiration: i64) -> Self {
99        let now = SystemTime::now()
100            .duration_since(UNIX_EPOCH)
101            .unwrap()
102            .as_secs() as i64;
103
104        Self {
105            iss: issuer,
106            sub: subject,
107            aud: audiences,
108            exp: expiration,
109            iat: now,
110            nbf: None,
111            jti: None,
112            custom: HashMap::new(),
113        }
114    }
115
116    /// Add custom claim
117    pub fn with_custom_claim(mut self, key: String, value: serde_json::Value) -> Self {
118        self.custom.insert(key, value);
119        self
120    }
121
122    /// Set JWT ID
123    pub fn with_jti(mut self, jti: String) -> Self {
124        self.jti = Some(jti);
125        self
126    }
127
128    /// Set not before
129    pub fn with_nbf(mut self, nbf: i64) -> Self {
130        self.nbf = Some(nbf);
131        self
132    }
133}
134
135/// Common JWT token management for OAuth 2.0 and OpenID Connect operations.
136///
137/// `JwtManager` provides comprehensive JWT token creation, verification, and
138/// management capabilities specifically designed for OAuth 2.0 authorization
139/// servers and OpenID Connect providers. It supports both symmetric and
140/// asymmetric signing algorithms with security best practices.
141///
142/// # Supported Algorithms
143///
144/// - **HMAC**: HS256, HS384, HS512 (symmetric)
145/// - **RSA**: RS256, RS384, RS512 (asymmetric)
146/// - **ECDSA**: ES256, ES384, ES512 (asymmetric)
147/// - **EdDSA**: EdDSA (asymmetric, Ed25519)
148///
149/// # Security Features
150///
151/// - **Algorithm Validation**: Prevents algorithm confusion attacks
152/// - **Time Validation**: Automatic `exp`, `nbf`, and `iat` claim validation
153/// - **Audience Validation**: Ensures tokens are used by intended recipients
154/// - **Issuer Validation**: Verifies token origin
155/// - **Secure Defaults**: Uses secure algorithm choices and expiration times
156///
157/// # Token Types Supported
158///
159/// - **Access Tokens**: OAuth 2.0 access tokens with scopes
160/// - **ID Tokens**: OpenID Connect identity tokens
161/// - **Refresh Tokens**: Long-lived tokens for access token renewal
162/// - **Custom Tokens**: Application-specific token types
163///
164/// # Key Management
165///
166/// - **Symmetric Keys**: HMAC-based signing with shared secrets
167/// - **RSA Keys**: Support for PKCS#1 and PKCS#8 key formats
168/// - **Key Rotation**: Support for multiple signing keys
169/// - **Key Security**: Secure key storage and access patterns
170///
171/// # Example
172///
173/// ```rust,no_run
174/// use auth_framework::server::core::common_jwt::{JwtManager, JwtConfig, CommonJwtClaims};
175///
176/// # fn example(private_key_bytes: &[u8], public_key_bytes: &[u8], expiration_time: i64) -> Result<(), Box<dyn std::error::Error>> {
177/// // Create JWT manager with RSA keys
178/// let config = JwtConfig::with_rsa_keys(
179///     private_key_bytes,
180///     public_key_bytes,
181///     "https://auth.example.com".to_string()
182/// )?;
183/// let jwt_manager = JwtManager::new(config);
184///
185/// // Create access token
186/// let claims = CommonJwtClaims::new(
187///     "https://auth.example.com".to_string(),
188///     "user123".to_string(),
189///     vec!["api".to_string()],
190///     expiration_time
191/// ).with_custom_claim("scope".to_string(), serde_json::json!("read write"));
192///
193/// let token = jwt_manager.create_token(&claims)?;
194///
195/// // Verify token
196/// let verified_claims = jwt_manager.verify_token(&token)?;
197/// # Ok(())
198/// # }
199/// ```
200///
201/// # Performance Considerations
202///
203/// - Asymmetric algorithms are more computationally expensive
204/// - Token verification is optimized for high-throughput scenarios
205/// - Key caching reduces cryptographic operation overhead
206///
207/// # RFC Compliance
208///
209/// - **RFC 7519**: JSON Web Token (JWT)
210/// - **RFC 7515**: JSON Web Signature (JWS)
211/// - **RFC 8725**: JWT Best Current Practices
212/// - **RFC 9068**: JWT Profile for OAuth 2.0 Access Tokens
213pub struct JwtManager {
214    config: JwtConfig,
215}
216
217impl JwtManager {
218    /// Create new JWT manager
219    pub fn new(config: JwtConfig) -> Self {
220        Self { config }
221    }
222
223    /// Create signed JWT token
224    pub fn create_token(&self, claims: &CommonJwtClaims) -> Result<String> {
225        let header = Header {
226            alg: self.config.algorithm,
227            ..Default::default()
228        };
229
230        encode(&header, claims, &self.config.signing_key)
231            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
232    }
233
234    /// Create signed token with custom claims
235    pub fn create_token_with_custom_claims<T>(&self, claims: &T) -> Result<String>
236    where
237        T: Serialize,
238    {
239        let header = Header {
240            alg: self.config.algorithm,
241            ..Default::default()
242        };
243
244        encode(&header, claims, &self.config.signing_key)
245            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
246    }
247
248    /// Verify and decode JWT token
249    pub fn verify_token(&self, token: &str) -> Result<CommonJwtClaims> {
250        // Basic format validation
251        common_validation::jwt::validate_jwt_format(token)?;
252
253        let mut validation = Validation::new(self.config.algorithm);
254        validation.set_issuer(&[&self.config.issuer]);
255
256        if !self.config.audiences.is_empty() {
257            validation.set_audience(
258                &self
259                    .config
260                    .audiences
261                    .iter()
262                    .map(String::as_str)
263                    .collect::<Vec<_>>(),
264            );
265        }
266
267        let token_data =
268            decode::<CommonJwtClaims>(token, &self.config.verification_key, &validation)
269                .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;
270
271        // Additional validation using common validation utilities
272        let claims_value = serde_json::to_value(&token_data.claims)
273            .map_err(|e| AuthError::validation(format!("Failed to serialize claims: {}", e)))?;
274
275        common_validation::jwt::validate_time_claims(&claims_value)?;
276
277        Ok(token_data.claims)
278    }
279
280    /// Verify token and extract custom claims
281    pub fn verify_token_with_custom_claims<T>(&self, token: &str) -> Result<T>
282    where
283        T: for<'de> Deserialize<'de>,
284    {
285        common_validation::jwt::validate_jwt_format(token)?;
286
287        let mut validation = Validation::new(self.config.algorithm);
288        validation.set_issuer(&[&self.config.issuer]);
289
290        if !self.config.audiences.is_empty() {
291            validation.set_audience(
292                &self
293                    .config
294                    .audiences
295                    .iter()
296                    .map(String::as_str)
297                    .collect::<Vec<_>>(),
298            );
299        }
300
301        let token_data = decode::<T>(token, &self.config.verification_key, &validation)
302            .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;
303
304        Ok(token_data.claims)
305    }
306
307    /// Create access token with standard claims
308    pub fn create_access_token(
309        &self,
310        subject: String,
311        scope: Vec<String>,
312        client_id: Option<String>,
313    ) -> Result<String> {
314        let exp = SystemTime::now()
315            .duration_since(UNIX_EPOCH)
316            .unwrap()
317            .as_secs() as i64
318            + self.config.default_expiration as i64;
319
320        let mut claims = CommonJwtClaims::new(
321            self.config.issuer.clone(),
322            subject,
323            self.config.audiences.clone(),
324            exp,
325        );
326
327        claims
328            .custom
329            .insert("scope".to_string(), serde_json::json!(scope.join(" ")));
330
331        if let Some(client_id) = client_id {
332            claims.custom.insert(
333                "client_id".to_string(),
334                serde_json::Value::String(client_id),
335            );
336        }
337
338        claims.custom.insert(
339            "token_type".to_string(),
340            serde_json::Value::String("access_token".to_string()),
341        );
342
343        self.create_token(&claims)
344    }
345
346    /// Create refresh token
347    pub fn create_refresh_token(&self, subject: String, client_id: String) -> Result<String> {
348        // Refresh tokens typically have longer expiration
349        let exp = SystemTime::now()
350            .duration_since(UNIX_EPOCH)
351            .unwrap()
352            .as_secs() as i64
353            + (self.config.default_expiration * 24) as i64; // 24x longer
354
355        let mut claims = CommonJwtClaims::new(
356            self.config.issuer.clone(),
357            subject,
358            self.config.audiences.clone(),
359            exp,
360        );
361
362        claims.custom.insert(
363            "client_id".to_string(),
364            serde_json::Value::String(client_id),
365        );
366        claims.custom.insert(
367            "token_type".to_string(),
368            serde_json::Value::String("refresh_token".to_string()),
369        );
370
371        self.create_token(&claims)
372    }
373
374    /// Create ID token for OpenID Connect
375    pub fn create_id_token(
376        &self,
377        subject: String,
378        nonce: Option<String>,
379        auth_time: Option<i64>,
380        user_info: HashMap<String, serde_json::Value>,
381    ) -> Result<String> {
382        let exp = SystemTime::now()
383            .duration_since(UNIX_EPOCH)
384            .unwrap()
385            .as_secs() as i64
386            + 300; // 5 minutes for ID token
387
388        let mut claims = CommonJwtClaims::new(
389            self.config.issuer.clone(),
390            subject,
391            self.config.audiences.clone(),
392            exp,
393        );
394
395        claims.custom.insert(
396            "token_type".to_string(),
397            serde_json::Value::String("id_token".to_string()),
398        );
399
400        if let Some(nonce) = nonce {
401            claims
402                .custom
403                .insert("nonce".to_string(), serde_json::Value::String(nonce));
404        }
405
406        if let Some(auth_time) = auth_time {
407            claims.custom.insert(
408                "auth_time".to_string(),
409                serde_json::Value::Number(auth_time.into()),
410            );
411        }
412
413        // Add user info claims
414        for (key, value) in user_info {
415            claims.custom.insert(key, value);
416        }
417
418        self.create_token(&claims)
419    }
420}
421
422/// JWT utilities for token introspection and manipulation
423pub mod utils {
424    use super::*;
425
426    /// Extract claims from JWT without verification (for inspection only)
427    ///
428    /// # Security Warning
429    /// This function bypasses JWT signature verification! Only use for:
430    /// - Token inspection and debugging
431    /// - Extracting metadata before full validation
432    /// - Non-security-critical token analysis
433    ///
434    /// Never use for authentication or authorization decisions!
435    pub fn extract_claims_unsafe(token: &str) -> Result<serde_json::Value> {
436        common_validation::jwt::extract_claims_unsafe(token)
437    }
438
439    /// Check if token is expired without full verification
440    ///
441    /// # Security Warning
442    /// This function checks expiration without validating the JWT signature.
443    /// Only use for preliminary checks - always validate the token fully
444    /// before making security decisions!
445    pub fn is_token_expired(token: &str) -> Result<bool> {
446        let claims = extract_claims_unsafe(token)?;
447
448        let now = SystemTime::now()
449            .duration_since(UNIX_EPOCH)
450            .unwrap()
451            .as_secs() as i64;
452
453        if let Some(exp) = claims.get("exp").and_then(|v| v.as_i64()) {
454            Ok(now >= exp)
455        } else {
456            Ok(false) // No expiration claim means not expired
457        }
458    }
459
460    /// Get token expiration time without signature validation
461    ///
462    /// # Security Warning
463    /// This function extracts expiration time without validating the JWT signature.
464    /// Only use for inspection - validate the token before trusting the data!
465    pub fn get_token_expiration(token: &str) -> Result<Option<i64>> {
466        let claims = extract_claims_unsafe(token)?;
467        Ok(claims.get("exp").and_then(|v| v.as_i64()))
468    }
469
470    /// Get token subject without signature validation
471    ///
472    /// # Security Warning
473    /// This function extracts the subject without validating the JWT signature.
474    /// Only use for inspection - validate the token before trusting the data!
475    pub fn get_token_subject(token: &str) -> Result<Option<String>> {
476        let claims = extract_claims_unsafe(token)?;
477        Ok(claims.get("sub").and_then(|v| v.as_str()).map(String::from))
478    }
479
480    /// Get token scopes without signature validation
481    ///
482    /// # Security Warning
483    /// This function extracts scopes without validating the JWT signature.
484    /// Only use for inspection - validate the token before trusting the data!
485    pub fn get_token_scopes(token: &str) -> Result<Vec<String>> {
486        let claims = extract_claims_unsafe(token)?;
487
488        if let Some(scope_str) = claims.get("scope").and_then(|v| v.as_str()) {
489            Ok(scope_str.split_whitespace().map(String::from).collect())
490        } else if let Some(scopes_array) = claims.get("scopes").and_then(|v| v.as_array()) {
491            Ok(scopes_array
492                .iter()
493                .filter_map(|v| v.as_str())
494                .map(String::from)
495                .collect())
496        } else {
497            Ok(vec![])
498        }
499    }
500}