auth-framework 0.6.0-rc217

A comprehensive, production-ready authentication and authorization framework for Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
//! Common JWT Operations
//!
//! This module provides shared JWT functionality to eliminate
//! duplication across server modules.

use crate::errors::{AuthError, Result};
use crate::server::core::common_validation;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

/// Common JWT configuration
#[derive(Clone)]
pub struct JwtConfig {
    /// Signing algorithm
    pub algorithm: Algorithm,
    /// Signing key
    pub signing_key: EncodingKey,
    /// Verification key
    pub verification_key: DecodingKey,
    /// Default expiration time in seconds
    pub default_expiration: u64,
    /// Issuer
    pub issuer: String,
    /// Audiences
    pub audiences: Vec<String>,
}

impl JwtConfig {
    /// Create new JWT config with symmetric key
    pub fn with_symmetric_key(secret: &[u8], issuer: String) -> Self {
        Self {
            algorithm: Algorithm::HS256,
            signing_key: EncodingKey::from_secret(secret),
            verification_key: DecodingKey::from_secret(secret),
            default_expiration: 3600, // 1 hour
            issuer,
            audiences: vec![],
        }
    }

    /// Create new JWT config with RSA keys
    pub fn with_rsa_keys(private_key: &[u8], public_key: &[u8], issuer: String) -> Result<Self> {
        let signing_key = EncodingKey::from_rsa_pem(private_key)
            .map_err(|e| AuthError::validation(format!("Invalid private key: {}", e)))?;

        let verification_key = DecodingKey::from_rsa_pem(public_key)
            .map_err(|e| AuthError::validation(format!("Invalid public key: {}", e)))?;

        Ok(Self {
            algorithm: Algorithm::RS256,
            signing_key,
            verification_key,
            default_expiration: 3600, // 1 hour
            issuer,
            audiences: vec![],
        })
    }

    /// Add audience
    pub fn with_audience(mut self, audience: String) -> Self {
        self.audiences.push(audience);
        self
    }

    /// Set expiration time
    pub fn with_expiration(mut self, expiration: u64) -> Self {
        self.default_expiration = expiration;
        self
    }
}

/// Common JWT claims structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommonJwtClaims {
    /// Issuer
    pub iss: String,
    /// Subject
    pub sub: String,
    /// Audience. Omitted from the serialized token when empty -- RFC 7519
    /// treats `aud` as an intended-recipient claim, and an empty array is
    /// not a meaningful value for it. jsonwebtoken 10.4.0+ validates a
    /// present `aud` even when the verifier configured no expected
    /// audience, so previously we issued tokens that could fail
    /// verification for a reason unrelated to any real audience mismatch.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aud: Vec<String>,
    /// Expiration time
    pub exp: i64,
    /// Issued at
    pub iat: i64,
    /// Not before
    pub nbf: Option<i64>,
    /// JWT ID
    pub jti: Option<String>,
    /// Custom claims
    #[serde(flatten)]
    pub custom: HashMap<String, serde_json::Value>,
}

impl CommonJwtClaims {
    /// Create new claims with required fields
    pub fn new(issuer: String, subject: String, audiences: Vec<String>, expiration: i64) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;

        Self {
            iss: issuer,
            sub: subject,
            aud: audiences,
            exp: expiration,
            iat: now,
            nbf: None,
            jti: None,
            custom: HashMap::new(),
        }
    }

    /// Add custom claim
    pub fn with_custom_claim(mut self, key: String, value: serde_json::Value) -> Self {
        self.custom.insert(key, value);
        self
    }

    /// Set JWT ID
    pub fn with_jti(mut self, jti: String) -> Self {
        self.jti = Some(jti);
        self
    }

    /// Set not before
    pub fn with_nbf(mut self, nbf: i64) -> Self {
        self.nbf = Some(nbf);
        self
    }
}

/// Common JWT token management for OAuth 2.0 and OpenID Connect operations.
///
/// `JwtManager` provides comprehensive JWT token creation, verification, and
/// management capabilities specifically designed for OAuth 2.0 authorization
/// servers and OpenID Connect providers. It supports both symmetric and
/// asymmetric signing algorithms with security best practices.
///
/// # Supported Algorithms
///
/// - **HMAC**: HS256, HS384, HS512 (symmetric)
/// - **RSA**: RS256, RS384, RS512 (asymmetric)
/// - **ECDSA**: ES256, ES384, ES512 (asymmetric)
/// - **EdDSA**: EdDSA (asymmetric, Ed25519)
///
/// # Security Features
///
/// - **Algorithm Validation**: Prevents algorithm confusion attacks
/// - **Time Validation**: Automatic `exp`, `nbf`, and `iat` claim validation
/// - **Audience Validation**: Ensures tokens are used by intended recipients
/// - **Issuer Validation**: Verifies token origin
/// - **Secure Defaults**: Uses secure algorithm choices and expiration times
///
/// # Token Types Supported
///
/// - **Access Tokens**: OAuth 2.0 access tokens with scopes
/// - **ID Tokens**: OpenID Connect identity tokens
/// - **Refresh Tokens**: Long-lived tokens for access token renewal
/// - **Custom Tokens**: Application-specific token types
///
/// # Key Management
///
/// - **Symmetric Keys**: HMAC-based signing with shared secrets
/// - **RSA Keys**: Support for PKCS#1 and PKCS#8 key formats
/// - **Key Rotation**: Support for multiple signing keys
/// - **Key Security**: Secure key storage and access patterns
///
/// # Example
///
/// ```rust,no_run
/// use auth_framework::server::core::common_jwt::{JwtManager, JwtConfig, CommonJwtClaims};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # let private_key_bytes: &[u8] = unimplemented!();
/// # let public_key_bytes: &[u8] = unimplemented!();
/// # let expiration_time: i64 = unimplemented!();
/// // Create JWT manager with RSA keys
/// let config = JwtConfig::with_rsa_keys(
///     private_key_bytes,
///     public_key_bytes,
///     "https://auth.example.com".to_string()
/// )?;
/// let jwt_manager = JwtManager::new(config);
///
/// // Create access token
/// let claims = CommonJwtClaims::new(
///     "https://auth.example.com".to_string(),
///     "user123".to_string(),
///     vec!["api".to_string()],
///     expiration_time
/// ).with_custom_claim("scope".to_string(), serde_json::json!("read write"));
///
/// let token = jwt_manager.create_token(&claims)?;
///
/// // Verify token
/// let verified_claims = jwt_manager.verify_token(&token)?;
/// # Ok(())
/// # }
/// ```
///
/// # Performance Considerations
///
/// - Asymmetric algorithms are more computationally expensive
/// - Token verification is optimized for high-throughput scenarios
/// - Key caching reduces cryptographic operation overhead
///
/// # RFC Compliance
///
/// - **RFC 7519**: JSON Web Token (JWT)
/// - **RFC 7515**: JSON Web Signature (JWS)
/// - **RFC 8725**: JWT Best Current Practices
/// - **RFC 9068**: JWT Profile for OAuth 2.0 Access Tokens
pub struct JwtManager {
    config: JwtConfig,
}

impl JwtManager {
    /// Create new JWT manager
    pub fn new(config: JwtConfig) -> Self {
        Self { config }
    }

    /// Create signed JWT token
    pub fn create_token(&self, claims: &CommonJwtClaims) -> Result<String> {
        let header = Header {
            alg: self.config.algorithm,
            ..Default::default()
        };

        encode(&header, claims, &self.config.signing_key)
            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
    }

    /// Create signed token with custom claims
    pub fn create_token_with_custom_claims<T>(&self, claims: &T) -> Result<String>
    where
        T: Serialize,
    {
        let header = Header {
            alg: self.config.algorithm,
            ..Default::default()
        };

        encode(&header, claims, &self.config.signing_key)
            .map_err(|e| AuthError::validation(format!("Failed to encode JWT: {}", e)))
    }

    /// Verify and decode JWT token
    pub fn verify_token(&self, token: &str) -> Result<CommonJwtClaims> {
        // Basic format validation
        common_validation::jwt::validate_jwt_format(token)?;

        let mut validation = Validation::new(self.config.algorithm);
        validation.set_issuer(&[&self.config.issuer]);

        if !self.config.audiences.is_empty() {
            validation.set_audience(
                &self
                    .config
                    .audiences
                    .iter()
                    .map(String::as_str)
                    .collect::<Vec<_>>(),
            );
        }

        let token_data =
            decode::<CommonJwtClaims>(token, &self.config.verification_key, &validation)
                .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;

        // Additional validation using common validation utilities
        let claims_value = serde_json::to_value(&token_data.claims)
            .map_err(|e| AuthError::validation(format!("Failed to serialize claims: {}", e)))?;

        common_validation::jwt::validate_time_claims(&claims_value)?;

        Ok(token_data.claims)
    }

    /// Verify token and extract custom claims
    pub fn verify_token_with_custom_claims<T>(&self, token: &str) -> Result<T>
    where
        T: for<'de> Deserialize<'de>,
    {
        common_validation::jwt::validate_jwt_format(token)?;

        let mut validation = Validation::new(self.config.algorithm);
        validation.set_issuer(&[&self.config.issuer]);

        if !self.config.audiences.is_empty() {
            validation.set_audience(
                &self
                    .config
                    .audiences
                    .iter()
                    .map(String::as_str)
                    .collect::<Vec<_>>(),
            );
        }

        let token_data = decode::<T>(token, &self.config.verification_key, &validation)
            .map_err(|e| AuthError::validation(format!("Invalid JWT: {}", e)))?;

        Ok(token_data.claims)
    }

    /// Create access token with standard claims
    pub fn create_access_token(
        &self,
        subject: String,
        scope: Vec<String>,
        client_id: Option<String>,
    ) -> Result<String> {
        let exp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64
            + self.config.default_expiration as i64;

        let mut claims = CommonJwtClaims::new(
            self.config.issuer.clone(),
            subject,
            self.config.audiences.clone(),
            exp,
        );

        claims
            .custom
            .insert("scope".to_string(), serde_json::json!(scope.join(" ")));

        if let Some(client_id) = client_id {
            claims.custom.insert(
                "client_id".to_string(),
                serde_json::Value::String(client_id),
            );
        }

        claims.custom.insert(
            "token_type".to_string(),
            serde_json::Value::String("access_token".to_string()),
        );

        self.create_token(&claims)
    }

    /// Create refresh token
    pub fn create_refresh_token(&self, subject: String, client_id: String) -> Result<String> {
        // Refresh tokens typically have longer expiration
        let exp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64
            + (self.config.default_expiration * 24) as i64; // 24x longer

        let mut claims = CommonJwtClaims::new(
            self.config.issuer.clone(),
            subject,
            self.config.audiences.clone(),
            exp,
        );

        claims.custom.insert(
            "client_id".to_string(),
            serde_json::Value::String(client_id),
        );
        claims.custom.insert(
            "token_type".to_string(),
            serde_json::Value::String("refresh_token".to_string()),
        );

        self.create_token(&claims)
    }

    /// Create ID token for OpenID Connect
    pub fn create_id_token(
        &self,
        subject: String,
        nonce: Option<String>,
        auth_time: Option<i64>,
        user_info: HashMap<String, serde_json::Value>,
    ) -> Result<String> {
        let exp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64
            + 300; // 5 minutes for ID token

        let mut claims = CommonJwtClaims::new(
            self.config.issuer.clone(),
            subject,
            self.config.audiences.clone(),
            exp,
        );

        claims.custom.insert(
            "token_type".to_string(),
            serde_json::Value::String("id_token".to_string()),
        );

        if let Some(nonce) = nonce {
            claims
                .custom
                .insert("nonce".to_string(), serde_json::Value::String(nonce));
        }

        if let Some(auth_time) = auth_time {
            claims.custom.insert(
                "auth_time".to_string(),
                serde_json::Value::Number(auth_time.into()),
            );
        }

        // Add user info claims
        for (key, value) in user_info {
            claims.custom.insert(key, value);
        }

        self.create_token(&claims)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_manager() -> JwtManager {
        let config = JwtConfig::with_symmetric_key(
            b"a-test-secret-key-with-enough-bytes-for-hmac",
            "https://test-issuer.example.com".into(),
        );
        JwtManager::new(config)
    }

    // ── JwtConfig ───────────────────────────────────────────────────────

    #[test]
    fn test_jwt_config_symmetric() {
        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into());
        assert_eq!(config.issuer, "iss");
        assert_eq!(config.default_expiration, 3600);
    }

    #[test]
    fn test_jwt_config_with_audience() {
        let config =
            JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_audience("aud1".into());
        assert_eq!(config.audiences, vec!["aud1"]);
    }

    #[test]
    fn test_jwt_config_with_expiration() {
        let config = JwtConfig::with_symmetric_key(b"secret", "iss".into()).with_expiration(7200);
        assert_eq!(config.default_expiration, 7200);
    }

    // ── CommonJwtClaims ─────────────────────────────────────────────────

    #[test]
    fn test_claims_new() {
        let claims = CommonJwtClaims::new(
            "issuer".into(),
            "subject".into(),
            vec!["aud".into()],
            9999999999,
        );
        assert_eq!(claims.iss, "issuer");
        assert_eq!(claims.sub, "subject");
        assert!(claims.iat > 0);
    }

    #[test]
    fn test_claims_with_custom_claim() {
        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
            .with_custom_claim("role".to_string(), serde_json::json!("admin"));
        assert_eq!(claims.custom.get("role").unwrap(), "admin");
    }

    #[test]
    fn test_claims_with_jti() {
        let claims = CommonJwtClaims::new("iss".into(), "sub".into(), vec![], 9999999999)
            .with_jti("test-jti-value".into());
        assert!(claims.jti.is_some());
    }

    // ── JwtManager create/verify ────────────────────────────────────────

    #[test]
    fn test_create_and_verify_token() {
        let mgr = make_manager();
        let claims = CommonJwtClaims::new(
            "https://test-issuer.example.com".into(),
            "user_123".into(),
            vec![],
            (SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                + 3600) as i64,
        );
        let token = mgr.create_token(&claims).unwrap();
        let verified = mgr.verify_token(&token).unwrap();
        assert_eq!(verified.sub, "user_123");
    }

    #[test]
    fn test_verify_invalid_token() {
        let mgr = make_manager();
        assert!(mgr.verify_token("not.a.valid.jwt").is_err());
    }

    #[test]
    fn test_verify_wrong_key() {
        let mgr1 = make_manager();
        let mgr2 = JwtManager::new(JwtConfig::with_symmetric_key(
            b"different-key-entirely-for-testing",
            "https://test-issuer.example.com".into(),
        ));
        let claims = CommonJwtClaims::new(
            "https://test-issuer.example.com".into(),
            "user".into(),
            vec![],
            (SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                + 3600) as i64,
        );
        let token = mgr1.create_token(&claims).unwrap();
        assert!(mgr2.verify_token(&token).is_err());
    }

    // ── Specialized token creation ──────────────────────────────────────

    #[test]
    fn test_create_access_token() {
        let mgr = make_manager();
        let token = mgr
            .create_access_token(
                "user_1".into(),
                vec!["read".into()],
                Some("client_1".into()),
            )
            .unwrap();
        let claims = mgr.verify_token(&token).unwrap();
        assert_eq!(claims.sub, "user_1");
        assert!(claims.custom.contains_key("scope"));
    }

    #[test]
    fn test_create_refresh_token() {
        let mgr = make_manager();
        let token = mgr
            .create_refresh_token("user_2".into(), "client_2".into())
            .unwrap();
        let claims = mgr.verify_token(&token).unwrap();
        assert_eq!(claims.sub, "user_2");
        assert_eq!(
            claims.custom.get("token_type").unwrap(),
            &serde_json::json!("refresh_token")
        );
    }

    #[test]
    fn test_create_id_token() {
        let mgr = make_manager();
        let user_info = HashMap::from([
            ("name".into(), serde_json::json!("Test User")),
            ("email".into(), serde_json::json!("test@example.com")),
        ]);
        let token = mgr
            .create_id_token("user_3".into(), Some("nonce_123".into()), None, user_info)
            .unwrap();
        let claims = mgr.verify_token(&token).unwrap();
        assert_eq!(claims.sub, "user_3");
        assert_eq!(claims.custom.get("nonce").unwrap(), "nonce_123");
        assert_eq!(
            claims.custom.get("token_type").unwrap(),
            &serde_json::json!("id_token")
        );
    }

    // ── Utils ───────────────────────────────────────────────────────────
}