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/// JWT utilities for token introspection and manipulation
432pub(crate) mod utils {
433    use super::*;
434
435    /// Extract claims from JWT without verification (for inspection only)
436    ///
437    /// # Security Warning
438    /// This function bypasses JWT signature verification! Only use for:
439    /// - Token inspection and debugging
440    /// - Extracting metadata before full validation
441    /// - Non-security-critical token analysis
442    ///
443    /// Never use for authentication or authorization decisions!
444    #[allow(dead_code)]
445    pub(crate) fn extract_claims_unsafe(token: &str) -> Result<serde_json::Value> {
446        common_validation::jwt::extract_claims_unsafe(token)
447    }
448
449    /// Check if token is expired without full verification
450    ///
451    /// # Security Warning
452    /// This function checks expiration without validating the JWT signature.
453    /// Only use for preliminary checks - always validate the token fully
454    /// before making security decisions!
455    #[allow(dead_code)]
456    pub(crate) fn is_token_expired(token: &str) -> Result<bool> {
457        let claims = extract_claims_unsafe(token)?;
458
459        let now = SystemTime::now()
460            .duration_since(UNIX_EPOCH)
461            .unwrap_or_default()
462            .as_secs() as i64;
463
464        if let Some(exp) = claims.get("exp").and_then(|v| v.as_i64()) {
465            Ok(now >= exp)
466        } else {
467            Ok(false) // No expiration claim means not expired
468        }
469    }
470
471    /// Get token expiration time without signature validation
472    ///
473    /// # Security Warning
474    /// This function extracts expiration time without validating the JWT signature.
475    /// Only use for inspection - validate the token before trusting the data!
476    #[allow(dead_code)]
477    pub(crate) fn get_token_expiration(token: &str) -> Result<Option<i64>> {
478        let claims = extract_claims_unsafe(token)?;
479        Ok(claims.get("exp").and_then(|v| v.as_i64()))
480    }
481
482    /// Get token subject without signature validation
483    ///
484    /// # Security Warning
485    /// This function extracts the subject without validating the JWT signature.
486    /// Only use for inspection - validate the token before trusting the data!
487    #[allow(dead_code)]
488    pub(crate) fn get_token_subject(token: &str) -> Result<Option<String>> {
489        let claims = extract_claims_unsafe(token)?;
490        Ok(claims.get("sub").and_then(|v| v.as_str()).map(String::from))
491    }
492
493    /// Get token scopes without signature validation
494    ///
495    /// # Security Warning
496    /// This function extracts scopes without validating the JWT signature.
497    /// Only use for inspection - validate the token before trusting the data!
498    #[allow(dead_code)]
499    pub(crate) fn get_token_scopes(token: &str) -> Result<Vec<String>> {
500        let claims = extract_claims_unsafe(token)?;
501
502        if let Some(scope_str) = claims.get("scope").and_then(|v| v.as_str()) {
503            Ok(scope_str.split_whitespace().map(String::from).collect())
504        } else if let Some(scopes_array) = claims.get("scopes").and_then(|v| v.as_array()) {
505            Ok(scopes_array
506                .iter()
507                .filter_map(|v| v.as_str())
508                .map(String::from)
509                .collect())
510        } else {
511            Ok(vec![])
512        }
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    fn make_manager() -> JwtManager {
521        let config = JwtConfig::with_symmetric_key(
522            b"a-test-secret-key-with-enough-bytes-for-hmac",
523            "https://test-issuer.example.com".into(),
524        );
525        JwtManager::new(config)
526    }
527
528    // ── JwtConfig ───────────────────────────────────────────────────────
529
530    #[test]
531    fn test_jwt_config_symmetric() {
532        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into());
533        assert_eq!(config.issuer, "iss");
534        assert_eq!(config.default_expiration, 3600);
535    }
536
537    #[test]
538    fn test_jwt_config_with_audience() {
539        let config =
540            JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_audience("aud1".into());
541        assert_eq!(config.audiences, vec!["aud1"]);
542    }
543
544    #[test]
545    fn test_jwt_config_with_expiration() {
546        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_expiration(7200);
547        assert_eq!(config.default_expiration, 7200);
548    }
549
550    // ── CommonJwtClaims ─────────────────────────────────────────────────
551
552    #[test]
553    fn test_claims_new() {
554        let claims = CommonJwtClaims::new(
555            "issuer".into(),
556            "subject".into(),
557            vec!["aud".into()],
558            9999999999,
559        );
560        assert_eq!(claims.iss, "issuer");
561        assert_eq!(claims.sub, "subject");
562        assert!(claims.iat > 0);
563    }
564
565    #[test]
566    fn test_claims_with_custom_claim() {
567        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
568            .with_custom_claim("role".to_string(), serde_json::json!("admin"));
569        assert_eq!(claims.custom.get("role").unwrap(), "admin");
570    }
571
572    #[test]
573    fn test_claims_with_jti() {
574        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
575            .with_jti("test-jti-value".into());
576        assert!(claims.jti.is_some());
577    }
578
579    // ── JwtManager create/verify ────────────────────────────────────────
580
581    #[test]
582    fn test_create_and_verify_token() {
583        let mgr = make_manager();
584        let claims = CommonJwtClaims::new(
585            "https://test-issuer.example.com".into(),
586            "user_123".into(),
587            vec![],
588            (SystemTime::now()
589                .duration_since(UNIX_EPOCH)
590                .unwrap()
591                .as_secs()
592                + 3600) as i64,
593        );
594        let token = mgr.create_token(&claims).unwrap();
595        let verified = mgr.verify_token(&token).unwrap();
596        assert_eq!(verified.sub, "user_123");
597    }
598
599    #[test]
600    fn test_verify_invalid_token() {
601        let mgr = make_manager();
602        assert!(mgr.verify_token("not.a.valid.jwt").is_err());
603    }
604
605    #[test]
606    fn test_verify_wrong_key() {
607        let mgr1 = make_manager();
608        let mgr2 = JwtManager::new(JwtConfig::with_symmetric_key(
609            b"different-key-entirely-for-testing",
610            "https://test-issuer.example.com".into(),
611        ));
612        let claims = CommonJwtClaims::new(
613            "https://test-issuer.example.com".into(),
614            "user".into(),
615            vec![],
616            (SystemTime::now()
617                .duration_since(UNIX_EPOCH)
618                .unwrap()
619                .as_secs()
620                + 3600) as i64,
621        );
622        let token = mgr1.create_token(&claims).unwrap();
623        assert!(mgr2.verify_token(&token).is_err());
624    }
625
626    // ── Specialized token creation ──────────────────────────────────────
627
628    #[test]
629    fn test_create_access_token() {
630        let mgr = make_manager();
631        let token = mgr
632            .create_access_token(
633                "user_1".into(),
634                vec!["read".into()],
635                Some("client_1".into()),
636            )
637            .unwrap();
638        let claims = mgr.verify_token(&token).unwrap();
639        assert_eq!(claims.sub, "user_1");
640        assert!(claims.custom.contains_key("scope"));
641    }
642
643    #[test]
644    fn test_create_refresh_token() {
645        let mgr = make_manager();
646        let token = mgr
647            .create_refresh_token("user_2".into(), "client_2".into())
648            .unwrap();
649        let claims = mgr.verify_token(&token).unwrap();
650        assert_eq!(claims.sub, "user_2");
651        assert_eq!(
652            claims.custom.get("token_type").unwrap(),
653            &serde_json::json!("refresh_token")
654        );
655    }
656
657    #[test]
658    fn test_create_id_token() {
659        let mgr = make_manager();
660        let user_info = HashMap::from([
661            ("name".into(), serde_json::json!("Test User")),
662            ("email".into(), serde_json::json!("test@example.com")),
663        ]);
664        let token = mgr
665            .create_id_token("user_3".into(), Some("nonce_123".into()), None, user_info)
666            .unwrap();
667        let claims = mgr.verify_token(&token).unwrap();
668        assert_eq!(claims.sub, "user_3");
669        assert_eq!(claims.custom.get("nonce").unwrap(), "nonce_123");
670        assert_eq!(
671            claims.custom.get("token_type").unwrap(),
672            &serde_json::json!("id_token")
673        );
674    }
675
676    // ── Utils ───────────────────────────────────────────────────────────
677
678    #[test]
679    fn test_extract_claims_unsafe_works() {
680        let mgr = make_manager();
681        let claims = CommonJwtClaims::new(
682            "https://test-issuer.example.com".into(),
683            "peek_user".into(),
684            vec![],
685            (SystemTime::now()
686                .duration_since(UNIX_EPOCH)
687                .unwrap()
688                .as_secs()
689                + 3600) as i64,
690        );
691        let token = mgr.create_token(&claims).unwrap();
692        let extracted = utils::extract_claims_unsafe(&token).unwrap();
693        assert_eq!(extracted["sub"], "peek_user");
694    }
695
696    #[test]
697    fn test_is_token_expired_not_expired() {
698        let mgr = make_manager();
699        let token = mgr
700            .create_access_token("user".into(), vec![], None)
701            .unwrap();
702        assert!(!utils::is_token_expired(&token).unwrap());
703    }
704}