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