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
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 #[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 #[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 #[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 #[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 }