1use crate::errors::{AuthError, Result, TokenError};
3use crate::providers::{OAuthProvider, ProfileExtractor, UserProfile};
4use chrono::{DateTime, Utc};
5use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
6use serde::{Deserialize, Serialize};
7#[cfg(feature = "postgres-storage")]
8use sqlx::FromRow;
9use std::collections::HashMap;
10use std::time::Duration;
11use uuid::Uuid;
12
13#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
15#[derive(Clone, Serialize, Deserialize)]
16pub struct AuthToken {
17 pub token_id: String,
19
20 pub user_id: String,
22
23 pub access_token: String,
25
26 pub token_type: Option<String>,
28
29 pub subject: Option<String>,
31
32 pub issuer: Option<String>,
34
35 pub refresh_token: Option<String>,
37
38 pub issued_at: DateTime<Utc>,
40
41 pub expires_at: DateTime<Utc>,
43
44 pub scopes: Vec<String>,
46
47 pub auth_method: String,
49
50 pub client_id: Option<String>,
52
53 pub user_profile: Option<UserProfile>,
55
56 pub permissions: Vec<String>,
58
59 pub roles: Vec<String>,
61
62 pub metadata: TokenMetadata,
64}
65
66impl std::fmt::Debug for AuthToken {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 let mut d = f.debug_struct("AuthToken");
69 d.field("token_id", &self.token_id);
70 d.field("user_id", &self.user_id);
71 d.field(
72 "access_token",
73 &crate::utils::redact::redacted(&self.access_token),
74 );
75 d.field("token_type", &self.token_type);
76 d.field("subject", &self.subject);
77 d.field("issuer", &self.issuer);
78 d.field(
79 "refresh_token",
80 &crate::utils::redact::redacted(&self.refresh_token),
81 );
82 d.field("issued_at", &self.issued_at);
83 d.field("expires_at", &self.expires_at);
84 d.field("scopes", &self.scopes);
85 d.field("auth_method", &self.auth_method);
86 d.field("client_id", &self.client_id);
87 d.field("user_profile", &self.user_profile);
88 d.field("permissions", &self.permissions);
89 d.field("roles", &self.roles);
90 d.field("metadata", &self.metadata);
91 d.finish()
92 }
93}
94
95#[derive(Clone, Serialize, Deserialize, Default)]
97pub struct TokenMetadata {
98 pub issued_ip: Option<String>,
100
101 pub user_agent: Option<String>,
103
104 pub device_id: Option<String>,
106
107 pub session_id: Option<String>,
109
110 pub revoked: bool,
112
113 pub revoked_at: Option<DateTime<Utc>>,
115
116 pub revoked_reason: Option<String>,
118
119 pub last_used: Option<DateTime<Utc>>,
121
122 pub use_count: u64,
124
125 pub custom: HashMap<String, serde_json::Value>,
127}
128
129impl std::fmt::Debug for TokenMetadata {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 let mut d = f.debug_struct("TokenMetadata");
132 d.field("issued_ip", &self.issued_ip);
133 d.field("user_agent", &self.user_agent);
134 d.field("device_id", &self.device_id);
135 d.field(
136 "session_id",
137 &crate::utils::redact::redacted(&self.session_id),
138 );
139 d.field("revoked", &self.revoked);
140 d.field("revoked_at", &self.revoked_at);
141 d.field("revoked_reason", &self.revoked_reason);
142 d.field("last_used", &self.last_used);
143 d.field("use_count", &self.use_count);
144 d.field("custom", &crate::utils::redact::redacted(&self.custom));
145 d.finish()
146 }
147}
148
149#[cfg(feature = "postgres-storage")]
150use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
151
152#[cfg(feature = "postgres-storage")]
153impl<'r> Decode<'r, Postgres> for TokenMetadata {
154 fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
155 let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
156 serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
157 }
158}
159
160#[cfg(feature = "postgres-storage")]
161impl Type<Postgres> for TokenMetadata {
162 fn type_info() -> sqlx::postgres::PgTypeInfo {
163 <serde_json::Value as Type<Postgres>>::type_info()
164 }
165 fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
166 <serde_json::Value as Type<Postgres>>::compatible(ty)
167 }
168}
169
170#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct TokenInfo {
173 pub user_id: String,
175
176 pub username: Option<String>,
178
179 pub email: Option<String>,
181
182 pub name: Option<String>,
184
185 pub roles: Vec<String>,
187
188 pub permissions: Vec<String>,
190
191 pub attributes: HashMap<String, serde_json::Value>,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct JwtClaims {
198 pub sub: String,
200
201 pub iss: String,
203
204 pub aud: String,
206
207 pub exp: i64,
209
210 pub iat: i64,
212
213 pub nbf: i64,
215
216 pub jti: String,
218
219 pub scope: String,
221
222 pub permissions: Option<Vec<String>>,
224
225 pub roles: Option<Vec<String>>,
227
228 pub client_id: Option<String>,
230
231 #[serde(flatten)]
233 pub custom: HashMap<String, serde_json::Value>,
234}
235
236impl JwtClaims {
237 pub const TOKEN_USE_CLAIM: &'static str = "token_use";
239 pub const TOKEN_USE_REFRESH: &'static str = "refresh";
241
242 pub fn is_refresh_token(&self) -> bool {
246 self.custom
247 .get(Self::TOKEN_USE_CLAIM)
248 .and_then(|v| v.as_str())
249 == Some(Self::TOKEN_USE_REFRESH)
250 }
251}
252
253pub struct TokenManager {
255 encoding_key: EncodingKey,
257
258 decoding_key: DecodingKey,
260
261 key_material: KeyMaterial,
263
264 algorithm: Algorithm,
266
267 issuer: String,
269
270 audience: String,
272
273 default_lifetime: Duration,
275}
276
277#[derive(Clone)]
279enum KeyMaterial {
280 Hmac(Vec<u8>),
282 Rsa { private: Vec<u8>, public: Vec<u8> },
284}
285
286impl AuthToken {
287 pub fn new(
289 user_id: impl Into<String>,
290 access_token: impl Into<String>,
291 expires_in: std::time::Duration,
292 auth_method: impl Into<String>,
293 ) -> Self {
294 let now = Utc::now();
295 let expires_in_chrono =
296 chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
297
298 Self {
299 token_id: Uuid::new_v4().to_string(),
300 user_id: user_id.into(),
301 access_token: access_token.into(),
302 refresh_token: None,
303 token_type: Some("Bearer".to_string()),
304 subject: None,
305 issuer: None,
306 issued_at: now,
307 expires_at: now + expires_in_chrono,
308 scopes: Vec::new(),
309 auth_method: auth_method.into(),
310 client_id: None,
311 user_profile: None,
312 permissions: Vec::new(),
313 roles: Vec::new(),
314 metadata: TokenMetadata::default(),
315 }
316 }
317
318 pub fn access_token(&self) -> &str {
320 &self.access_token
321 }
322
323 pub fn user_id(&self) -> &str {
325 &self.user_id
326 }
327
328 pub fn expires_at(&self) -> DateTime<Utc> {
330 self.expires_at
331 }
332
333 pub fn token_value(&self) -> &str {
335 &self.access_token
336 }
337
338 pub fn token_type(&self) -> Option<&str> {
340 self.token_type.as_deref()
341 }
342
343 pub fn subject(&self) -> Option<&str> {
345 self.subject.as_deref()
346 }
347
348 pub fn issuer(&self) -> Option<&str> {
350 self.issuer.as_deref()
351 }
352
353 pub fn is_expired(&self) -> bool {
355 Utc::now() > self.expires_at
356 }
357
358 pub fn is_expiring(&self, within: Duration) -> bool {
360 Utc::now() + within > self.expires_at
361 }
362
363 pub fn is_revoked(&self) -> bool {
365 self.metadata.revoked
366 }
367
368 pub fn is_valid(&self) -> bool {
370 !self.is_expired() && !self.is_revoked()
371 }
372
373 pub fn revoke(&mut self, reason: Option<String>) {
375 self.metadata.revoked = true;
376 self.metadata.revoked_at = Some(Utc::now());
377 self.metadata.revoked_reason = reason;
378 }
379
380 pub fn mark_used(&mut self) {
382 self.metadata.last_used = Some(Utc::now());
383 self.metadata.use_count += 1;
384 }
385
386 pub fn add_scope(&mut self, scope: impl Into<String>) {
388 let scope = scope.into();
389 if !self.scopes.contains(&scope) {
390 self.scopes.push(scope);
391 }
392 }
393
394 pub fn has_scope(&self, scope: &str) -> bool {
396 self.scopes.contains(&scope.to_string())
397 }
398
399 pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
401 self.refresh_token = Some(refresh_token.into());
402 self
403 }
404
405 pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
407 self.client_id = Some(client_id.into());
408 self
409 }
410
411 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
413 self.scopes = scopes;
414 self
415 }
416
417 pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
419 self.metadata = metadata;
420 self
421 }
422
423 pub fn time_until_expiry(&self) -> Duration {
425 let now = Utc::now();
426 if self.expires_at > now {
427 (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
428 } else {
429 Duration::ZERO
430 }
431 }
432
433 pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
435 self.metadata.custom.insert(key.into(), value);
436 }
437
438 pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
440 self.metadata.custom.get(key)
441 }
442
443 pub fn has_permission(&self, permission: &str) -> bool {
445 self.permissions.contains(&permission.to_string())
446 }
447
448 pub fn add_permission(&mut self, permission: impl Into<String>) {
450 let permission = permission.into();
451 if !self.permissions.contains(&permission) {
452 self.permissions.push(permission);
453 }
454 }
455
456 pub fn add_role(&mut self, role: impl Into<String>) {
458 let role = role.into();
459 if !self.roles.contains(&role) {
460 self.roles.push(role);
461 }
462 }
463
464 pub fn has_role(&self, role: &str) -> bool {
466 self.roles.contains(&role.to_string())
467 }
468
469 pub fn with_permissions(mut self, permissions: Vec<String>) -> Self {
471 self.permissions = permissions;
472 self
473 }
474
475 pub fn with_roles(mut self, roles: Vec<String>) -> Self {
477 self.roles = roles;
478 self
479 }
480}
481
482impl Clone for TokenManager {
483 fn clone(&self) -> Self {
484 match &self.key_material {
485 KeyMaterial::Hmac(secret) => Self {
486 encoding_key: EncodingKey::from_secret(secret),
487 decoding_key: DecodingKey::from_secret(secret),
488 key_material: self.key_material.clone(),
489 algorithm: self.algorithm,
490 issuer: self.issuer.clone(),
491 audience: self.audience.clone(),
492 default_lifetime: self.default_lifetime,
493 },
494 KeyMaterial::Rsa { private, public } => Self {
495 encoding_key: EncodingKey::from_rsa_pem(private).expect("Valid RSA private key"),
496 decoding_key: DecodingKey::from_rsa_pem(public).expect("Valid RSA public key"),
497 key_material: self.key_material.clone(),
498 algorithm: self.algorithm,
499 issuer: self.issuer.clone(),
500 audience: self.audience.clone(),
501 default_lifetime: self.default_lifetime,
502 },
503 }
504 }
505}
506
507impl TokenManager {
508 pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
510 Self {
511 encoding_key: EncodingKey::from_secret(secret),
512 decoding_key: DecodingKey::from_secret(secret),
513 key_material: KeyMaterial::Hmac(secret.to_vec()),
514 algorithm: Algorithm::HS256,
515 issuer: issuer.into(),
516 audience: audience.into(),
517 default_lifetime: Duration::from_secs(3600), }
519 }
520
521 pub fn new_rsa(
549 private_key: &[u8],
550 public_key: &[u8],
551 issuer: impl Into<String>,
552 audience: impl Into<String>,
553 ) -> Result<Self> {
554 let encoding_key = EncodingKey::from_rsa_pem(private_key)
555 .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
556
557 let decoding_key = DecodingKey::from_rsa_pem(public_key)
558 .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
559
560 Ok(Self {
561 encoding_key,
562 decoding_key,
563 key_material: KeyMaterial::Rsa {
564 private: private_key.to_vec(),
565 public: public_key.to_vec(),
566 },
567 algorithm: Algorithm::RS256,
568 issuer: issuer.into(),
569 audience: audience.into(),
570 default_lifetime: Duration::from_secs(3600), })
572 }
573
574 pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
576 self.default_lifetime = lifetime;
577 self
578 }
579
580 pub fn create_jwt_token(
582 &self,
583 user_id: impl Into<String>,
584 scopes: Vec<String>,
585 lifetime: Option<Duration>,
586 ) -> Result<String> {
587 self.encode_jwt(user_id.into(), scopes, lifetime, None, None)
588 }
589
590 pub fn create_client_jwt_token(
593 &self,
594 user_id: impl Into<String>,
595 client_id: impl AsRef<str>,
596 scopes: Vec<String>,
597 lifetime: Option<Duration>,
598 ) -> Result<String> {
599 self.encode_jwt(
600 user_id.into(),
601 scopes,
602 lifetime,
603 None,
604 Some(client_id.as_ref()),
605 )
606 }
607
608 pub fn create_refresh_jwt_token(
611 &self,
612 user_id: impl Into<String>,
613 lifetime: Option<Duration>,
614 ) -> Result<String> {
615 self.encode_jwt(
616 user_id.into(),
617 vec!["refresh".to_string()],
618 lifetime,
619 Some(JwtClaims::TOKEN_USE_REFRESH),
620 None,
621 )
622 }
623
624 fn encode_jwt(
625 &self,
626 user_id: String,
627 scopes: Vec<String>,
628 lifetime: Option<Duration>,
629 token_use: Option<&str>,
630 client_id: Option<&str>,
631 ) -> Result<String> {
632 let lifetime = lifetime.unwrap_or(self.default_lifetime);
633 let now = Utc::now();
634 let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
635
636 let mut custom = HashMap::new();
637 if let Some(token_use) = token_use {
638 custom.insert(
639 JwtClaims::TOKEN_USE_CLAIM.to_string(),
640 serde_json::Value::String(token_use.to_string()),
641 );
642 }
643 let claims = JwtClaims {
644 sub: user_id,
645 iss: self.issuer.clone(),
646 aud: self.audience.clone(),
647 exp: exp.timestamp(),
648 iat: now.timestamp(),
649 nbf: now.timestamp(),
650 jti: Uuid::new_v4().to_string(),
651 scope: scopes.join(" "),
652 permissions: None,
653 roles: None,
654 client_id: client_id.map(String::from),
655 custom,
656 };
657
658 let header = Header::new(self.algorithm);
659
660 encode(&header, &claims, &self.encoding_key)
661 .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
662 }
663
664 pub fn validate_session_jwt_token(&self, token: &str) -> Result<JwtClaims> {
668 let claims = self.validate_jwt_token(token)?;
669 if claims.client_id.is_some() {
670 return Err(AuthError::Token(TokenError::Invalid {
671 message: "Token was issued to an OAuth client and is not a user session"
672 .to_string(),
673 }));
674 }
675 Ok(claims)
676 }
677
678 pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
680 let mut validation = Validation::new(self.algorithm);
681 validation.set_issuer(&[&self.issuer]);
682 validation.set_audience(&[&self.audience]);
683
684 let token_data =
685 decode::<JwtClaims>(token, &self.decoding_key, &validation).map_err(|e| {
686 match e.kind() {
687 jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
688 AuthError::Token(TokenError::Expired)
689 }
690 kind => {
691 tracing::debug!(cause = ?kind, "JWT validation failed");
694 AuthError::Token(TokenError::Invalid {
695 message: "Invalid token format".to_string(),
696 })
697 }
698 }
699 })?;
700
701 Ok(token_data.claims)
702 }
703
704 pub fn create_auth_token(
706 &self,
707 user_id: impl Into<String>,
708 scopes: Vec<String>,
709 auth_method: impl Into<String>,
710 lifetime: Option<std::time::Duration>,
711 ) -> Result<AuthToken> {
712 let user_id_str = user_id.into();
713 let lifetime = lifetime.unwrap_or(self.default_lifetime);
714
715 let jwt_token = self.create_jwt_token(&user_id_str, scopes.clone(), Some(lifetime))?;
716
717 let token =
718 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
719
720 Ok(token)
721 }
722
723 pub fn create_client_auth_token(
726 &self,
727 user_id: impl Into<String>,
728 client_id: impl Into<String>,
729 scopes: Vec<String>,
730 auth_method: impl Into<String>,
731 lifetime: Option<std::time::Duration>,
732 ) -> Result<AuthToken> {
733 let user_id_str = user_id.into();
734 let client_id = client_id.into();
735 let lifetime = lifetime.unwrap_or(self.default_lifetime);
736
737 let jwt_token =
738 self.create_client_jwt_token(&user_id_str, &client_id, scopes.clone(), Some(lifetime))?;
739
740 Ok(
741 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method)
742 .with_scopes(scopes)
743 .with_client_id(client_id),
744 )
745 }
746
747 pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
749 if token.is_expired() {
751 return Err(TokenError::Expired.into());
752 }
753
754 if token.is_revoked() {
756 return Err(TokenError::Invalid {
757 message: "Token has been revoked".to_string(),
758 }
759 .into());
760 }
761
762 if token.auth_method == "jwt" || token.access_token.contains('.') {
764 self.validate_jwt_token(&token.access_token)?;
765 }
766
767 Ok(())
768 }
769
770 pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
772 if token.is_expired() {
773 return Err(TokenError::Expired.into());
774 }
775
776 if token.is_revoked() {
777 return Err(TokenError::Invalid {
778 message: "Cannot refresh revoked token".to_string(),
779 }
780 .into());
781 }
782
783 if let Some(client_id) = &token.client_id {
785 return self.create_client_auth_token(
786 &token.user_id,
787 client_id,
788 token.scopes.clone(),
789 &token.auth_method,
790 Some(self.default_lifetime),
791 );
792 }
793 self.create_auth_token(
794 &token.user_id,
795 token.scopes.clone(),
796 &token.auth_method,
797 Some(self.default_lifetime),
798 )
799 }
800
801 pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
803 let claims = self.validate_jwt_token(token)?;
804
805 Ok(TokenInfo {
806 user_id: claims.sub,
807 username: claims
808 .custom
809 .get("username")
810 .and_then(|v| v.as_str())
811 .map(|s| s.to_string()),
812 email: claims
813 .custom
814 .get("email")
815 .and_then(|v| v.as_str())
816 .map(|s| s.to_string()),
817 name: claims
818 .custom
819 .get("name")
820 .and_then(|v| v.as_str())
821 .map(|s| s.to_string()),
822 roles: claims
823 .custom
824 .get("roles")
825 .and_then(|v| v.as_array())
826 .map(|arr| {
827 arr.iter()
828 .filter_map(|v| v.as_str())
829 .map(|s| s.to_string())
830 .collect()
831 })
832 .unwrap_or_default(),
833 permissions: claims
834 .scope
835 .split_whitespace()
836 .map(|s| s.to_string())
837 .collect(),
838 attributes: claims.custom,
839 })
840 }
841}
842
843#[async_trait::async_trait]
845pub trait TokenToProfile {
846 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
848
849 async fn to_profile_with_extractor(
851 &self,
852 provider: &OAuthProvider,
853 extractor: &ProfileExtractor,
854 ) -> Result<UserProfile>;
855}
856
857#[async_trait::async_trait]
858impl TokenToProfile for AuthToken {
859 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile> {
860 let extractor = ProfileExtractor::new();
861 extractor.extract_profile(self, provider).await
862 }
863
864 async fn to_profile_with_extractor(
865 &self,
866 provider: &OAuthProvider,
867 extractor: &ProfileExtractor,
868 ) -> Result<UserProfile> {
869 extractor.extract_profile(self, provider).await
870 }
871}
872
873#[cfg(test)]
874mod tests {
875 use super::*;
876
877 #[test]
878 fn test_auth_token_creation() {
879 let token = AuthToken::new(
880 "user123",
881 "token123",
882 Duration::from_secs(3600), "password",
884 );
885
886 assert_eq!(token.user_id(), "user123");
887 assert_eq!(token.access_token(), "token123");
888 assert!(!token.is_expired());
889 assert!(!token.is_revoked());
890 assert!(token.is_valid());
891 }
892
893 #[test]
894 fn test_token_expiry() {
895 let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
896
897 std::thread::sleep(std::time::Duration::from_millis(10));
899
900 assert!(token.is_expired());
901 assert!(!token.is_valid());
902 }
903
904 #[test]
905 fn test_token_revocation() {
906 let mut token = AuthToken::new(
907 "user123",
908 "token123",
909 Duration::from_secs(3600), "password",
911 );
912
913 assert!(!token.is_revoked());
914
915 token.revoke(Some("User logout".to_string()));
916
917 assert!(token.is_revoked());
918 assert!(!token.is_valid());
919 assert!(token.metadata.revoked);
920 }
921}