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. Omitted from the serialized token when empty -- RFC 7519
82    /// treats `aud` as an intended-recipient claim, and an empty array is
83    /// not a meaningful value for it. jsonwebtoken 10.4.0+ validates a
84    /// present `aud` even when the verifier configured no expected
85    /// audience, so previously we issued tokens that could fail
86    /// verification for a reason unrelated to any real audience mismatch.
87    #[serde(default, skip_serializing_if = "Vec::is_empty")]
88    pub aud: Vec<String>,
89    /// Expiration time
90    pub exp: i64,
91    /// Issued at
92    pub iat: i64,
93    /// Not before
94    pub nbf: Option<i64>,
95    /// JWT ID
96    pub jti: Option<String>,
97    /// Custom claims
98    #[serde(flatten)]
99    pub custom: HashMap<String, serde_json::Value>,
100}
101
102impl CommonJwtClaims {
103    /// Create new claims with required fields
104    pub fn new(issuer: String, subject: String, audiences: Vec<String>, expiration: i64) -> Self {
105        let now = SystemTime::now()
106            .duration_since(UNIX_EPOCH)
107            .unwrap_or_default()
108            .as_secs() as i64;
109
110        Self {
111            iss: issuer,
112            sub: subject,
113            aud: audiences,
114            exp: expiration,
115            iat: now,
116            nbf: None,
117            jti: None,
118            custom: HashMap::new(),
119        }
120    }
121
122    /// Add custom claim
123    pub fn with_custom_claim(mut self, key: String, value: serde_json::Value) -> Self {
124        self.custom.insert(key, value);
125        self
126    }
127
128    /// Set JWT ID
129    pub fn with_jti(mut self, jti: String) -> Self {
130        self.jti = Some(jti);
131        self
132    }
133
134    /// Set not before
135    pub fn with_nbf(mut self, nbf: i64) -> Self {
136        self.nbf = Some(nbf);
137        self
138    }
139}
140
141/// Common JWT token management for OAuth 2.0 and OpenID Connect operations.
142///
143/// `JwtManager` provides comprehensive JWT token creation, verification, and
144/// management capabilities specifically designed for OAuth 2.0 authorization
145/// servers and OpenID Connect providers. It supports both symmetric and
146/// asymmetric signing algorithms with security best practices.
147///
148/// # Supported Algorithms
149///
150/// - **HMAC**: HS256, HS384, HS512 (symmetric)
151/// - **RSA**: RS256, RS384, RS512 (asymmetric)
152/// - **ECDSA**: ES256, ES384, ES512 (asymmetric)
153/// - **EdDSA**: EdDSA (asymmetric, Ed25519)
154///
155/// # Security Features
156///
157/// - **Algorithm Validation**: Prevents algorithm confusion attacks
158/// - **Time Validation**: Automatic `exp`, `nbf`, and `iat` claim validation
159/// - **Audience Validation**: Ensures tokens are used by intended recipients
160/// - **Issuer Validation**: Verifies token origin
161/// - **Secure Defaults**: Uses secure algorithm choices and expiration times
162///
163/// # Token Types Supported
164///
165/// - **Access Tokens**: OAuth 2.0 access tokens with scopes
166/// - **ID Tokens**: OpenID Connect identity tokens
167/// - **Refresh Tokens**: Long-lived tokens for access token renewal
168/// - **Custom Tokens**: Application-specific token types
169///
170/// # Key Management
171///
172/// - **Symmetric Keys**: HMAC-based signing with shared secrets
173/// - **RSA Keys**: Support for PKCS#1 and PKCS#8 key formats
174/// - **Key Rotation**: Support for multiple signing keys
175/// - **Key Security**: Secure key storage and access patterns
176///
177/// # Example
178///
179/// ```rust,no_run
180/// use auth_framework::server::core::common_jwt::{JwtManager, JwtConfig, CommonJwtClaims};
181///
182/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
183/// # let private_key_bytes: &[u8] = unimplemented!();
184/// # let public_key_bytes: &[u8] = unimplemented!();
185/// # let expiration_time: i64 = unimplemented!();
186/// // Create JWT manager with RSA keys
187/// let config = JwtConfig::with_rsa_keys(
188///     private_key_bytes,
189///     public_key_bytes,
190///     "https://auth.example.com".to_string()
191/// )?;
192/// let jwt_manager = JwtManager::new(config);
193///
194/// // Create access token
195/// let claims = CommonJwtClaims::new(
196///     "https://auth.example.com".to_string(),
197///     "user123".to_string(),
198///     vec!["api".to_string()],
199///     expiration_time
200/// ).with_custom_claim("scope".to_string(), serde_json::json!("read write"));
201///
202/// let token = jwt_manager.create_token(&claims)?;
203///
204/// // Verify token
205/// let verified_claims = jwt_manager.verify_token(&token)?;
206/// # Ok(())
207/// # }
208/// ```
209///
210/// # Performance Considerations
211///
212/// - Asymmetric algorithms are more computationally expensive
213/// - Token verification is optimized for high-throughput scenarios
214/// - Key caching reduces cryptographic operation overhead
215///
216/// # RFC Compliance
217///
218/// - **RFC 7519**: JSON Web Token (JWT)
219/// - **RFC 7515**: JSON Web Signature (JWS)
220/// - **RFC 8725**: JWT Best Current Practices
221/// - **RFC 9068**: JWT Profile for OAuth 2.0 Access Tokens
222pub struct JwtManager {
223    config: JwtConfig,
224}
225
226impl JwtManager {
227    /// Create new JWT manager
228    pub fn new(config: JwtConfig) -> Self {
229        Self { config }
230    }
231
232    /// Create signed JWT token
233    pub fn create_token(&self, claims: &CommonJwtClaims) -> Result<String> {
234        let header = Header {
235            alg: self.config.algorithm,
236            ..Default::default()
237        };
238
239        encode(&header, claims, &self.config.signing_key)
240            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
241    }
242
243    /// Create signed token with custom claims
244    pub fn create_token_with_custom_claims<T>(&self, claims: &T) -> Result<String>
245    where
246        T: Serialize,
247    {
248        let header = Header {
249            alg: self.config.algorithm,
250            ..Default::default()
251        };
252
253        encode(&header, claims, &self.config.signing_key)
254            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
255    }
256
257    /// Verify and decode JWT token
258    pub fn verify_token(&self, token: &str) -> Result<CommonJwtClaims> {
259        // Basic format validation
260        common_validation::jwt::validate_jwt_format(token)?;
261
262        let mut validation = Validation::new(self.config.algorithm);
263        validation.set_issuer(&[&self.config.issuer]);
264
265        if !self.config.audiences.is_empty() {
266            validation.set_audience(
267                &self
268                    .config
269                    .audiences
270                    .iter()
271                    .map(String::as_str)
272                    .collect::<Vec<_>>(),
273            );
274        }
275
276        let token_data =
277            decode::<CommonJwtClaims>(token, &self.config.verification_key, &validation)
278                .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;
279
280        // Additional validation using common validation utilities
281        let claims_value = serde_json::to_value(&token_data.claims)
282            .map_err(|e| AuthError::validation(format!("Failed to serialize claims: {}", e)))?;
283
284        common_validation::jwt::validate_time_claims(&claims_value)?;
285
286        Ok(token_data.claims)
287    }
288
289    /// Verify token and extract custom claims
290    pub fn verify_token_with_custom_claims<T>(&self, token: &str) -> Result<T>
291    where
292        T: for<'de> Deserialize<'de>,
293    {
294        common_validation::jwt::validate_jwt_format(token)?;
295
296        let mut validation = Validation::new(self.config.algorithm);
297        validation.set_issuer(&[&self.config.issuer]);
298
299        if !self.config.audiences.is_empty() {
300            validation.set_audience(
301                &self
302                    .config
303                    .audiences
304                    .iter()
305                    .map(String::as_str)
306                    .collect::<Vec<_>>(),
307            );
308        }
309
310        let token_data = decode::<T>(token, &self.config.verification_key, &validation)
311            .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;
312
313        Ok(token_data.claims)
314    }
315
316    /// Create access token with standard claims
317    pub fn create_access_token(
318        &self,
319        subject: String,
320        scope: Vec<String>,
321        client_id: Option<String>,
322    ) -> Result<String> {
323        let exp = SystemTime::now()
324            .duration_since(UNIX_EPOCH)
325            .unwrap_or_default()
326            .as_secs() as i64
327            + self.config.default_expiration as i64;
328
329        let mut claims = CommonJwtClaims::new(
330            self.config.issuer.clone(),
331            subject,
332            self.config.audiences.clone(),
333            exp,
334        );
335
336        claims
337            .custom
338            .insert("scope".to_string(), serde_json::json!(scope.join(" ")));
339
340        if let Some(client_id) = client_id {
341            claims.custom.insert(
342                "client_id".to_string(),
343                serde_json::Value::String(client_id),
344            );
345        }
346
347        claims.custom.insert(
348            "token_type".to_string(),
349            serde_json::Value::String("access_token".to_string()),
350        );
351
352        self.create_token(&claims)
353    }
354
355    /// Create refresh token
356    pub fn create_refresh_token(&self, subject: String, client_id: String) -> Result<String> {
357        // Refresh tokens typically have longer expiration
358        let exp = SystemTime::now()
359            .duration_since(UNIX_EPOCH)
360            .unwrap_or_default()
361            .as_secs() as i64
362            + (self.config.default_expiration * 24) as i64; // 24x longer
363
364        let mut claims = CommonJwtClaims::new(
365            self.config.issuer.clone(),
366            subject,
367            self.config.audiences.clone(),
368            exp,
369        );
370
371        claims.custom.insert(
372            "client_id".to_string(),
373            serde_json::Value::String(client_id),
374        );
375        claims.custom.insert(
376            "token_type".to_string(),
377            serde_json::Value::String("refresh_token".to_string()),
378        );
379
380        self.create_token(&claims)
381    }
382
383    /// Create ID token for OpenID Connect
384    pub fn create_id_token(
385        &self,
386        subject: String,
387        nonce: Option<String>,
388        auth_time: Option<i64>,
389        user_info: HashMap<String, serde_json::Value>,
390    ) -> Result<String> {
391        let exp = SystemTime::now()
392            .duration_since(UNIX_EPOCH)
393            .unwrap_or_default()
394            .as_secs() as i64
395            + 300; // 5 minutes for ID token
396
397        let mut claims = CommonJwtClaims::new(
398            self.config.issuer.clone(),
399            subject,
400            self.config.audiences.clone(),
401            exp,
402        );
403
404        claims.custom.insert(
405            "token_type".to_string(),
406            serde_json::Value::String("id_token".to_string()),
407        );
408
409        if let Some(nonce) = nonce {
410            claims
411                .custom
412                .insert("nonce".to_string(), serde_json::Value::String(nonce));
413        }
414
415        if let Some(auth_time) = auth_time {
416            claims.custom.insert(
417                "auth_time".to_string(),
418                serde_json::Value::Number(auth_time.into()),
419            );
420        }
421
422        // Add user info claims
423        for (key, value) in user_info {
424            claims.custom.insert(key, value);
425        }
426
427        self.create_token(&claims)
428    }
429}
430
431#[cfg(test)]
432mod tests {
433    use super::*;
434
435    fn make_manager() -> JwtManager {
436        let config = JwtConfig::with_symmetric_key(
437            b"a-test-secret-key-with-enough-bytes-for-hmac",
438            "https://test-issuer.example.com".into(),
439        );
440        JwtManager::new(config)
441    }
442
443    // ── JwtConfig ───────────────────────────────────────────────────────
444
445    #[test]
446    fn test_jwt_config_symmetric() {
447        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into());
448        assert_eq!(config.issuer, "iss");
449        assert_eq!(config.default_expiration, 3600);
450    }
451
452    #[test]
453    fn test_jwt_config_with_audience() {
454        let config =
455            JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_audience("aud1".into());
456        assert_eq!(config.audiences, vec!["aud1"]);
457    }
458
459    #[test]
460    fn test_jwt_config_with_expiration() {
461        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_expiration(7200);
462        assert_eq!(config.default_expiration, 7200);
463    }
464
465    // ── CommonJwtClaims ─────────────────────────────────────────────────
466
467    #[test]
468    fn test_claims_new() {
469        let claims = CommonJwtClaims::new(
470            "issuer".into(),
471            "subject".into(),
472            vec!["aud".into()],
473            9999999999,
474        );
475        assert_eq!(claims.iss, "issuer");
476        assert_eq!(claims.sub, "subject");
477        assert!(claims.iat > 0);
478    }
479
480    #[test]
481    fn test_claims_with_custom_claim() {
482        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
483            .with_custom_claim("role".to_string(), serde_json::json!("admin"));
484        assert_eq!(claims.custom.get("role").unwrap(), "admin");
485    }
486
487    #[test]
488    fn test_claims_with_jti() {
489        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
490            .with_jti("test-jti-value".into());
491        assert!(claims.jti.is_some());
492    }
493
494    // ── JwtManager create/verify ────────────────────────────────────────
495
496    #[test]
497    fn test_create_and_verify_token() {
498        let mgr = make_manager();
499        let claims = CommonJwtClaims::new(
500            "https://test-issuer.example.com".into(),
501            "user_123".into(),
502            vec![],
503            (SystemTime::now()
504                .duration_since(UNIX_EPOCH)
505                .unwrap()
506                .as_secs()
507                + 3600) as i64,
508        );
509        let token = mgr.create_token(&claims).unwrap();
510        let verified = mgr.verify_token(&token).unwrap();
511        assert_eq!(verified.sub, "user_123");
512    }
513
514    #[test]
515    fn test_verify_invalid_token() {
516        let mgr = make_manager();
517        assert!(mgr.verify_token("not.a.valid.jwt").is_err());
518    }
519
520    #[test]
521    fn test_verify_wrong_key() {
522        let mgr1 = make_manager();
523        let mgr2 = JwtManager::new(JwtConfig::with_symmetric_key(
524            b"different-key-entirely-for-testing",
525            "https://test-issuer.example.com".into(),
526        ));
527        let claims = CommonJwtClaims::new(
528            "https://test-issuer.example.com".into(),
529            "user".into(),
530            vec![],
531            (SystemTime::now()
532                .duration_since(UNIX_EPOCH)
533                .unwrap()
534                .as_secs()
535                + 3600) as i64,
536        );
537        let token = mgr1.create_token(&claims).unwrap();
538        assert!(mgr2.verify_token(&token).is_err());
539    }
540
541    // ── Specialized token creation ──────────────────────────────────────
542
543    #[test]
544    fn test_create_access_token() {
545        let mgr = make_manager();
546        let token = mgr
547            .create_access_token(
548                "user_1".into(),
549                vec!["read".into()],
550                Some("client_1".into()),
551            )
552            .unwrap();
553        let claims = mgr.verify_token(&token).unwrap();
554        assert_eq!(claims.sub, "user_1");
555        assert!(claims.custom.contains_key("scope"));
556    }
557
558    #[test]
559    fn test_create_refresh_token() {
560        let mgr = make_manager();
561        let token = mgr
562            .create_refresh_token("user_2".into(), "client_2".into())
563            .unwrap();
564        let claims = mgr.verify_token(&token).unwrap();
565        assert_eq!(claims.sub, "user_2");
566        assert_eq!(
567            claims.custom.get("token_type").unwrap(),
568            &serde_json::json!("refresh_token")
569        );
570    }
571
572    #[test]
573    fn test_create_id_token() {
574        let mgr = make_manager();
575        let user_info = HashMap::from([
576            ("name".into(), serde_json::json!("Test User")),
577            ("email".into(), serde_json::json!("test@example.com")),
578        ]);
579        let token = mgr
580            .create_id_token("user_3".into(), Some("nonce_123".into()), None, user_info)
581            .unwrap();
582        let claims = mgr.verify_token(&token).unwrap();
583        assert_eq!(claims.sub, "user_3");
584        assert_eq!(claims.custom.get("nonce").unwrap(), "nonce_123");
585        assert_eq!(
586            claims.custom.get("token_type").unwrap(),
587            &serde_json::json!("id_token")
588        );
589    }
590
591    // ── Utils ───────────────────────────────────────────────────────────
592}