1use 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#[derive(Clone)]
15pub struct JwtConfig {
16 pub algorithm: Algorithm,
18 pub signing_key: EncodingKey,
20 pub verification_key: DecodingKey,
22 pub default_expiration: u64,
24 pub issuer: String,
26 pub audiences: Vec<String>,
28}
29
30impl JwtConfig {
31 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, issuer,
39 audiences: vec![],
40 }
41 }
42
43 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, issuer,
57 audiences: vec![],
58 })
59 }
60
61 pub fn with_audience(mut self, audience: String) -> Self {
63 self.audiences.push(audience);
64 self
65 }
66
67 pub fn with_expiration(mut self, expiration: u64) -> Self {
69 self.default_expiration = expiration;
70 self
71 }
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct CommonJwtClaims {
77 pub iss: String,
79 pub sub: String,
81 #[serde(default, skip_serializing_if = "Vec::is_empty")]
88 pub aud: Vec<String>,
89 pub exp: i64,
91 pub iat: i64,
93 pub nbf: Option<i64>,
95 pub jti: Option<String>,
97 #[serde(flatten)]
99 pub custom: HashMap<String, serde_json::Value>,
100}
101
102impl CommonJwtClaims {
103 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 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 pub fn with_jti(mut self, jti: String) -> Self {
130 self.jti = Some(jti);
131 self
132 }
133
134 pub fn with_nbf(mut self, nbf: i64) -> Self {
136 self.nbf = Some(nbf);
137 self
138 }
139}
140
141pub struct JwtManager {
223 config: JwtConfig,
224}
225
226impl JwtManager {
227 pub fn new(config: JwtConfig) -> Self {
229 Self { config }
230 }
231
232 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 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 pub fn verify_token(&self, token: &str) -> Result<CommonJwtClaims> {
259 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 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 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 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 pub fn create_refresh_token(&self, subject: String, client_id: String) -> Result<String> {
357 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; 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 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; 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 for (key, value) in user_info {
424 claims.custom.insert(key, value);
425 }
426
427 self.create_token(&claims)
428 }
429}
430
431pub(crate) mod utils {
433 use super::*;
434
435 #[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 #[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) }
469 }
470
471 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}