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)
588 }
589
590 pub fn create_refresh_jwt_token(
593 &self,
594 user_id: impl Into<String>,
595 lifetime: Option<Duration>,
596 ) -> Result<String> {
597 self.encode_jwt(
598 user_id.into(),
599 vec!["refresh".to_string()],
600 lifetime,
601 Some(JwtClaims::TOKEN_USE_REFRESH),
602 )
603 }
604
605 fn encode_jwt(
606 &self,
607 user_id: String,
608 scopes: Vec<String>,
609 lifetime: Option<Duration>,
610 token_use: Option<&str>,
611 ) -> Result<String> {
612 let lifetime = lifetime.unwrap_or(self.default_lifetime);
613 let now = Utc::now();
614 let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
615
616 let mut custom = HashMap::new();
617 if let Some(token_use) = token_use {
618 custom.insert(
619 JwtClaims::TOKEN_USE_CLAIM.to_string(),
620 serde_json::Value::String(token_use.to_string()),
621 );
622 }
623 let claims = JwtClaims {
624 sub: user_id,
625 iss: self.issuer.clone(),
626 aud: self.audience.clone(),
627 exp: exp.timestamp(),
628 iat: now.timestamp(),
629 nbf: now.timestamp(),
630 jti: Uuid::new_v4().to_string(),
631 scope: scopes.join(" "),
632 permissions: None,
633 roles: None,
634 client_id: None,
635 custom,
636 };
637
638 let header = Header::new(self.algorithm);
639
640 encode(&header, &claims, &self.encoding_key)
641 .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
642 }
643
644 pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
646 let mut validation = Validation::new(self.algorithm);
647 validation.set_issuer(&[&self.issuer]);
648 validation.set_audience(&[&self.audience]);
649
650 let token_data =
651 decode::<JwtClaims>(token, &self.decoding_key, &validation).map_err(|e| {
652 match e.kind() {
653 jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
654 AuthError::Token(TokenError::Expired)
655 }
656 kind => {
657 tracing::debug!(cause = ?kind, "JWT validation failed");
660 AuthError::Token(TokenError::Invalid {
661 message: "Invalid token format".to_string(),
662 })
663 }
664 }
665 })?;
666
667 Ok(token_data.claims)
668 }
669
670 pub fn create_auth_token(
672 &self,
673 user_id: impl Into<String>,
674 scopes: Vec<String>,
675 auth_method: impl Into<String>,
676 lifetime: Option<std::time::Duration>,
677 ) -> Result<AuthToken> {
678 let user_id_str = user_id.into();
679 let lifetime = lifetime.unwrap_or(self.default_lifetime);
680
681 let jwt_token = self.create_jwt_token(&user_id_str, scopes.clone(), Some(lifetime))?;
682
683 let token =
684 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
685
686 Ok(token)
687 }
688
689 pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
691 if token.is_expired() {
693 return Err(TokenError::Expired.into());
694 }
695
696 if token.is_revoked() {
698 return Err(TokenError::Invalid {
699 message: "Token has been revoked".to_string(),
700 }
701 .into());
702 }
703
704 if token.auth_method == "jwt" || token.access_token.contains('.') {
706 self.validate_jwt_token(&token.access_token)?;
707 }
708
709 Ok(())
710 }
711
712 pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
714 if token.is_expired() {
715 return Err(TokenError::Expired.into());
716 }
717
718 if token.is_revoked() {
719 return Err(TokenError::Invalid {
720 message: "Cannot refresh revoked token".to_string(),
721 }
722 .into());
723 }
724
725 self.create_auth_token(
727 &token.user_id,
728 token.scopes.clone(),
729 &token.auth_method,
730 Some(self.default_lifetime),
731 )
732 }
733
734 pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
736 let claims = self.validate_jwt_token(token)?;
737
738 Ok(TokenInfo {
739 user_id: claims.sub,
740 username: claims
741 .custom
742 .get("username")
743 .and_then(|v| v.as_str())
744 .map(|s| s.to_string()),
745 email: claims
746 .custom
747 .get("email")
748 .and_then(|v| v.as_str())
749 .map(|s| s.to_string()),
750 name: claims
751 .custom
752 .get("name")
753 .and_then(|v| v.as_str())
754 .map(|s| s.to_string()),
755 roles: claims
756 .custom
757 .get("roles")
758 .and_then(|v| v.as_array())
759 .map(|arr| {
760 arr.iter()
761 .filter_map(|v| v.as_str())
762 .map(|s| s.to_string())
763 .collect()
764 })
765 .unwrap_or_default(),
766 permissions: claims
767 .scope
768 .split_whitespace()
769 .map(|s| s.to_string())
770 .collect(),
771 attributes: claims.custom,
772 })
773 }
774}
775
776#[async_trait::async_trait]
778pub trait TokenToProfile {
779 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
781
782 async fn to_profile_with_extractor(
784 &self,
785 provider: &OAuthProvider,
786 extractor: &ProfileExtractor,
787 ) -> Result<UserProfile>;
788}
789
790#[async_trait::async_trait]
791impl TokenToProfile for AuthToken {
792 async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile> {
793 let extractor = ProfileExtractor::new();
794 extractor.extract_profile(self, provider).await
795 }
796
797 async fn to_profile_with_extractor(
798 &self,
799 provider: &OAuthProvider,
800 extractor: &ProfileExtractor,
801 ) -> Result<UserProfile> {
802 extractor.extract_profile(self, provider).await
803 }
804}
805
806#[cfg(test)]
807mod tests {
808 use super::*;
809
810 #[test]
811 fn test_auth_token_creation() {
812 let token = AuthToken::new(
813 "user123",
814 "token123",
815 Duration::from_secs(3600), "password",
817 );
818
819 assert_eq!(token.user_id(), "user123");
820 assert_eq!(token.access_token(), "token123");
821 assert!(!token.is_expired());
822 assert!(!token.is_revoked());
823 assert!(token.is_valid());
824 }
825
826 #[test]
827 fn test_token_expiry() {
828 let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
829
830 std::thread::sleep(std::time::Duration::from_millis(10));
832
833 assert!(token.is_expired());
834 assert!(!token.is_valid());
835 }
836
837 #[test]
838 fn test_token_revocation() {
839 let mut token = AuthToken::new(
840 "user123",
841 "token123",
842 Duration::from_secs(3600), "password",
844 );
845
846 assert!(!token.is_revoked());
847
848 token.revoke(Some("User logout".to_string()));
849
850 assert!(token.is_revoked());
851 assert!(!token.is_valid());
852 assert!(token.metadata.revoked);
853 }
854}