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