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(Debug, 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
66/// Additional metadata that can be attached to tokens.
67#[derive(Debug, Clone, Serialize, Deserialize, Default)]
68pub struct TokenMetadata {
69    /// IP address where the token was issued
70    pub issued_ip: Option<String>,
71
72    /// User agent of the client
73    pub user_agent: Option<String>,
74
75    /// Device identifier
76    pub device_id: Option<String>,
77
78    /// Session identifier
79    pub session_id: Option<String>,
80
81    /// Whether this token has been revoked
82    pub revoked: bool,
83
84    /// When the token was revoked (if applicable)
85    pub revoked_at: Option<DateTime<Utc>>,
86
87    /// Reason for revocation
88    pub revoked_reason: Option<String>,
89
90    /// Last time this token was used
91    pub last_used: Option<DateTime<Utc>>,
92
93    /// Number of times this token has been used
94    pub use_count: u64,
95
96    /// Custom metadata
97    pub custom: HashMap<String, serde_json::Value>,
98}
99
100#[cfg(feature = "postgres-storage")]
101use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
102
103#[cfg(feature = "postgres-storage")]
104impl<'r> Decode<'r, Postgres> for TokenMetadata {
105    fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
106        let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
107        serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
108    }
109}
110
111#[cfg(feature = "postgres-storage")]
112impl Type<Postgres> for TokenMetadata {
113    fn type_info() -> sqlx::postgres::PgTypeInfo {
114        <serde_json::Value as Type<Postgres>>::type_info()
115    }
116    fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
117        <serde_json::Value as Type<Postgres>>::compatible(ty)
118    }
119}
120
121/// Information about a user extracted from a token.
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct TokenInfo {
124    /// User identifier
125    pub user_id: String,
126
127    /// Username or email
128    pub username: Option<String>,
129
130    /// User's email address
131    pub email: Option<String>,
132
133    /// User's display name
134    pub name: Option<String>,
135
136    /// User's roles
137    pub roles: Vec<String>,
138
139    /// User's permissions
140    pub permissions: Vec<String>,
141
142    /// Additional user attributes
143    pub attributes: HashMap<String, serde_json::Value>,
144}
145
146/// JWT claims structure used internally.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct JwtClaims {
149    /// Subject (user ID)
150    pub sub: String,
151
152    /// Issuer
153    pub iss: String,
154
155    /// Audience
156    pub aud: String,
157
158    /// Expiration time
159    pub exp: i64,
160
161    /// Issued at
162    pub iat: i64,
163
164    /// Not before
165    pub nbf: i64,
166
167    /// JWT ID
168    pub jti: String,
169
170    /// Scopes
171    pub scope: String,
172
173    /// User permissions
174    pub permissions: Option<Vec<String>>,
175
176    /// User roles
177    pub roles: Option<Vec<String>>,
178
179    /// Client ID
180    pub client_id: Option<String>,
181
182    /// Custom claims
183    #[serde(flatten)]
184    pub custom: HashMap<String, serde_json::Value>,
185}
186
187impl JwtClaims {
188    /// Name of the custom claim that says what a token may be used for.
189    pub const TOKEN_USE_CLAIM: &'static str = "token_use";
190    /// Value of [`TOKEN_USE_CLAIM`](Self::TOKEN_USE_CLAIM) on refresh tokens.
191    pub const TOKEN_USE_REFRESH: &'static str = "refresh";
192
193    /// `true` only for tokens minted by [`TokenManager::create_refresh_jwt_token`].
194    /// The `scope` string plays no part: a scope is permission data a user or client can
195    /// influence, this claim is not.
196    pub fn is_refresh_token(&self) -> bool {
197        self.custom
198            .get(Self::TOKEN_USE_CLAIM)
199            .and_then(|v| v.as_str())
200            == Some(Self::TOKEN_USE_REFRESH)
201    }
202}
203
204/// Token manager for creating, validating, and managing tokens.
205pub struct TokenManager {
206    /// JWT encoding key
207    encoding_key: EncodingKey,
208
209    /// JWT decoding key
210    decoding_key: DecodingKey,
211
212    /// Key material for recreating keys during clone
213    key_material: KeyMaterial,
214
215    /// JWT algorithm
216    algorithm: Algorithm,
217
218    /// Token issuer
219    issuer: String,
220
221    /// Token audience
222    audience: String,
223
224    /// Default token lifetime
225    default_lifetime: Duration,
226}
227
228/// Key material for cloning TokenManager
229#[derive(Clone)]
230enum KeyMaterial {
231    /// HMAC secret
232    Hmac(Vec<u8>),
233    /// RSA private and public keys
234    Rsa { private: Vec<u8>, public: Vec<u8> },
235}
236
237impl AuthToken {
238    /// Create a new authentication token.
239    pub fn new(
240        user_id: impl Into<String>,
241        access_token: impl Into<String>,
242        expires_in: std::time::Duration,
243        auth_method: impl Into<String>,
244    ) -> Self {
245        let now = Utc::now();
246        let expires_in_chrono =
247            chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
248
249        Self {
250            token_id: Uuid::new_v4().to_string(),
251            user_id: user_id.into(),
252            access_token: access_token.into(),
253            refresh_token: None,
254            token_type: Some("Bearer".to_string()),
255            subject: None,
256            issuer: None,
257            issued_at: now,
258            expires_at: now + expires_in_chrono,
259            scopes: Vec::new(),
260            auth_method: auth_method.into(),
261            client_id: None,
262            user_profile: None,
263            permissions: Vec::new(),
264            roles: Vec::new(),
265            metadata: TokenMetadata::default(),
266        }
267    }
268
269    /// Get the access token string.
270    pub fn access_token(&self) -> &str {
271        &self.access_token
272    }
273
274    /// Get the user ID.
275    pub fn user_id(&self) -> &str {
276        &self.user_id
277    }
278
279    /// Get the expiration time.
280    pub fn expires_at(&self) -> DateTime<Utc> {
281        self.expires_at
282    }
283
284    /// Get the token value
285    pub fn token_value(&self) -> &str {
286        &self.access_token
287    }
288
289    /// Get the token type
290    pub fn token_type(&self) -> Option<&str> {
291        self.token_type.as_deref()
292    }
293
294    /// Get the subject claim
295    pub fn subject(&self) -> Option<&str> {
296        self.subject.as_deref()
297    }
298
299    /// Get the issuer
300    pub fn issuer(&self) -> Option<&str> {
301        self.issuer.as_deref()
302    }
303
304    /// Check if the token has expired.
305    pub fn is_expired(&self) -> bool {
306        Utc::now() > self.expires_at
307    }
308
309    /// Check if the token is expiring within the given duration.
310    pub fn is_expiring(&self, within: Duration) -> bool {
311        Utc::now() + within > self.expires_at
312    }
313
314    /// Check if the token has been revoked.
315    pub fn is_revoked(&self) -> bool {
316        self.metadata.revoked
317    }
318
319    /// Check if the token is valid (not expired and not revoked).
320    pub fn is_valid(&self) -> bool {
321        !self.is_expired() && !self.is_revoked()
322    }
323
324    /// Revoke the token.
325    pub fn revoke(&mut self, reason: Option<String>) {
326        self.metadata.revoked = true;
327        self.metadata.revoked_at = Some(Utc::now());
328        self.metadata.revoked_reason = reason;
329    }
330
331    /// Update the last used time and increment use count.
332    pub fn mark_used(&mut self) {
333        self.metadata.last_used = Some(Utc::now());
334        self.metadata.use_count += 1;
335    }
336
337    /// Add a scope to the token.
338    pub fn add_scope(&mut self, scope: impl Into<String>) {
339        let scope = scope.into();
340        if !self.scopes.contains(&scope) {
341            self.scopes.push(scope);
342        }
343    }
344
345    /// Check if the token has a specific scope.
346    pub fn has_scope(&self, scope: &str) -> bool {
347        self.scopes.contains(&scope.to_string())
348    }
349
350    /// Set the refresh token.
351    pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
352        self.refresh_token = Some(refresh_token.into());
353        self
354    }
355
356    /// Set the client ID.
357    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
358        self.client_id = Some(client_id.into());
359        self
360    }
361
362    /// Set the token scopes.
363    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
364        self.scopes = scopes;
365        self
366    }
367
368    /// Add metadata to the token.
369    pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
370        self.metadata = metadata;
371        self
372    }
373
374    /// Get time until expiration.
375    pub fn time_until_expiry(&self) -> Duration {
376        let now = Utc::now();
377        if self.expires_at > now {
378            (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
379        } else {
380            Duration::ZERO
381        }
382    }
383
384    /// Add a custom claim to the token metadata
385    pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
386        self.metadata.custom.insert(key.into(), value);
387    }
388
389    /// Get a custom claim from the token metadata
390    pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
391        self.metadata.custom.get(key)
392    }
393
394    /// Check if the token has a specific permission
395    pub fn has_permission(&self, permission: &str) -> bool {
396        self.permissions.contains(&permission.to_string())
397    }
398
399    /// Add a permission to the token
400    pub fn add_permission(&mut self, permission: impl Into<String>) {
401        let permission = permission.into();
402        if !self.permissions.contains(&permission) {
403            self.permissions.push(permission);
404        }
405    }
406
407    /// Add a role to the token
408    pub fn add_role(&mut self, role: impl Into<String>) {
409        let role = role.into();
410        if !self.roles.contains(&role) {
411            self.roles.push(role);
412        }
413    }
414
415    /// Check if the token has a specific role
416    pub fn has_role(&self, role: &str) -> bool {
417        self.roles.contains(&role.to_string())
418    }
419
420    /// Set the permissions
421    pub fn with_permissions(mut self, permissions: Vec<String>) -> Self {
422        self.permissions = permissions;
423        self
424    }
425
426    /// Set the roles
427    pub fn with_roles(mut self, roles: Vec<String>) -> Self {
428        self.roles = roles;
429        self
430    }
431}
432
433impl Clone for TokenManager {
434    fn clone(&self) -> Self {
435        match &self.key_material {
436            KeyMaterial::Hmac(secret) => Self {
437                encoding_key: EncodingKey::from_secret(secret),
438                decoding_key: DecodingKey::from_secret(secret),
439                key_material: self.key_material.clone(),
440                algorithm: self.algorithm,
441                issuer: self.issuer.clone(),
442                audience: self.audience.clone(),
443                default_lifetime: self.default_lifetime,
444            },
445            KeyMaterial::Rsa { private, public } => Self {
446                encoding_key: EncodingKey::from_rsa_pem(private).expect("Valid RSA private key"),
447                decoding_key: DecodingKey::from_rsa_pem(public).expect("Valid RSA public key"),
448                key_material: self.key_material.clone(),
449                algorithm: self.algorithm,
450                issuer: self.issuer.clone(),
451                audience: self.audience.clone(),
452                default_lifetime: self.default_lifetime,
453            },
454        }
455    }
456}
457
458impl TokenManager {
459    /// Create a new token manager with HMAC key.
460    pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
461        Self {
462            encoding_key: EncodingKey::from_secret(secret),
463            decoding_key: DecodingKey::from_secret(secret),
464            key_material: KeyMaterial::Hmac(secret.to_vec()),
465            algorithm: Algorithm::HS256,
466            issuer: issuer.into(),
467            audience: audience.into(),
468            default_lifetime: Duration::from_secs(3600), // 1 hour
469        }
470    }
471
472    /// Create a new token manager with RSA keys.
473    ///
474    /// ## RSA Key Format Support
475    ///
476    /// This method supports RSA keys in both standard PEM formats:
477    /// - **PKCS#1**: `-----BEGIN RSA PRIVATE KEY-----` (traditional RSA format)
478    /// - **PKCS#8**: `-----BEGIN PRIVATE KEY-----` (modern standard format, recommended)
479    ///
480    /// Both formats are automatically detected and parsed. No format conversion is required.
481    ///
482    /// ## Example
483    ///
484    /// ```rust,no_run
485    /// use auth_framework::tokens::TokenManager;
486    ///
487    /// // Both PKCS#1 and PKCS#8 formats work
488    /// let private_key = include_bytes!("../../private.pem");  // Either format
489    /// let public_key = include_bytes!("../../public.pem");
490    ///
491    /// let manager = TokenManager::new_rsa(
492    ///     private_key,
493    ///     public_key,
494    ///     "my-service",
495    ///     "my-audience"
496    /// )?;
497    /// # Ok::<(), auth_framework::errors::AuthError>(())
498    /// ```
499    pub fn new_rsa(
500        private_key: &[u8],
501        public_key: &[u8],
502        issuer: impl Into<String>,
503        audience: impl Into<String>,
504    ) -> Result<Self> {
505        let encoding_key = EncodingKey::from_rsa_pem(private_key)
506            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
507
508        let decoding_key = DecodingKey::from_rsa_pem(public_key)
509            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
510
511        Ok(Self {
512            encoding_key,
513            decoding_key,
514            key_material: KeyMaterial::Rsa {
515                private: private_key.to_vec(),
516                public: public_key.to_vec(),
517            },
518            algorithm: Algorithm::RS256,
519            issuer: issuer.into(),
520            audience: audience.into(),
521            default_lifetime: Duration::from_secs(3600), // 1 hour
522        })
523    }
524
525    /// Set the default token lifetime.
526    pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
527        self.default_lifetime = lifetime;
528        self
529    }
530
531    /// Create a new JWT token.
532    pub fn create_jwt_token(
533        &self,
534        user_id: impl Into<String>,
535        scopes: Vec<String>,
536        lifetime: Option<Duration>,
537    ) -> Result<String> {
538        self.encode_jwt(user_id.into(), scopes, lifetime, None)
539    }
540
541    /// Create a JWT that is a refresh token: it carries `token_use: "refresh"`, which
542    /// `/auth/refresh` requires and which an access token never has.
543    pub fn create_refresh_jwt_token(
544        &self,
545        user_id: impl Into<String>,
546        lifetime: Option<Duration>,
547    ) -> Result<String> {
548        self.encode_jwt(
549            user_id.into(),
550            vec!["refresh".to_string()],
551            lifetime,
552            Some(JwtClaims::TOKEN_USE_REFRESH),
553        )
554    }
555
556    fn encode_jwt(
557        &self,
558        user_id: String,
559        scopes: Vec<String>,
560        lifetime: Option<Duration>,
561        token_use: Option<&str>,
562    ) -> Result<String> {
563        let lifetime = lifetime.unwrap_or(self.default_lifetime);
564        let now = Utc::now();
565        let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
566
567        let mut custom = HashMap::new();
568        if let Some(token_use) = token_use {
569            custom.insert(
570                JwtClaims::TOKEN_USE_CLAIM.to_string(),
571                serde_json::Value::String(token_use.to_string()),
572            );
573        }
574        let claims = JwtClaims {
575            sub: user_id,
576            iss: self.issuer.clone(),
577            aud: self.audience.clone(),
578            exp: exp.timestamp(),
579            iat: now.timestamp(),
580            nbf: now.timestamp(),
581            jti: Uuid::new_v4().to_string(),
582            scope: scopes.join(" "),
583            permissions: None,
584            roles: None,
585            client_id: None,
586            custom,
587        };
588
589        let header = Header::new(self.algorithm);
590
591        encode(&header, &claims, &self.encoding_key)
592            .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
593    }
594
595    /// Validate and decode a JWT token.
596    pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
597        let mut validation = Validation::new(self.algorithm);
598        validation.set_issuer(&[&self.issuer]);
599        validation.set_audience(&[&self.audience]);
600
601        let token_data =
602            decode::<JwtClaims>(token, &self.decoding_key, &validation).map_err(|e| {
603                match e.kind() {
604                    jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
605                        AuthError::Token(TokenError::Expired)
606                    }
607                    _ => AuthError::Token(TokenError::Invalid {
608                        message: "Invalid token format".to_string(),
609                    }),
610                }
611            })?;
612
613        Ok(token_data.claims)
614    }
615
616    /// Create a complete authentication token with JWT.
617    pub fn create_auth_token(
618        &self,
619        user_id: impl Into<String>,
620        scopes: Vec<String>,
621        auth_method: impl Into<String>,
622        lifetime: Option<std::time::Duration>,
623    ) -> Result<AuthToken> {
624        let user_id_str = user_id.into();
625        let lifetime = lifetime.unwrap_or(self.default_lifetime);
626
627        let jwt_token = self.create_jwt_token(&user_id_str, scopes.clone(), Some(lifetime))?;
628
629        let token =
630            AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
631
632        Ok(token)
633    }
634
635    /// Validate an authentication token.
636    pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
637        // Check if token is expired
638        if token.is_expired() {
639            return Err(TokenError::Expired.into());
640        }
641
642        // Check if token is revoked
643        if token.is_revoked() {
644            return Err(TokenError::Invalid {
645                message: "Token has been revoked".to_string(),
646            }
647            .into());
648        }
649
650        // Validate JWT if it's a JWT token
651        if token.auth_method == "jwt" || token.access_token.contains('.') {
652            self.validate_jwt_token(&token.access_token)?;
653        }
654
655        Ok(())
656    }
657
658    /// Refresh a token (create a new one with extended lifetime).
659    pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
660        if token.is_expired() {
661            return Err(TokenError::Expired.into());
662        }
663
664        if token.is_revoked() {
665            return Err(TokenError::Invalid {
666                message: "Cannot refresh revoked token".to_string(),
667            }
668            .into());
669        }
670
671        // Create a new token with the same properties but new expiry
672        self.create_auth_token(
673            &token.user_id,
674            token.scopes.clone(),
675            &token.auth_method,
676            Some(self.default_lifetime),
677        )
678    }
679
680    /// Extract token information from a JWT.
681    pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
682        let claims = self.validate_jwt_token(token)?;
683
684        Ok(TokenInfo {
685            user_id: claims.sub,
686            username: claims
687                .custom
688                .get("username")
689                .and_then(|v| v.as_str())
690                .map(|s| s.to_string()),
691            email: claims
692                .custom
693                .get("email")
694                .and_then(|v| v.as_str())
695                .map(|s| s.to_string()),
696            name: claims
697                .custom
698                .get("name")
699                .and_then(|v| v.as_str())
700                .map(|s| s.to_string()),
701            roles: claims
702                .custom
703                .get("roles")
704                .and_then(|v| v.as_array())
705                .map(|arr| {
706                    arr.iter()
707                        .filter_map(|v| v.as_str())
708                        .map(|s| s.to_string())
709                        .collect()
710                })
711                .unwrap_or_default(),
712            permissions: claims
713                .scope
714                .split_whitespace()
715                .map(|s| s.to_string())
716                .collect(),
717            attributes: claims.custom,
718        })
719    }
720}
721
722/// Trait for converting tokens to user profiles
723#[async_trait::async_trait]
724pub trait TokenToProfile {
725    /// Convert this token to a user profile using the specified provider
726    async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile>;
727
728    /// Convert this token to a user profile with a custom extractor
729    async fn to_profile_with_extractor(
730        &self,
731        provider: &OAuthProvider,
732        extractor: &ProfileExtractor,
733    ) -> Result<UserProfile>;
734}
735
736#[async_trait::async_trait]
737impl TokenToProfile for AuthToken {
738    async fn to_profile(&self, provider: &OAuthProvider) -> Result<UserProfile> {
739        let extractor = ProfileExtractor::new();
740        extractor.extract_profile(self, provider).await
741    }
742
743    async fn to_profile_with_extractor(
744        &self,
745        provider: &OAuthProvider,
746        extractor: &ProfileExtractor,
747    ) -> Result<UserProfile> {
748        extractor.extract_profile(self, provider).await
749    }
750}
751
752#[cfg(test)]
753mod tests {
754    use super::*;
755
756    #[test]
757    fn test_auth_token_creation() {
758        let token = AuthToken::new(
759            "user123",
760            "token123",
761            Duration::from_secs(3600), // 1 hour
762            "password",
763        );
764
765        assert_eq!(token.user_id(), "user123");
766        assert_eq!(token.access_token(), "token123");
767        assert!(!token.is_expired());
768        assert!(!token.is_revoked());
769        assert!(token.is_valid());
770    }
771
772    #[test]
773    fn test_token_expiry() {
774        let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
775
776        // Wait a bit to ensure expiry
777        std::thread::sleep(std::time::Duration::from_millis(10));
778
779        assert!(token.is_expired());
780        assert!(!token.is_valid());
781    }
782
783    #[test]
784    fn test_token_revocation() {
785        let mut token = AuthToken::new(
786            "user123",
787            "token123",
788            Duration::from_secs(3600), // 1 hour
789            "password",
790        );
791
792        assert!(!token.is_revoked());
793
794        token.revoke(Some("User logout".to_string()));
795
796        assert!(token.is_revoked());
797        assert!(!token.is_valid());
798        assert!(token.metadata.revoked);
799    }
800}