Skip to main content

auth_framework/tokens/
mod.rs

1//! Token management and validation for the authentication framework.
2use 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/// Represents an authentication token with all associated metadata.
14#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
15#[derive(Clone, Serialize, Deserialize)]
16pub struct AuthToken {
17    /// Unique token identifier
18    pub token_id: String,
19
20    /// User identifier this token belongs to
21    pub user_id: String,
22
23    /// Access token value
24    pub access_token: String,
25
26    /// Token type (e.g., "bearer")
27    pub token_type: Option<String>,
28
29    /// Subject claim
30    pub subject: Option<String>,
31
32    /// Token issuer
33    pub issuer: Option<String>,
34
35    /// Optional refresh token
36    pub refresh_token: Option<String>,
37
38    /// When the token was issued
39    pub issued_at: DateTime<Utc>,
40
41    /// When the token expires
42    pub expires_at: DateTime<Utc>,
43
44    /// Scopes granted to this token
45    pub scopes: Vec<String>,
46
47    /// Authentication method used to obtain this token
48    pub auth_method: String,
49
50    /// Client ID that requested this token
51    pub client_id: Option<String>,
52
53    /// User profile data (optional)
54    pub user_profile: Option<UserProfile>,
55
56    /// User's permissions
57    pub permissions: Vec<String>,
58
59    /// User's roles
60    pub roles: Vec<String>,
61
62    /// Additional token metadata
63    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/// Additional metadata that can be attached to tokens.
96#[derive(Clone, Serialize, Deserialize, Default)]
97pub struct TokenMetadata {
98    /// IP address where the token was issued
99    pub issued_ip: Option<String>,
100
101    /// User agent of the client
102    pub user_agent: Option<String>,
103
104    /// Device identifier
105    pub device_id: Option<String>,
106
107    /// Session identifier
108    pub session_id: Option<String>,
109
110    /// Whether this token has been revoked
111    pub revoked: bool,
112
113    /// When the token was revoked (if applicable)
114    pub revoked_at: Option<DateTime<Utc>>,
115
116    /// Reason for revocation
117    pub revoked_reason: Option<String>,
118
119    /// Last time this token was used
120    pub last_used: Option<DateTime<Utc>>,
121
122    /// Number of times this token has been used
123    pub use_count: u64,
124
125    /// Custom metadata
126    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/// Information about a user extracted from a token.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172pub struct TokenInfo {
173    /// User identifier
174    pub user_id: String,
175
176    /// Username or email
177    pub username: Option<String>,
178
179    /// User's email address
180    pub email: Option<String>,
181
182    /// User's display name
183    pub name: Option<String>,
184
185    /// User's roles
186    pub roles: Vec<String>,
187
188    /// User's permissions
189    pub permissions: Vec<String>,
190
191    /// Additional user attributes
192    pub attributes: HashMap<String, serde_json::Value>,
193}
194
195/// JWT claims structure used internally.
196#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct JwtClaims {
198    /// Subject (user ID)
199    pub sub: String,
200
201    /// Issuer
202    pub iss: String,
203
204    /// Audience
205    pub aud: String,
206
207    /// Expiration time
208    pub exp: i64,
209
210    /// Issued at
211    pub iat: i64,
212
213    /// Not before
214    pub nbf: i64,
215
216    /// JWT ID
217    pub jti: String,
218
219    /// Scopes
220    pub scope: String,
221
222    /// User permissions
223    pub permissions: Option<Vec<String>>,
224
225    /// User roles
226    pub roles: Option<Vec<String>>,
227
228    /// Client ID
229    pub client_id: Option<String>,
230
231    /// Custom claims
232    #[serde(flatten)]
233    pub custom: HashMap<String, serde_json::Value>,
234}
235
236impl JwtClaims {
237    /// Name of the custom claim that says what a token may be used for.
238    pub const TOKEN_USE_CLAIM: &'static str = "token_use";
239    /// Value of [`TOKEN_USE_CLAIM`](Self::TOKEN_USE_CLAIM) on refresh tokens.
240    pub const TOKEN_USE_REFRESH: &'static str = "refresh";
241
242    /// `true` only for tokens minted by [`TokenManager::create_refresh_jwt_token`].
243    /// The `scope` string plays no part: a scope is permission data a user or client can
244    /// influence, this claim is not.
245    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
253/// Token manager for creating, validating, and managing tokens.
254pub struct TokenManager {
255    /// JWT encoding key
256    encoding_key: EncodingKey,
257
258    /// JWT decoding key
259    decoding_key: DecodingKey,
260
261    /// Key material for recreating keys during clone
262    key_material: KeyMaterial,
263
264    /// JWT algorithm
265    algorithm: Algorithm,
266
267    /// Token issuer
268    issuer: String,
269
270    /// Token audience
271    audience: String,
272
273    /// Default token lifetime
274    default_lifetime: Duration,
275}
276
277/// Key material for cloning TokenManager
278#[derive(Clone)]
279enum KeyMaterial {
280    /// HMAC secret
281    Hmac(Vec<u8>),
282    /// RSA private and public keys
283    Rsa { private: Vec<u8>, public: Vec<u8> },
284}
285
286impl AuthToken {
287    /// Create a new authentication token.
288    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    /// Get the access token string.
319    pub fn access_token(&self) -> &str {
320        &self.access_token
321    }
322
323    /// Get the user ID.
324    pub fn user_id(&self) -> &str {
325        &self.user_id
326    }
327
328    /// Get the expiration time.
329    pub fn expires_at(&self) -> DateTime<Utc> {
330        self.expires_at
331    }
332
333    /// Get the token value
334    pub fn token_value(&self) -> &str {
335        &self.access_token
336    }
337
338    /// Get the token type
339    pub fn token_type(&self) -> Option<&str> {
340        self.token_type.as_deref()
341    }
342
343    /// Get the subject claim
344    pub fn subject(&self) -> Option<&str> {
345        self.subject.as_deref()
346    }
347
348    /// Get the issuer
349    pub fn issuer(&self) -> Option<&str> {
350        self.issuer.as_deref()
351    }
352
353    /// Check if the token has expired.
354    pub fn is_expired(&self) -> bool {
355        Utc::now() > self.expires_at
356    }
357
358    /// Check if the token is expiring within the given duration.
359    pub fn is_expiring(&self, within: Duration) -> bool {
360        Utc::now() + within > self.expires_at
361    }
362
363    /// Check if the token has been revoked.
364    pub fn is_revoked(&self) -> bool {
365        self.metadata.revoked
366    }
367
368    /// Check if the token is valid (not expired and not revoked).
369    pub fn is_valid(&self) -> bool {
370        !self.is_expired() && !self.is_revoked()
371    }
372
373    /// Revoke the token.
374    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    /// Update the last used time and increment use count.
381    pub fn mark_used(&mut self) {
382        self.metadata.last_used = Some(Utc::now());
383        self.metadata.use_count += 1;
384    }
385
386    /// Add a scope to the token.
387    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    /// Check if the token has a specific scope.
395    pub fn has_scope(&self, scope: &str) -> bool {
396        self.scopes.contains(&scope.to_string())
397    }
398
399    /// Set the refresh token.
400    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    /// Set the client ID.
406    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    /// Set the token scopes.
412    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
413        self.scopes = scopes;
414        self
415    }
416
417    /// Add metadata to the token.
418    pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
419        self.metadata = metadata;
420        self
421    }
422
423    /// Get time until expiration.
424    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    /// Add a custom claim to the token metadata
434    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    /// Get a custom claim from the token metadata
439    pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
440        self.metadata.custom.get(key)
441    }
442
443    /// Check if the token has a specific permission
444    pub fn has_permission(&self, permission: &str) -> bool {
445        self.permissions.contains(&permission.to_string())
446    }
447
448    /// Add a permission to the token
449    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    /// Add a role to the token
457    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    /// Check if the token has a specific role
465    pub fn has_role(&self, role: &str) -> bool {
466        self.roles.contains(&role.to_string())
467    }
468
469    /// Set the permissions
470    pub fn with_permissions(mut self, permissions: Vec<String>) -> Self {
471        self.permissions = permissions;
472        self
473    }
474
475    /// Set the roles
476    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    /// Create a new token manager with HMAC key.
509    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), // 1 hour
518        }
519    }
520
521    /// Create a new token manager with RSA keys.
522    ///
523    /// ## RSA Key Format Support
524    ///
525    /// This method supports RSA keys in both standard PEM formats:
526    /// - **PKCS#1**: `-----BEGIN RSA PRIVATE KEY-----` (traditional RSA format)
527    /// - **PKCS#8**: `-----BEGIN PRIVATE KEY-----` (modern standard format, recommended)
528    ///
529    /// Both formats are automatically detected and parsed. No format conversion is required.
530    ///
531    /// ## Example
532    ///
533    /// ```rust,no_run
534    /// use auth_framework::tokens::TokenManager;
535    ///
536    /// // Both PKCS#1 and PKCS#8 formats work; provide PEM bytes from your key store.
537    /// # let private_key: &[u8] = b"";
538    /// # let public_key: &[u8] = b"";
539    ///
540    /// let manager = TokenManager::new_rsa(
541    ///     private_key,
542    ///     public_key,
543    ///     "my-service",
544    ///     "my-audience"
545    /// )?;
546    /// # Ok::<(), auth_framework::errors::AuthError>(())
547    /// ```
548    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), // 1 hour
571        })
572    }
573
574    /// Set the default token lifetime.
575    pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
576        self.default_lifetime = lifetime;
577        self
578    }
579
580    /// Create a new JWT token.
581    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    /// Create a JWT for a token issued to an OAuth client on a user's behalf: it carries the
591    /// `client_id` claim, which marks it as delegated access and not as the user's own session.
592    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    /// Create a JWT that is a refresh token: it carries `token_use: "refresh"`, which
609    /// `/auth/refresh` requires and which an access token never has.
610    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    /// Validate a JWT that stands for a user's own session: like
665    /// [`validate_jwt_token`](Self::validate_jwt_token), but a token issued to an OAuth client
666    /// (one that carries a `client_id` claim) is refused.
667    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    /// Validate and decode a JWT token.
679    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                        // The caller gets one opaque message so a client learns nothing about why a
692                        // token was refused; the operator gets the cause. The token is never logged.
693                        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    /// Create a complete authentication token with JWT.
705    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    /// Create a complete authentication token for a token issued to an OAuth client
724    /// (see [`create_client_jwt_token`](Self::create_client_jwt_token)).
725    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    /// Validate an authentication token.
748    pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
749        // Check if token is expired
750        if token.is_expired() {
751            return Err(TokenError::Expired.into());
752        }
753
754        // Check if token is revoked
755        if token.is_revoked() {
756            return Err(TokenError::Invalid {
757                message: "Token has been revoked".to_string(),
758            }
759            .into());
760        }
761
762        // Validate JWT if it's a JWT token
763        if token.auth_method == "jwt" || token.access_token.contains('.') {
764            self.validate_jwt_token(&token.access_token)?;
765        }
766
767        Ok(())
768    }
769
770    /// Refresh a token (create a new one with extended lifetime).
771    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        // Create a new token with the same properties but new expiry
784        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    /// Extract token information from a JWT.
802    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/// Trait for converting tokens to user profiles
844#[async_trait::async_trait]
845pub trait TokenToProfile {
846    /// Convert this token to a user profile using the specified provider
847    async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
848
849    /// Convert this token to a user profile with a custom extractor
850    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), // 1 hour
883            "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        // Wait a bit to ensure expiry
898        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), // 1 hour
910            "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}