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, ProviderProfile};
4use base64::Engine as _;
5use chrono::{DateTime, Utc};
6use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, encode};
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9#[cfg(feature = "postgres-storage")]
10use sqlx::FromRow;
11use std::collections::HashMap;
12use std::time::Duration;
13use uuid::Uuid;
14
15/// An issued authentication token with all associated metadata.
16///
17/// Created by [`TokenManager`] and returned from
18/// [`AuthFramework::authenticate`](crate::auth::AuthFramework::authenticate).
19/// Contains the encoded `access_token` string, optional `refresh_token`,
20/// granted scopes, and contextual [`TokenMetadata`].
21#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
22#[derive(Clone, Serialize, Deserialize)]
23pub struct AuthToken {
24    /// Unique token identifier
25    pub token_id: String,
26
27    /// User identifier this token belongs to
28    pub user_id: String,
29
30    /// Access token value
31    pub access_token: String,
32
33    /// Token type (e.g., "bearer")
34    pub token_type: Option<String>,
35
36    /// Subject claim
37    pub subject: Option<String>,
38
39    /// Token issuer
40    pub issuer: Option<String>,
41
42    /// Optional refresh token
43    pub refresh_token: Option<String>,
44
45    /// When the token was issued
46    pub issued_at: DateTime<Utc>,
47
48    /// When the token expires
49    pub expires_at: DateTime<Utc>,
50
51    /// Scopes granted to this token
52    pub scopes: crate::types::Scopes,
53
54    /// Authentication method used to obtain this token
55    pub auth_method: String,
56
57    /// Client ID that requested this token
58    pub client_id: Option<String>,
59
60    /// User profile data (optional)
61    pub user_profile: Option<ProviderProfile>,
62
63    /// User's permissions
64    pub permissions: crate::types::Permissions,
65
66    /// User's roles
67    pub roles: crate::types::Roles,
68
69    /// Additional token metadata
70    pub metadata: TokenMetadata,
71}
72
73impl std::fmt::Debug for AuthToken {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        f.debug_struct("AuthToken")
76            .field("token_id", &self.token_id)
77            .field("user_id", &self.user_id)
78            .field("access_token", &"[REDACTED]")
79            .field("token_type", &self.token_type)
80            .field("subject", &self.subject)
81            .field("issuer", &self.issuer)
82            .field(
83                "refresh_token",
84                if self.refresh_token.is_some() {
85                    &"Some([REDACTED])"
86                } else {
87                    &"None"
88                },
89            )
90            .field("issued_at", &self.issued_at)
91            .field("expires_at", &self.expires_at)
92            .field("scopes", &self.scopes)
93            .field("auth_method", &self.auth_method)
94            .field("client_id", &self.client_id)
95            .field("permissions", &self.permissions)
96            .field("roles", &self.roles)
97            .field("metadata", &self.metadata)
98            .finish()
99    }
100}
101
102/// Builder for creating `AuthToken` instances with fluent API.
103///
104/// Reduces cognitive load when constructing tokens with many optional fields.
105/// Required fields are set in `new()`, optional fields via builder methods.
106///
107/// # Example
108///
109/// ```rust
110/// use auth_framework::tokens::{AuthToken, TokenMetadata};
111/// use auth_framework::types::{Scopes, Permissions, Roles};
112/// use chrono::{Utc, Duration};
113///
114/// let token = AuthToken::builder("user123", "token456", "access_token_here")
115///     .scopes(Scopes::new(vec!["read".to_string(), "write".to_string()]))
116///     .permissions(Permissions::new(vec!["admin".to_string()]))
117///     .roles(Roles::new(vec!["user".to_string()]))
118///     .expires_at(Utc::now() + Duration::hours(1))
119///     .client_id("client123")
120///     .build();
121/// ```
122#[derive(Debug, Clone)]
123pub struct AuthTokenBuilder {
124    token_id: String,
125    user_id: String,
126    access_token: String,
127    token_type: Option<String>,
128    subject: Option<String>,
129    issuer: Option<String>,
130    refresh_token: Option<String>,
131    issued_at: DateTime<Utc>,
132    expires_at: DateTime<Utc>,
133    scopes: crate::types::Scopes,
134    auth_method: String,
135    client_id: Option<String>,
136    user_profile: Option<ProviderProfile>,
137    permissions: crate::types::Permissions,
138    roles: crate::types::Roles,
139    metadata: TokenMetadata,
140}
141
142impl AuthTokenBuilder {
143    /// Create a new builder with required fields.
144    ///
145    /// Sets sensible defaults for optional fields:
146    /// - `issued_at`: current time
147    /// - `expires_at`: 1 hour from now
148    /// - `scopes`, `permissions`, `roles`: empty collections
149    /// - `auth_method`: "unknown"
150    /// - `metadata`: default (empty)
151    pub fn new(
152        token_id: impl Into<String>,
153        user_id: impl Into<String>,
154        access_token: impl Into<String>,
155    ) -> Self {
156        let now = Utc::now();
157        Self {
158            token_id: token_id.into(),
159            user_id: user_id.into(),
160            access_token: access_token.into(),
161            token_type: None,
162            subject: None,
163            issuer: None,
164            refresh_token: None,
165            issued_at: now,
166            expires_at: now + chrono::Duration::hours(1),
167            scopes: crate::types::Scopes::empty(),
168            auth_method: "unknown".to_string(),
169            client_id: None,
170            user_profile: None,
171            permissions: crate::types::Permissions::empty(),
172            roles: crate::types::Roles::empty(),
173            metadata: TokenMetadata::default(),
174        }
175    }
176
177    /// Set the token type (e.g., "bearer").
178    ///
179    /// # Example
180    ///
181    /// ```rust
182    /// use auth_framework::tokens::AuthToken;
183    ///
184    /// let token = AuthToken::builder("t1", "u1", "access")
185    ///     .token_type("bearer")
186    ///     .build();
187    /// assert_eq!(token.token_type.as_deref(), Some("bearer"));
188    /// ```
189    pub fn token_type(mut self, token_type: impl Into<String>) -> Self {
190        self.token_type = Some(token_type.into());
191        self
192    }
193
194    /// Set the subject claim.
195    ///
196    /// # Example
197    ///
198    /// ```rust
199    /// use auth_framework::tokens::AuthToken;
200    ///
201    /// let token = AuthToken::builder("t1", "u1", "access")
202    ///     .subject("user@example.com")
203    ///     .build();
204    /// assert_eq!(token.subject.as_deref(), Some("user@example.com"));
205    /// ```
206    pub fn subject(mut self, subject: impl Into<String>) -> Self {
207        self.subject = Some(subject.into());
208        self
209    }
210
211    /// Set the token issuer.
212    ///
213    /// # Example
214    ///
215    /// ```rust
216    /// use auth_framework::tokens::AuthToken;
217    ///
218    /// let token = AuthToken::builder("t1", "u1", "access")
219    ///     .issuer("auth.example.com")
220    ///     .build();
221    /// assert_eq!(token.issuer.as_deref(), Some("auth.example.com"));
222    /// ```
223    pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
224        self.issuer = Some(issuer.into());
225        self
226    }
227
228    /// Set the refresh token.
229    ///
230    /// # Example
231    ///
232    /// ```rust
233    /// use auth_framework::tokens::AuthToken;
234    ///
235    /// let token = AuthToken::builder("t1", "u1", "access")
236    ///     .refresh_token("refresh_token_value")
237    ///     .build();
238    /// assert!(token.refresh_token.is_some());
239    /// ```
240    pub fn refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
241        self.refresh_token = Some(refresh_token.into());
242        self
243    }
244
245    /// Set the issued timestamp.
246    ///
247    /// # Example
248    ///
249    /// ```rust
250    /// use auth_framework::tokens::AuthToken;
251    /// use chrono::Utc;
252    ///
253    /// let now = Utc::now();
254    /// let token = AuthToken::builder("t1", "u1", "access")
255    ///     .issued_at(now)
256    ///     .build();
257    /// assert_eq!(token.issued_at, now);
258    /// ```
259    pub fn issued_at(mut self, issued_at: DateTime<Utc>) -> Self {
260        self.issued_at = issued_at;
261        self
262    }
263
264    /// Set the expiration timestamp.
265    ///
266    /// # Example
267    ///
268    /// ```rust
269    /// use auth_framework::tokens::AuthToken;
270    /// use chrono::{Utc, Duration};
271    ///
272    /// let expires = Utc::now() + Duration::hours(2);
273    /// let token = AuthToken::builder("t1", "u1", "access")
274    ///     .expires_at(expires)
275    ///     .build();
276    /// ```
277    pub fn expires_at(mut self, expires_at: DateTime<Utc>) -> Self {
278        self.expires_at = expires_at;
279        self
280    }
281
282    /// Set the granted scopes.
283    ///
284    /// # Example
285    ///
286    /// ```rust
287    /// use auth_framework::tokens::AuthToken;
288    /// use auth_framework::types::Scopes;
289    ///
290    /// let token = AuthToken::builder("t1", "u1", "access")
291    ///     .scopes(Scopes::new(vec!["read".into(), "write".into()]))
292    ///     .build();
293    /// ```
294    pub fn scopes(mut self, scopes: crate::types::Scopes) -> Self {
295        self.scopes = scopes;
296        self
297    }
298
299    /// Set the authentication method.
300    ///
301    /// # Example
302    ///
303    /// ```rust
304    /// use auth_framework::tokens::AuthToken;
305    ///
306    /// let token = AuthToken::builder("t1", "u1", "access")
307    ///     .auth_method("password")
308    ///     .build();
309    /// assert_eq!(token.auth_method, "password");
310    /// ```
311    pub fn auth_method(mut self, auth_method: impl Into<String>) -> Self {
312        self.auth_method = auth_method.into();
313        self
314    }
315
316    /// Set the client ID.
317    ///
318    /// # Example
319    ///
320    /// ```rust
321    /// use auth_framework::tokens::AuthToken;
322    ///
323    /// let token = AuthToken::builder("t1", "u1", "access")
324    ///     .client_id("client-app")
325    ///     .build();
326    /// assert_eq!(token.client_id.as_deref(), Some("client-app"));
327    /// ```
328    pub fn client_id(mut self, client_id: impl Into<String>) -> Self {
329        self.client_id = Some(client_id.into());
330        self
331    }
332
333    /// Set the user profile.
334    ///
335    /// # Example
336    ///
337    /// ```rust,ignore
338    /// use auth_framework::tokens::AuthToken;
339    /// use auth_framework::providers::ProviderProfile;
340    ///
341    /// let profile = ProviderProfile { /* ... */ };
342    /// let token = AuthToken::builder("t1", "u1", "access")
343    ///     .user_profile(profile)
344    ///     .build();
345    /// ```
346    pub fn user_profile(mut self, user_profile: ProviderProfile) -> Self {
347        self.user_profile = Some(user_profile);
348        self
349    }
350
351    /// Set the user permissions.
352    ///
353    /// # Example
354    ///
355    /// ```rust
356    /// use auth_framework::tokens::AuthToken;
357    /// use auth_framework::types::Permissions;
358    ///
359    /// let token = AuthToken::builder("t1", "u1", "access")
360    ///     .permissions(Permissions::new(vec!["admin".into()]))
361    ///     .build();
362    /// ```
363    pub fn permissions(mut self, permissions: crate::types::Permissions) -> Self {
364        self.permissions = permissions;
365        self
366    }
367
368    /// Set the user roles.
369    ///
370    /// # Example
371    ///
372    /// ```rust
373    /// use auth_framework::tokens::AuthToken;
374    /// use auth_framework::types::Roles;
375    ///
376    /// let token = AuthToken::builder("t1", "u1", "access")
377    ///     .roles(Roles::new(vec!["editor".into()]))
378    ///     .build();
379    /// ```
380    pub fn roles(mut self, roles: crate::types::Roles) -> Self {
381        self.roles = roles;
382        self
383    }
384
385    /// Set the token metadata.
386    ///
387    /// # Example
388    ///
389    /// ```rust
390    /// use auth_framework::tokens::{AuthToken, TokenMetadata};
391    ///
392    /// let meta = TokenMetadata::builder().issued_ip("10.0.0.1").build();
393    /// let token = AuthToken::builder("t1", "u1", "access")
394    ///     .metadata(meta)
395    ///     .build();
396    /// ```
397    pub fn metadata(mut self, metadata: TokenMetadata) -> Self {
398        self.metadata = metadata;
399        self
400    }
401
402    /// Build the `AuthToken` instance.
403    ///
404    /// # Example
405    ///
406    /// ```rust
407    /// use auth_framework::tokens::AuthToken;
408    ///
409    /// let token = AuthToken::builder("t1", "u1", "access").build();
410    /// assert_eq!(token.user_id, "u1");
411    /// ```
412    pub fn build(self) -> AuthToken {
413        AuthToken {
414            token_id: self.token_id,
415            user_id: self.user_id,
416            access_token: self.access_token,
417            token_type: self.token_type,
418            subject: self.subject,
419            issuer: self.issuer,
420            refresh_token: self.refresh_token,
421            issued_at: self.issued_at,
422            expires_at: self.expires_at,
423            scopes: self.scopes,
424            auth_method: self.auth_method,
425            client_id: self.client_id,
426            user_profile: self.user_profile,
427            permissions: self.permissions,
428            roles: self.roles,
429            metadata: self.metadata,
430        }
431    }
432}
433
434impl AuthToken {
435    /// Start building an `AuthToken` with fluent setters.
436    ///
437    /// # Example
438    ///
439    /// ```rust
440    /// use auth_framework::tokens::AuthToken;
441    ///
442    /// let token = AuthToken::builder("token123", "user456", "access_token")
443    ///     .expires_at(chrono::Utc::now() + chrono::Duration::hours(2))
444    ///     .build();
445    /// ```
446    pub fn builder(
447        token_id: impl Into<String>,
448        user_id: impl Into<String>,
449        access_token: impl Into<String>,
450    ) -> AuthTokenBuilder {
451        AuthTokenBuilder::new(token_id, user_id, access_token)
452    }
453}
454
455/// Contextual information attached to a token at issuance time.
456///
457/// Tracks revocation state, usage counters, and client fingerprints
458/// (IP, user-agent, device).  Defaults to an empty / non-revoked state.
459#[derive(Debug, Clone, Serialize, Deserialize, Default)]
460pub struct TokenMetadata {
461    /// IP address where the token was issued
462    pub issued_ip: Option<String>,
463
464    /// User agent of the client
465    pub user_agent: Option<String>,
466
467    /// Device identifier
468    pub device_id: Option<String>,
469
470    /// Session identifier
471    pub session_id: Option<String>,
472
473    /// Whether this token has been revoked
474    pub revoked: bool,
475
476    /// When the token was revoked (if applicable)
477    pub revoked_at: Option<DateTime<Utc>>,
478
479    /// Reason for revocation
480    pub revoked_reason: Option<String>,
481
482    /// Last time this token was used
483    pub last_used: Option<DateTime<Utc>>,
484
485    /// Number of times this token has been used
486    pub use_count: u64,
487
488    /// Custom metadata
489    pub custom: HashMap<String, serde_json::Value>,
490}
491
492impl TokenMetadata {
493    /// Start building a `TokenMetadata` with fluent setters.
494    ///
495    /// # Example
496    ///
497    /// ```rust
498    /// use auth_framework::tokens::TokenMetadata;
499    /// let meta = TokenMetadata::builder()
500    ///     .issued_ip("10.0.0.1")
501    ///     .user_agent("curl/8.0")
502    ///     .device_id("device-abc")
503    ///     .build();
504    /// assert_eq!(meta.issued_ip.as_deref(), Some("10.0.0.1"));
505    /// ```
506    pub fn builder() -> TokenMetadataBuilder {
507        TokenMetadataBuilder::default()
508    }
509}
510
511/// Fluent builder for [`TokenMetadata`].
512#[derive(Debug, Clone, Default)]
513pub struct TokenMetadataBuilder {
514    inner: TokenMetadata,
515}
516
517impl TokenMetadataBuilder {
518    /// Set the IP address that issued the token.
519    ///
520    /// # Example
521    ///
522    /// ```rust
523    /// use auth_framework::tokens::TokenMetadata;
524    ///
525    /// let meta = TokenMetadata::builder().issued_ip("10.0.0.1").build();
526    /// assert_eq!(meta.issued_ip.as_deref(), Some("10.0.0.1"));
527    /// ```
528    pub fn issued_ip(mut self, ip: impl Into<String>) -> Self {
529        self.inner.issued_ip = Some(ip.into());
530        self
531    }
532
533    /// Set the user-agent string of the issuing client.
534    ///
535    /// # Example
536    ///
537    /// ```rust
538    /// use auth_framework::tokens::TokenMetadata;
539    ///
540    /// let meta = TokenMetadata::builder().user_agent("curl/8.0").build();
541    /// assert_eq!(meta.user_agent.as_deref(), Some("curl/8.0"));
542    /// ```
543    pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
544        self.inner.user_agent = Some(ua.into());
545        self
546    }
547
548    /// Set the device identifier.
549    ///
550    /// # Example
551    ///
552    /// ```rust
553    /// use auth_framework::tokens::TokenMetadata;
554    ///
555    /// let meta = TokenMetadata::builder().device_id("phone-123").build();
556    /// assert_eq!(meta.device_id.as_deref(), Some("phone-123"));
557    /// ```
558    pub fn device_id(mut self, id: impl Into<String>) -> Self {
559        self.inner.device_id = Some(id.into());
560        self
561    }
562
563    /// Set the associated session identifier.
564    ///
565    /// # Example
566    ///
567    /// ```rust
568    /// use auth_framework::tokens::TokenMetadata;
569    ///
570    /// let meta = TokenMetadata::builder().session_id("sess-abc").build();
571    /// assert_eq!(meta.session_id.as_deref(), Some("sess-abc"));
572    /// ```
573    pub fn session_id(mut self, id: impl Into<String>) -> Self {
574        self.inner.session_id = Some(id.into());
575        self
576    }
577
578    /// Insert a custom metadata entry.
579    ///
580    /// # Example
581    ///
582    /// ```rust
583    /// use auth_framework::tokens::TokenMetadata;
584    ///
585    /// let meta = TokenMetadata::builder()
586    ///     .custom("region", serde_json::json!("us-east-1"))
587    ///     .build();
588    /// assert_eq!(meta.custom.get("region").unwrap(), "us-east-1");
589    /// ```
590    pub fn custom(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
591        self.inner.custom.insert(key.into(), value);
592        self
593    }
594
595    /// Consume the builder and return the finished [`TokenMetadata`].
596    ///
597    /// # Example
598    ///
599    /// ```rust
600    /// use auth_framework::tokens::TokenMetadata;
601    ///
602    /// let meta = TokenMetadata::builder()
603    ///     .issued_ip("127.0.0.1")
604    ///     .user_agent("test-client")
605    ///     .build();
606    /// assert!(!meta.revoked);
607    /// ```
608    pub fn build(self) -> TokenMetadata {
609        self.inner
610    }
611}
612
613#[cfg(feature = "postgres-storage")]
614use sqlx::{Decode, Postgres, Type, postgres::PgValueRef};
615
616#[cfg(feature = "postgres-storage")]
617impl<'r> Decode<'r, Postgres> for TokenMetadata {
618    fn decode(value: PgValueRef<'r>) -> std::result::Result<Self, sqlx::error::BoxDynError> {
619        let json: serde_json::Value = <serde_json::Value as Decode<Postgres>>::decode(value)?;
620        serde_json::from_value(json).map_err(|e| Box::new(e) as sqlx::error::BoxDynError)
621    }
622}
623
624#[cfg(feature = "postgres-storage")]
625impl Type<Postgres> for TokenMetadata {
626    fn type_info() -> sqlx::postgres::PgTypeInfo {
627        <serde_json::Value as Type<Postgres>>::type_info()
628    }
629    fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool {
630        <serde_json::Value as Type<Postgres>>::compatible(ty)
631    }
632}
633
634/// Lightweight user information extracted from a validated token.
635///
636/// Returned by [`AuthFramework::get_token_info`](crate::auth::AuthFramework)
637/// after token validation succeeds.
638#[derive(Debug, Clone, Serialize, Deserialize)]
639pub struct TokenInfo {
640    /// User identifier
641    pub user_id: String,
642
643    /// Username or email
644    pub username: Option<String>,
645
646    /// User's email address
647    pub email: Option<String>,
648
649    /// User's display name
650    pub name: Option<String>,
651
652    /// User's roles
653    pub roles: Vec<String>,
654
655    /// User's permissions
656    pub permissions: Vec<String>,
657
658    /// Additional user attributes
659    pub attributes: HashMap<String, serde_json::Value>,
660}
661
662/// Standard and custom JWT claims used by [`TokenManager`].
663///
664/// Fields follow the [JWT RFC 7519](https://tools.ietf.org/html/rfc7519)
665/// registered claim names.  Additional claims can be stored in [`custom`](JwtClaims::custom).
666#[derive(Debug, Clone, Serialize, Deserialize)]
667pub struct JwtClaims {
668    /// Subject (user ID)
669    pub sub: String,
670
671    /// Issuer
672    pub iss: String,
673
674    /// Audience
675    pub aud: String,
676
677    /// Expiration time
678    pub exp: i64,
679
680    /// Issued at
681    pub iat: i64,
682
683    /// Not before
684    pub nbf: i64,
685
686    /// JWT ID
687    pub jti: String,
688
689    /// Scopes
690    pub scope: String,
691
692    /// User permissions
693    pub permissions: Option<Vec<String>>,
694
695    /// User roles
696    pub roles: Option<Vec<String>>,
697
698    /// Client ID
699    pub client_id: Option<String>,
700
701    /// Custom claims
702    #[serde(flatten)]
703    pub custom: HashMap<String, serde_json::Value>,
704}
705
706/// Central token lifecycle manager: creation, validation, refresh, and
707/// revocation.
708///
709/// Constructed internally by [`AuthFramework`](crate::auth::AuthFramework)
710/// — most users interact with token operations through the
711/// [`TokenOperations`](crate::auth::TokenOperations) facade instead.
712pub struct TokenManager {
713    /// JWT encoding key
714    encoding_key: EncodingKey,
715
716    /// JWT decoding key (current)
717    decoding_key: DecodingKey,
718
719    /// Optional previous decoding key retained during key-rotation grace period.
720    ///
721    /// Tokens signed with the previous key are still accepted until they expire
722    /// naturally.  Once operators are satisfied all pre-rotation tokens have
723    /// expired, they can call [`TokenManager::retire_previous_key`] to remove it.
724    previous_decoding_key: Option<DecodingKey>,
725
726    /// Key material for recreating keys during clone
727    key_material: KeyMaterial,
728
729    /// Key material for the previous key (for clone support after rotation)
730    previous_key_material: Option<KeyMaterial>,
731
732    /// JWT algorithm
733    algorithm: Algorithm,
734
735    /// Token issuer
736    issuer: String,
737
738    /// Token audience
739    audience: String,
740
741    /// Default token lifetime
742    default_lifetime: Duration,
743}
744
745/// Key material for cloning TokenManager
746#[derive(Clone)]
747enum KeyMaterial {
748    /// HMAC secret
749    Hmac(Vec<u8>),
750    /// RSA private and public keys
751    Rsa { private: Vec<u8>, public: Vec<u8> },
752}
753
754/// Public key material that can be serialized into a JWKS document.
755///
756/// Contains the RSA key components needed for JWT verification by external
757/// clients. Typically exposed via a `/.well-known/jwks.json` endpoint.
758#[derive(Debug, Clone, Serialize, Deserialize)]
759pub struct JwksPublicKey {
760    /// The JWT signing algorithm (e.g., RS256).
761    pub algorithm: Algorithm,
762    /// Key ID uniquely identifying this key in the JWKS key set.
763    pub kid: String,
764    /// RSA modulus, base64url-encoded.
765    pub n: String,
766    /// RSA public exponent, base64url-encoded.
767    pub e: String,
768}
769
770impl AuthToken {
771    /// Create a new authentication token.
772    pub fn new(
773        user_id: impl Into<String>,
774        access_token: impl Into<String>,
775        expires_in: std::time::Duration,
776        auth_method: impl Into<String>,
777    ) -> Self {
778        let now = Utc::now();
779        let expires_in_chrono =
780            chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
781
782        Self {
783            token_id: Uuid::new_v4().to_string(),
784            user_id: user_id.into(),
785            access_token: access_token.into(),
786            refresh_token: None,
787            token_type: Some("Bearer".to_string()),
788            subject: None,
789            issuer: None,
790            issued_at: now,
791            expires_at: now + expires_in_chrono,
792            scopes: crate::types::Scopes::empty(),
793            auth_method: auth_method.into(),
794            client_id: None,
795            user_profile: None,
796            permissions: crate::types::Permissions::empty(),
797            roles: crate::types::Roles::empty(),
798            metadata: TokenMetadata::default(),
799        }
800    }
801
802    /// Get the access token string.
803    ///
804    /// # Example
805    ///
806    /// ```rust
807    /// use auth_framework::tokens::AuthToken;
808    ///
809    /// let token = AuthToken::builder("t1", "u1", "my_token").build();
810    /// assert_eq!(token.access_token(), "my_token");
811    /// ```
812    pub fn access_token(&self) -> &str {
813        &self.access_token
814    }
815
816    /// Get the user ID.
817    ///
818    /// # Example
819    ///
820    /// ```rust
821    /// use auth_framework::tokens::AuthToken;
822    ///
823    /// let token = AuthToken::builder("t1", "user42", "access").build();
824    /// assert_eq!(token.user_id(), "user42");
825    /// ```
826    pub fn user_id(&self) -> &str {
827        &self.user_id
828    }
829
830    /// Get the expiration time.
831    ///
832    /// # Example
833    ///
834    /// ```rust
835    /// use auth_framework::tokens::AuthToken;
836    /// use chrono::Utc;
837    ///
838    /// let token = AuthToken::builder("t1", "u1", "access").build();
839    /// assert!(token.expires_at() > Utc::now());
840    /// ```
841    pub fn expires_at(&self) -> DateTime<Utc> {
842        self.expires_at
843    }
844
845    /// Get the token value.
846    ///
847    /// Alias for [`access_token()`](Self::access_token).
848    ///
849    /// # Example
850    ///
851    /// ```rust
852    /// use auth_framework::tokens::AuthToken;
853    ///
854    /// let token = AuthToken::builder("t1", "u1", "tok_value").build();
855    /// assert_eq!(token.token_value(), "tok_value");
856    /// ```
857    pub fn token_value(&self) -> &str {
858        &self.access_token
859    }
860
861    /// Get the token type.
862    ///
863    /// # Example
864    ///
865    /// ```rust
866    /// use auth_framework::tokens::AuthToken;
867    ///
868    /// let token = AuthToken::builder("t1", "u1", "access")
869    ///     .token_type("Bearer")
870    ///     .build();
871    /// assert_eq!(token.token_type(), Some("Bearer"));
872    /// ```
873    pub fn token_type(&self) -> Option<&str> {
874        self.token_type.as_deref()
875    }
876
877    /// Get the subject claim.
878    ///
879    /// # Example
880    ///
881    /// ```rust
882    /// use auth_framework::tokens::AuthToken;
883    ///
884    /// let token = AuthToken::builder("t1", "u1", "access")
885    ///     .subject("sub-123")
886    ///     .build();
887    /// assert_eq!(token.subject(), Some("sub-123"));
888    /// ```
889    pub fn subject(&self) -> Option<&str> {
890        self.subject.as_deref()
891    }
892
893    /// Get the issuer.
894    ///
895    /// # Example
896    ///
897    /// ```rust
898    /// use auth_framework::tokens::AuthToken;
899    ///
900    /// let token = AuthToken::builder("t1", "u1", "access")
901    ///     .issuer("my-service")
902    ///     .build();
903    /// assert_eq!(token.issuer(), Some("my-service"));
904    /// ```
905    pub fn issuer(&self) -> Option<&str> {
906        self.issuer.as_deref()
907    }
908
909    /// Check if the token has expired.
910    ///
911    /// # Example
912    ///
913    /// ```rust
914    /// use auth_framework::tokens::AuthToken;
915    ///
916    /// let token = AuthToken::builder("t1", "u1", "access").build();
917    /// assert!(!token.is_expired()); // 1-hour default
918    /// ```
919    pub fn is_expired(&self) -> bool {
920        Utc::now() > self.expires_at
921    }
922
923    /// Check if the token is expiring within the given duration.
924    ///
925    /// # Example
926    ///
927    /// ```rust
928    /// use auth_framework::tokens::AuthToken;
929    /// use std::time::Duration;
930    ///
931    /// let token = AuthToken::builder("t1", "u1", "access").build();
932    /// assert!(token.is_expiring(Duration::from_secs(7200))); // within 2 hours
933    /// ```
934    pub fn is_expiring(&self, within: Duration) -> bool {
935        Utc::now() + within > self.expires_at
936    }
937
938    /// Check if the token has been revoked.
939    ///
940    /// # Example
941    ///
942    /// ```rust
943    /// use auth_framework::tokens::AuthToken;
944    ///
945    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
946    /// assert!(!token.is_revoked());
947    /// token.revoke(Some("user request".to_string()));
948    /// assert!(token.is_revoked());
949    /// ```
950    pub fn is_revoked(&self) -> bool {
951        self.metadata.revoked
952    }
953
954    /// Check if the token is valid (not expired and not revoked).
955    ///
956    /// # Example
957    ///
958    /// ```rust
959    /// use auth_framework::tokens::AuthToken;
960    ///
961    /// let token = AuthToken::builder("t1", "u1", "access").build();
962    /// assert!(token.is_valid());
963    /// ```
964    pub fn is_valid(&self) -> bool {
965        !self.is_expired() && !self.is_revoked()
966    }
967
968    /// Check whether this token carries a refresh token.
969    ///
970    /// # Example
971    ///
972    /// ```rust
973    /// use auth_framework::tokens::AuthToken;
974    ///
975    /// let token = AuthToken::builder("t1", "u1", "access")
976    ///     .refresh_token("rt-abc")
977    ///     .build();
978    /// assert!(token.has_refresh_token());
979    /// ```
980    pub fn has_refresh_token(&self) -> bool {
981        self.refresh_token.is_some()
982    }
983
984    /// Return the refresh token string, if present.
985    ///
986    /// # Example
987    ///
988    /// ```rust
989    /// use auth_framework::tokens::AuthToken;
990    ///
991    /// let token = AuthToken::builder("t1", "u1", "access")
992    ///     .refresh_token("rt-xyz")
993    ///     .build();
994    /// assert_eq!(token.get_refresh_token(), Some("rt-xyz"));
995    /// ```
996    pub fn get_refresh_token(&self) -> Option<&str> {
997        self.refresh_token.as_deref()
998    }
999
1000    /// Revoke the token.
1001    ///
1002    /// # Example
1003    ///
1004    /// ```rust
1005    /// use auth_framework::tokens::AuthToken;
1006    ///
1007    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1008    /// token.revoke(Some("compromised".to_string()));
1009    /// assert!(token.is_revoked());
1010    /// ```
1011    pub fn revoke(&mut self, reason: Option<String>) {
1012        self.metadata.revoked = true;
1013        self.metadata.revoked_at = Some(Utc::now());
1014        self.metadata.revoked_reason = reason;
1015    }
1016
1017    /// Update the last used time and increment use count.
1018    ///
1019    /// # Example
1020    ///
1021    /// ```rust
1022    /// use auth_framework::tokens::AuthToken;
1023    ///
1024    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1025    /// assert_eq!(token.metadata.use_count, 0);
1026    /// token.mark_used();
1027    /// assert_eq!(token.metadata.use_count, 1);
1028    /// ```
1029    pub fn mark_used(&mut self) {
1030        self.metadata.last_used = Some(Utc::now());
1031        self.metadata.use_count += 1;
1032    }
1033
1034    /// Add a scope to the token.
1035    ///
1036    /// Duplicates are ignored.
1037    ///
1038    /// # Example
1039    ///
1040    /// ```rust
1041    /// use auth_framework::tokens::AuthToken;
1042    ///
1043    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1044    /// token.add_scope("read");
1045    /// assert!(token.has_scope("read"));
1046    /// ```
1047    pub fn add_scope(&mut self, scope: impl Into<String>) {
1048        let scope = scope.into();
1049        if !self.scopes.contains(&scope) {
1050            self.scopes.push(scope);
1051        }
1052    }
1053
1054    /// Check if the token has a specific scope.
1055    ///
1056    /// # Example
1057    ///
1058    /// ```rust
1059    /// use auth_framework::tokens::AuthToken;
1060    ///
1061    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1062    /// token.add_scope("write");
1063    /// assert!(token.has_scope("write"));
1064    /// assert!(!token.has_scope("admin"));
1065    /// ```
1066    pub fn has_scope(&self, scope: &str) -> bool {
1067        self.scopes.contains(scope)
1068    }
1069
1070    /// Set the refresh token.
1071    ///
1072    /// # Example
1073    ///
1074    /// ```rust
1075    /// use auth_framework::tokens::AuthToken;
1076    ///
1077    /// let token = AuthToken::builder("t1", "u1", "access").build()
1078    ///     .with_refresh_token("refresh_xyz");
1079    /// assert!(token.refresh_token.is_some());
1080    /// ```
1081    pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
1082        self.refresh_token = Some(refresh_token.into());
1083        self
1084    }
1085
1086    /// Set the client ID.
1087    ///
1088    /// # Example
1089    ///
1090    /// ```rust
1091    /// use auth_framework::tokens::AuthToken;
1092    ///
1093    /// let token = AuthToken::builder("t1", "u1", "access").build()
1094    ///     .with_client_id("app-client");
1095    /// assert_eq!(token.client_id.as_deref(), Some("app-client"));
1096    /// ```
1097    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
1098        self.client_id = Some(client_id.into());
1099        self
1100    }
1101
1102    /// Set the token scopes.
1103    ///
1104    /// # Example
1105    ///
1106    /// ```rust
1107    /// use auth_framework::tokens::AuthToken;
1108    /// use auth_framework::types::Scopes;
1109    ///
1110    /// let token = AuthToken::builder("t1", "u1", "access").build()
1111    ///     .with_scopes(Scopes::new(vec!["read".into()]));
1112    /// assert!(token.has_scope("read"));
1113    /// ```
1114    pub fn with_scopes(mut self, scopes: impl Into<crate::types::Scopes>) -> Self {
1115        self.scopes = scopes.into();
1116        self
1117    }
1118
1119    /// Add metadata to the token.
1120    ///
1121    /// # Example
1122    ///
1123    /// ```rust
1124    /// use auth_framework::tokens::{AuthToken, TokenMetadata};
1125    ///
1126    /// let meta = TokenMetadata::builder().issued_ip("192.168.1.1").build();
1127    /// let token = AuthToken::builder("t1", "u1", "access").build()
1128    ///     .with_metadata(meta);
1129    /// assert_eq!(token.metadata.issued_ip.as_deref(), Some("192.168.1.1"));
1130    /// ```
1131    pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
1132        self.metadata = metadata;
1133        self
1134    }
1135
1136    /// Get time until expiration.
1137    ///
1138    /// Returns `Duration::ZERO` if the token has already expired.
1139    ///
1140    /// # Example
1141    ///
1142    /// ```rust
1143    /// use auth_framework::tokens::AuthToken;
1144    /// use std::time::Duration;
1145    ///
1146    /// let token = AuthToken::builder("t1", "u1", "access").build();
1147    /// assert!(token.time_until_expiry() > Duration::ZERO);
1148    /// ```
1149    pub fn time_until_expiry(&self) -> Duration {
1150        let now = Utc::now();
1151        if self.expires_at > now {
1152            (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
1153        } else {
1154            Duration::ZERO
1155        }
1156    }
1157
1158    /// Add a custom claim to the token metadata.
1159    ///
1160    /// # Example
1161    ///
1162    /// ```rust
1163    /// use auth_framework::tokens::AuthToken;
1164    ///
1165    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1166    /// token.add_custom_claim("tenant", serde_json::json!("acme"));
1167    /// assert_eq!(token.get_custom_claim("tenant").unwrap(), &serde_json::json!("acme"));
1168    /// ```
1169    pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
1170        self.metadata.custom.insert(key.into(), value);
1171    }
1172
1173    /// Get a custom claim from the token metadata.
1174    ///
1175    /// # Example
1176    ///
1177    /// ```rust
1178    /// use auth_framework::tokens::AuthToken;
1179    ///
1180    /// let token = AuthToken::builder("t1", "u1", "access").build();
1181    /// assert!(token.get_custom_claim("missing").is_none());
1182    /// ```
1183    pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
1184        self.metadata.custom.get(key)
1185    }
1186
1187    /// Check if the token has a specific permission.
1188    ///
1189    /// # Example
1190    ///
1191    /// ```rust
1192    /// use auth_framework::tokens::AuthToken;
1193    ///
1194    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1195    /// token.add_permission("admin");
1196    /// assert!(token.has_permission("admin"));
1197    /// ```
1198    pub fn has_permission(&self, permission: &str) -> bool {
1199        self.permissions.contains(permission)
1200    }
1201
1202    /// Add a permission to the token.
1203    ///
1204    /// Duplicates are ignored.
1205    ///
1206    /// # Example
1207    ///
1208    /// ```rust
1209    /// use auth_framework::tokens::AuthToken;
1210    ///
1211    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1212    /// token.add_permission("write");
1213    /// assert!(token.has_permission("write"));
1214    /// ```
1215    pub fn add_permission(&mut self, permission: impl Into<String>) {
1216        let permission = permission.into();
1217        if !self.permissions.contains(&permission) {
1218            self.permissions.push(permission);
1219        }
1220    }
1221
1222    /// Add a role to the token.
1223    ///
1224    /// Duplicates are ignored.
1225    ///
1226    /// # Example
1227    ///
1228    /// ```rust
1229    /// use auth_framework::tokens::AuthToken;
1230    ///
1231    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1232    /// token.add_role("editor");
1233    /// assert!(token.has_role("editor"));
1234    /// ```
1235    pub fn add_role(&mut self, role: impl Into<String>) {
1236        let role = role.into();
1237        if !self.roles.contains(&role) {
1238            self.roles.push(role);
1239        }
1240    }
1241
1242    /// Check if the token has a specific role.
1243    ///
1244    /// # Example
1245    ///
1246    /// ```rust
1247    /// use auth_framework::tokens::AuthToken;
1248    ///
1249    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1250    /// token.add_role("admin");
1251    /// assert!(token.has_role("admin"));
1252    /// assert!(!token.has_role("guest"));
1253    /// ```
1254    pub fn has_role(&self, role: &str) -> bool {
1255        self.roles.contains(role)
1256    }
1257
1258    /// Set the permissions.
1259    ///
1260    /// # Example
1261    ///
1262    /// ```rust
1263    /// use auth_framework::tokens::AuthToken;
1264    /// use auth_framework::types::Permissions;
1265    ///
1266    /// let token = AuthToken::builder("t1", "u1", "access").build()
1267    ///     .with_permissions(Permissions::new(vec!["read".into()]));
1268    /// assert!(token.has_permission("read"));
1269    /// ```
1270    pub fn with_permissions(mut self, permissions: impl Into<crate::types::Permissions>) -> Self {
1271        self.permissions = permissions.into();
1272        self
1273    }
1274
1275    /// Set the roles.
1276    ///
1277    /// # Example
1278    ///
1279    /// ```rust
1280    /// use auth_framework::tokens::AuthToken;
1281    /// use auth_framework::types::Roles;
1282    ///
1283    /// let token = AuthToken::builder("t1", "u1", "access").build()
1284    ///     .with_roles(Roles::new(vec!["viewer".into()]));
1285    /// assert!(token.has_role("viewer"));
1286    /// ```
1287    pub fn with_roles(mut self, roles: impl Into<crate::types::Roles>) -> Self {
1288        self.roles = roles.into();
1289        self
1290    }
1291}
1292
1293impl Clone for TokenManager {
1294    fn clone(&self) -> Self {
1295        let (previous_decoding_key, previous_key_material) = match &self.previous_key_material {
1296            Some(KeyMaterial::Hmac(secret)) => (
1297                Some(DecodingKey::from_secret(secret)),
1298                Some(KeyMaterial::Hmac(secret.clone())),
1299            ),
1300            Some(KeyMaterial::Rsa { public, .. }) => (
1301                DecodingKey::from_rsa_pem(public).ok(),
1302                self.previous_key_material.clone(),
1303            ),
1304            None => (None, None),
1305        };
1306        match &self.key_material {
1307            KeyMaterial::Hmac(secret) => Self {
1308                encoding_key: EncodingKey::from_secret(secret),
1309                decoding_key: DecodingKey::from_secret(secret),
1310                previous_decoding_key,
1311                key_material: self.key_material.clone(),
1312                previous_key_material,
1313                algorithm: self.algorithm,
1314                issuer: self.issuer.clone(),
1315                audience: self.audience.clone(),
1316                default_lifetime: self.default_lifetime,
1317            },
1318            KeyMaterial::Rsa { private, public } => Self {
1319                // SAFETY: The PEM was already validated when the TokenManager was first
1320                // constructed; re-parsing it here during Clone cannot fail unless the
1321                // bytes were corrupted in memory, which would be a catastrophic bug.
1322                encoding_key: EncodingKey::from_rsa_pem(private).expect("RSA private key PEM re-parse failed during Clone — this indicates memory corruption"),
1323                decoding_key: DecodingKey::from_rsa_pem(public).expect("RSA public key PEM re-parse failed during Clone — this indicates memory corruption"),
1324                previous_decoding_key,
1325                key_material: self.key_material.clone(),
1326                previous_key_material,
1327                algorithm: self.algorithm,
1328                issuer: self.issuer.clone(),
1329                audience: self.audience.clone(),
1330                default_lifetime: self.default_lifetime,
1331            },
1332        }
1333    }
1334}
1335
1336/// Strip PEM headers/footers and whitespace, then base64-decode to DER.
1337fn pem_to_der(pem: &str) -> Result<Vec<u8>> {
1338    let b64: String = pem
1339        .lines()
1340        .filter(|line| {
1341            !line.starts_with("-----BEGIN") && !line.starts_with("-----END") && !line.is_empty()
1342        })
1343        .collect();
1344
1345    base64::engine::general_purpose::STANDARD
1346        .decode(&b64)
1347        .map_err(|e| AuthError::crypto(format!("Failed to base64-decode PEM: {e}")))
1348}
1349
1350impl TokenManager {
1351    fn jwks_from_public_pem(public_key: &[u8], algorithm: Algorithm) -> Result<JwksPublicKey> {
1352        let pem = std::str::from_utf8(public_key)
1353            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key PEM encoding: {e}")))?;
1354        let der = pem_to_der(pem)?;
1355
1356        // `PublicKey::from_der` parses either RFC8017 (PKCS#1) or RFC5280
1357        // (X.509 SubjectPublicKeyInfo / PKCS#8) DER automatically -- no need
1358        // to try two separate parse paths as the `rsa` crate required.
1359        let public_key = aws_lc_rs::rsa::PublicKey::from_der(&der).map_err(|e| {
1360            AuthError::crypto(format!(
1361                "Failed to parse RSA public key for JWKS export: {e}"
1362            ))
1363        })?;
1364
1365        let modulus = public_key.modulus().big_endian_without_leading_zero();
1366        let exponent = public_key.exponent().big_endian_without_leading_zero();
1367        let kid_digest = Sha256::digest(modulus);
1368
1369        let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus);
1370        let e = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(exponent);
1371        let kid = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(kid_digest);
1372
1373        Ok(JwksPublicKey {
1374            algorithm,
1375            kid,
1376            n,
1377            e,
1378        })
1379    }
1380
1381    /// Export the current and previous RSA verification keys as JWKS-compatible material.
1382    pub fn export_public_jwks(&self) -> Result<Vec<JwksPublicKey>> {
1383        let mut keys = Vec::new();
1384
1385        if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1386            keys.push(Self::jwks_from_public_pem(public, self.algorithm)?);
1387        }
1388
1389        if let Some(KeyMaterial::Rsa { public, .. }) = &self.previous_key_material {
1390            let previous = Self::jwks_from_public_pem(public, self.algorithm)?;
1391            if !keys.iter().any(|key| key.kid == previous.kid) {
1392                keys.push(previous);
1393            }
1394        }
1395
1396        Ok(keys)
1397    }
1398
1399    /// Create a new token manager with HMAC key.
1400    pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
1401        Self {
1402            encoding_key: EncodingKey::from_secret(secret),
1403            decoding_key: DecodingKey::from_secret(secret),
1404            previous_decoding_key: None,
1405            key_material: KeyMaterial::Hmac(secret.to_vec()),
1406            previous_key_material: None,
1407            algorithm: Algorithm::HS256,
1408            issuer: issuer.into(),
1409            audience: audience.into(),
1410            default_lifetime: Duration::from_secs(3600), // 1 hour
1411        }
1412    }
1413
1414    /// Create a new token manager with RSA keys.
1415    ///
1416    /// ## RSA Key Format Support
1417    ///
1418    /// This method supports RSA keys in both standard PEM formats:
1419    /// - **PKCS#1**: `-----BEGIN RSA PRIVATE KEY-----` (traditional RSA format)
1420    /// - **PKCS#8**: `-----BEGIN PRIVATE KEY-----` (modern standard format, recommended)
1421    ///
1422    /// Both formats are automatically detected and parsed. No format conversion is required.
1423    ///
1424    /// ## Example
1425    ///
1426    /// ```rust,no_run
1427    /// use auth_framework::tokens::TokenManager;
1428    ///
1429    /// // Both PKCS#1 and PKCS#8 formats work; provide PEM bytes from your key store.
1430    /// # let private_key: &[u8] = b"";
1431    /// # let public_key: &[u8] = b"";
1432    ///
1433    /// let manager = TokenManager::new_rsa(
1434    ///     private_key,
1435    ///     public_key,
1436    ///     "my-service",
1437    ///     "my-audience"
1438    /// )?;
1439    /// # Ok::<(), auth_framework::errors::AuthError>(())
1440    /// ```
1441    pub fn new_rsa(
1442        private_key: &[u8],
1443        public_key: &[u8],
1444        issuer: impl Into<String>,
1445        audience: impl Into<String>,
1446    ) -> Result<Self> {
1447        let encoding_key = EncodingKey::from_rsa_pem(private_key)
1448            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1449
1450        let decoding_key = DecodingKey::from_rsa_pem(public_key)
1451            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1452
1453        Ok(Self {
1454            encoding_key,
1455            decoding_key,
1456            previous_decoding_key: None,
1457            key_material: KeyMaterial::Rsa {
1458                private: private_key.to_vec(),
1459                public: public_key.to_vec(),
1460            },
1461            previous_key_material: None,
1462            algorithm: Algorithm::RS256,
1463            issuer: issuer.into(),
1464            audience: audience.into(),
1465            default_lifetime: Duration::from_secs(3600), // 1 hour
1466        })
1467    }
1468
1469    /// Rotate HMAC key, keeping the current key as the previous decoding key
1470    /// to seamlessly allow verification of tokens signed with the old key.
1471    pub fn rotate_hmac_key(&mut self, new_secret: &[u8]) {
1472        // Move current key to previous
1473        if let KeyMaterial::Hmac(secret) = &self.key_material {
1474            self.previous_decoding_key = Some(DecodingKey::from_secret(secret));
1475            self.previous_key_material = Some(KeyMaterial::Hmac(secret.clone()));
1476        }
1477
1478        // Set new key
1479        self.encoding_key = EncodingKey::from_secret(new_secret);
1480        self.decoding_key = DecodingKey::from_secret(new_secret);
1481        self.key_material = KeyMaterial::Hmac(new_secret.to_vec());
1482        self.algorithm = Algorithm::HS256;
1483    }
1484
1485    /// Rotate RSA key, keeping the current key as the previous decoding key
1486    /// to seamlessly allow verification of tokens signed with the old key.
1487    pub fn rotate_rsa_key(&mut self, private_key: &[u8], public_key: &[u8]) -> Result<()> {
1488        let new_encoding_key = EncodingKey::from_rsa_pem(private_key)
1489            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1490        let new_decoding_key = DecodingKey::from_rsa_pem(public_key)
1491            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1492
1493        // Move current key to previous
1494        if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1495            self.previous_decoding_key = DecodingKey::from_rsa_pem(public).ok();
1496            self.previous_key_material = Some(self.key_material.clone());
1497        }
1498
1499        // Set new key
1500        self.encoding_key = new_encoding_key;
1501        self.decoding_key = new_decoding_key;
1502        self.key_material = KeyMaterial::Rsa {
1503            private: private_key.to_vec(),
1504            public: public_key.to_vec(),
1505        };
1506        self.algorithm = Algorithm::RS256;
1507
1508        Ok(())
1509    }
1510
1511    /// Retire the previous key (if any), so tokens signed with it are no longer valid.
1512    pub fn retire_previous_key(&mut self) {
1513        self.previous_decoding_key = None;
1514        self.previous_key_material = None;
1515    }
1516
1517    /// Set the default token lifetime.
1518    pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
1519        self.default_lifetime = lifetime;
1520        self
1521    }
1522
1523    /// Create a new JWT token.
1524    pub fn create_jwt_token(
1525        &self,
1526        user_id: impl Into<String>,
1527        scopes: Vec<String>,
1528        lifetime: Option<Duration>,
1529    ) -> Result<String> {
1530        let user_id = user_id.into();
1531        let lifetime = lifetime.unwrap_or(self.default_lifetime);
1532        let now = Utc::now();
1533        let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
1534
1535        let claims = JwtClaims {
1536            sub: user_id,
1537            iss: self.issuer.clone(),
1538            aud: self.audience.clone(),
1539            exp: exp.timestamp(),
1540            iat: now.timestamp(),
1541            nbf: now.timestamp(),
1542            jti: Uuid::new_v4().to_string(),
1543            scope: scopes.join(" "),
1544            permissions: None,
1545            roles: None,
1546            client_id: None,
1547            custom: HashMap::new(),
1548        };
1549
1550        let header = Header::new(self.algorithm);
1551
1552        encode(&header, &claims, &self.encoding_key)
1553            .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
1554    }
1555
1556    /// Validate and decode a JWT token.
1557    pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
1558        let mut validation = Validation::new(self.algorithm);
1559        validation.set_issuer(&[&self.issuer]);
1560        validation.set_audience(&[&self.audience]);
1561
1562        match decode::<JwtClaims>(token, &self.decoding_key, &validation) {
1563            Ok(token_data) => Ok(token_data.claims),
1564            Err(e) => {
1565                match e.kind() {
1566                    jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
1567                        Err(AuthError::Token(TokenError::Expired))
1568                    }
1569                    jsonwebtoken::errors::ErrorKind::InvalidSignature => {
1570                        // If signature is invalid, try the previous key if configured
1571                        if let Some(prev_key) = &self.previous_decoding_key
1572                            && let Ok(prev_token_data) =
1573                                decode::<JwtClaims>(token, prev_key, &validation)
1574                        {
1575                            return Ok(prev_token_data.claims);
1576                        }
1577
1578                        Err(AuthError::Token(TokenError::Invalid {
1579                            message: "Invalid token signature".to_string(),
1580                        }))
1581                    }
1582                    _ => Err(AuthError::Token(TokenError::Invalid {
1583                        message: "Invalid token format".to_string(),
1584                    })),
1585                }
1586            }
1587        }
1588    }
1589
1590    /// Create a complete authentication token with JWT.
1591    pub fn create_auth_token(
1592        &self,
1593        user_id: impl Into<String>,
1594        scopes: impl Into<crate::types::Scopes>,
1595        auth_method: impl Into<String>,
1596        lifetime: Option<std::time::Duration>,
1597    ) -> Result<AuthToken> {
1598        let user_id_str = user_id.into();
1599        let scopes: crate::types::Scopes = scopes.into();
1600        let lifetime = lifetime.unwrap_or(self.default_lifetime);
1601
1602        let jwt_token = self.create_jwt_token(&user_id_str, scopes.to_vec(), Some(lifetime))?;
1603
1604        let token =
1605            AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
1606
1607        Ok(token)
1608    }
1609
1610    /// Validate an authentication token.
1611    pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
1612        // Check if token is expired
1613        if token.is_expired() {
1614            return Err(TokenError::Expired.into());
1615        }
1616
1617        // Check if token is revoked
1618        if token.is_revoked() {
1619            return Err(TokenError::Invalid {
1620                message: "Token has been revoked".to_string(),
1621            }
1622            .into());
1623        }
1624
1625        // Validate JWT if it's a JWT token
1626        if token.auth_method == "jwt" || token.access_token.contains('.') {
1627            self.validate_jwt_token(&token.access_token)?;
1628        }
1629
1630        Ok(())
1631    }
1632
1633    /// Refresh a token (create a new one with extended lifetime).
1634    pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1635        if token.is_expired() {
1636            return Err(TokenError::Expired.into());
1637        }
1638
1639        if token.is_revoked() {
1640            return Err(TokenError::Invalid {
1641                message: "Cannot refresh revoked token".to_string(),
1642            }
1643            .into());
1644        }
1645
1646        // Create a new token with the same properties but new expiry
1647        self.create_auth_token(
1648            &token.user_id,
1649            token.scopes.clone(),
1650            &token.auth_method,
1651            Some(self.default_lifetime),
1652        )
1653    }
1654
1655    /// Extract token information from a JWT.
1656    pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
1657        let claims = self.validate_jwt_token(token)?;
1658
1659        Ok(TokenInfo {
1660            user_id: claims.sub,
1661            username: claims
1662                .custom
1663                .get("username")
1664                .and_then(|v| v.as_str())
1665                .map(|s| s.to_string()),
1666            email: claims
1667                .custom
1668                .get("email")
1669                .and_then(|v| v.as_str())
1670                .map(|s| s.to_string()),
1671            name: claims
1672                .custom
1673                .get("name")
1674                .and_then(|v| v.as_str())
1675                .map(|s| s.to_string()),
1676            roles: claims
1677                .custom
1678                .get("roles")
1679                .and_then(|v| v.as_array())
1680                .map(|arr| {
1681                    arr.iter()
1682                        .filter_map(|v| v.as_str())
1683                        .map(|s| s.to_string())
1684                        .collect()
1685                })
1686                .unwrap_or_default(),
1687            permissions: claims
1688                .scope
1689                .split_whitespace()
1690                .map(|s| s.to_string())
1691                .collect(),
1692            attributes: claims.custom,
1693        })
1694    }
1695}
1696
1697/// Trait for converting tokens to user profiles
1698#[async_trait::async_trait]
1699pub trait TokenToProfile {
1700    /// Convert this token to a user profile using the specified provider
1701    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile>;
1702
1703    /// Convert this token to a user profile with a custom extractor
1704    async fn to_profile_with_extractor(
1705        &self,
1706        provider: &OAuthProvider,
1707        extractor: &ProfileExtractor,
1708    ) -> Result<ProviderProfile>;
1709}
1710
1711#[async_trait::async_trait]
1712impl TokenToProfile for AuthToken {
1713    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile> {
1714        let extractor = ProfileExtractor::new();
1715        extractor.extract_profile(self, provider).await
1716    }
1717
1718    async fn to_profile_with_extractor(
1719        &self,
1720        provider: &OAuthProvider,
1721        extractor: &ProfileExtractor,
1722    ) -> Result<ProviderProfile> {
1723        extractor.extract_profile(self, provider).await
1724    }
1725}
1726
1727#[cfg(test)]
1728mod tests {
1729    use super::*;
1730
1731    #[test]
1732    fn test_auth_token_creation() {
1733        let token = AuthToken::new(
1734            "user123",
1735            "token123",
1736            Duration::from_secs(3600), // 1 hour
1737            "password",
1738        );
1739
1740        assert_eq!(token.user_id(), "user123");
1741        assert_eq!(token.access_token(), "token123");
1742        assert!(!token.is_expired());
1743        assert!(!token.is_revoked());
1744        assert!(token.is_valid());
1745    }
1746
1747    #[test]
1748    fn test_token_expiry() {
1749        let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
1750
1751        // Wait a bit to ensure expiry
1752        std::thread::sleep(std::time::Duration::from_millis(10));
1753
1754        assert!(token.is_expired());
1755        assert!(!token.is_valid());
1756    }
1757
1758    #[test]
1759    fn test_token_revocation() {
1760        let mut token = AuthToken::new(
1761            "user123",
1762            "token123",
1763            Duration::from_secs(3600), // 1 hour
1764            "password",
1765        );
1766
1767        assert!(!token.is_revoked());
1768
1769        token.revoke(Some("User logout".to_string()));
1770
1771        assert!(token.is_revoked());
1772        assert!(!token.is_valid());
1773        assert!(token.metadata.revoked);
1774    }
1775
1776    fn generate_test_rsa_pems() -> (Vec<u8>, Vec<u8>) {
1777        use aws_lc_rs::signature::KeyPair as _;
1778
1779        fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
1780            let b64 = base64::engine::general_purpose::STANDARD.encode(der);
1781            let mut pem = format!("-----BEGIN {label}-----\n");
1782            for chunk in b64.as_bytes().chunks(64) {
1783                pem.push_str(std::str::from_utf8(chunk).unwrap());
1784                pem.push('\n');
1785            }
1786            pem.push_str(&format!("-----END {label}-----\n"));
1787            pem.into_bytes()
1788        }
1789
1790        let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
1791            .expect("RSA key generation failed");
1792        let priv_der =
1793            aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
1794                .expect("private key DER export failed");
1795        let pub_der = key_pair.public_key().as_ref();
1796
1797        (
1798            der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
1799            // PublicKey::as_ref() returns RFC8017 (PKCS#1 RSAPublicKey) DER,
1800            // not SPKI -- label accordingly, matching jsonwebtoken's own
1801            // PEM classifier (Standard::Pkcs1 for the "RSA PUBLIC KEY" tag).
1802            der_to_pem(pub_der, "RSA PUBLIC KEY"),
1803        )
1804    }
1805
1806    /// Same key pair as `generate_test_rsa_pems`, but the public half in
1807    /// SPKI/PKCS#8 ("PUBLIC KEY") form -- the format the old `rsa` crate's
1808    /// `from_public_key_pem` treated as primary, and a different parse path
1809    /// through `jwks_from_public_pem`/`pem_to_der` than the PKCS#1 form
1810    /// above.
1811    fn generate_test_rsa_pems_spki_public() -> (Vec<u8>, Vec<u8>) {
1812        use aws_lc_rs::signature::KeyPair as _;
1813
1814        fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
1815            let b64 = base64::engine::general_purpose::STANDARD.encode(der);
1816            let mut pem = format!("-----BEGIN {label}-----\n");
1817            for chunk in b64.as_bytes().chunks(64) {
1818                pem.push_str(std::str::from_utf8(chunk).unwrap());
1819                pem.push('\n');
1820            }
1821            pem.push_str(&format!("-----END {label}-----\n"));
1822            pem.into_bytes()
1823        }
1824
1825        let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
1826            .expect("RSA key generation failed");
1827        let priv_der =
1828            aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
1829                .expect("private key DER export failed");
1830        let public_key = aws_lc_rs::rsa::PublicKey::from_der(key_pair.public_key().as_ref())
1831            .expect("re-parsing the freshly generated public key must succeed");
1832        let spki_der = aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::PublicKeyX509Der>::as_der(
1833            &public_key,
1834        )
1835        .expect("SPKI DER export failed");
1836
1837        (
1838            der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
1839            der_to_pem(spki_der.as_ref(), "PUBLIC KEY"),
1840        )
1841    }
1842
1843    /// Regression/coverage test for the RSA-removal rewrite of
1844    /// `jwks_from_public_pem`: a real RSA key's exported JWKS `n`/`e` must
1845    /// match the key's own modulus/exponent, and the exported key must
1846    /// actually be usable to verify a token signed by the paired private key.
1847    #[test]
1848    fn test_export_public_jwks_round_trips_rsa_key() {
1849        let (priv_pem, pub_pem) = generate_test_rsa_pems();
1850        let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
1851            .expect("TokenManager::new_rsa should accept a freshly generated RSA key pair");
1852
1853        let jwks = manager
1854            .export_public_jwks()
1855            .expect("JWKS export should succeed for a valid RSA key");
1856        assert_eq!(jwks.len(), 1, "exactly one key, no previous key configured");
1857
1858        let exported = &jwks[0];
1859        assert_eq!(exported.algorithm, Algorithm::RS256);
1860        assert!(!exported.n.is_empty());
1861        assert!(!exported.e.is_empty());
1862
1863        // Independently re-derive n/e directly from the DER and confirm they
1864        // match what jwks_from_public_pem produced -- not just "didn't error."
1865        let der = pem_to_der(std::str::from_utf8(&pub_pem).unwrap()).unwrap();
1866        let public_key =
1867            aws_lc_rs::rsa::PublicKey::from_der(&der).expect("public key DER should parse");
1868        let expected_n = base64::engine::general_purpose::URL_SAFE_NO_PAD
1869            .encode(public_key.modulus().big_endian_without_leading_zero());
1870        let expected_e = base64::engine::general_purpose::URL_SAFE_NO_PAD
1871            .encode(public_key.exponent().big_endian_without_leading_zero());
1872        assert_eq!(exported.n, expected_n);
1873        assert_eq!(exported.e, expected_e);
1874
1875        // The exported JWKS must be independently usable: sign a real token
1876        // with the manager's private key, then verify it using ONLY the
1877        // exported n/e (not the manager, not the PEM) -- the actual use case
1878        // a resource server validating against a published JWKS exercises.
1879        let token = manager
1880            .create_jwt_token("test-user", vec![], None)
1881            .expect("signing with the freshly generated RSA key should succeed");
1882        let decoding_key = DecodingKey::from_rsa_components(&exported.n, &exported.e)
1883            .expect("DecodingKey should accept the exported n/e");
1884        let mut validation = Validation::new(Algorithm::RS256);
1885        validation.set_issuer(&["test-issuer"]);
1886        validation.set_audience(&["test-audience"]);
1887        decode::<JwtClaims>(&token, &decoding_key, &validation)
1888            .expect("a token signed by this key must verify against its own exported JWKS");
1889    }
1890
1891    /// Same as the PKCS#1 test above, but for the SPKI ("PUBLIC KEY") PEM
1892    /// form -- the format the old `rsa` crate's `from_public_key_pem`
1893    /// treated as primary, and a different parse path through
1894    /// `pem_to_der`/`PublicKey::from_der` than the PKCS#1 form.
1895    #[test]
1896    fn test_export_public_jwks_accepts_spki_public_key_pem() {
1897        let (priv_pem, pub_pem) = generate_test_rsa_pems_spki_public();
1898        let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
1899            .expect("TokenManager::new_rsa should accept an SPKI-form public key");
1900
1901        let jwks = manager
1902            .export_public_jwks()
1903            .expect("JWKS export should succeed for an SPKI-form RSA public key");
1904        assert_eq!(jwks.len(), 1);
1905        assert!(!jwks[0].n.is_empty());
1906        assert!(!jwks[0].e.is_empty());
1907    }
1908}