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 accepted only while the previous key is
771    /// live: inside the grace window after the rotation, for a token issued before the
772    /// rotation and with a lifetime no longer than the configured maximum. After the
773    /// grace window the key is treated as retired without anyone calling
774    /// [`TokenManager::retire_previous_key`] (which still retires it at once).
775    previous_decoding_key: Option<DecodingKey>,
776
777    /// Unix time of the rotation that made the current previous key "previous".
778    previous_rotated_at: Option<i64>,
779
780    /// How long the previous key keeps verifying tokens after a rotation.
781    previous_key_grace: Duration,
782
783    /// Longest token lifetime (`exp - iat`) accepted under the previous key.
784    previous_key_max_token_lifetime: Duration,
785
786    /// Key material for recreating keys during clone
787    key_material: KeyMaterial,
788
789    /// Key material for the previous key (for clone support after rotation)
790    previous_key_material: Option<KeyMaterial>,
791
792    /// JWT algorithm
793    algorithm: Algorithm,
794
795    /// Token issuer
796    issuer: String,
797
798    /// Token audience
799    audience: String,
800
801    /// Default token lifetime
802    default_lifetime: Duration,
803}
804
805/// Default grace window, and default longest token lifetime, for the previous key after a
806/// rotation (24 hours).
807const DEFAULT_PREVIOUS_KEY_WINDOW: Duration = Duration::from_secs(24 * 3600);
808
809/// Key material for cloning TokenManager
810#[derive(Clone)]
811enum KeyMaterial {
812    /// HMAC secret
813    Hmac(Vec<u8>),
814    /// RSA private and public keys
815    Rsa { private: Vec<u8>, public: Vec<u8> },
816}
817
818/// Public key material that can be serialized into a JWKS document.
819///
820/// Contains the RSA key components needed for JWT verification by external
821/// clients. Typically exposed via a `/.well-known/jwks.json` endpoint.
822#[derive(Debug, Clone, Serialize, Deserialize)]
823pub struct JwksPublicKey {
824    /// The JWT signing algorithm (e.g., RS256).
825    pub algorithm: Algorithm,
826    /// Key ID uniquely identifying this key in the JWKS key set.
827    pub kid: String,
828    /// RSA modulus, base64url-encoded.
829    pub n: String,
830    /// RSA public exponent, base64url-encoded.
831    pub e: String,
832}
833
834impl AuthToken {
835    /// Create a new authentication token.
836    pub fn new(
837        user_id: impl Into<String>,
838        access_token: impl Into<String>,
839        expires_in: std::time::Duration,
840        auth_method: impl Into<String>,
841    ) -> Self {
842        let now = Utc::now();
843        let expires_in_chrono =
844            chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
845
846        Self {
847            token_id: Uuid::new_v4().to_string(),
848            user_id: user_id.into(),
849            access_token: access_token.into(),
850            refresh_token: None,
851            token_type: Some("Bearer".to_string()),
852            subject: None,
853            issuer: None,
854            issued_at: now,
855            expires_at: now + expires_in_chrono,
856            scopes: crate::types::Scopes::empty(),
857            auth_method: auth_method.into(),
858            client_id: None,
859            user_profile: None,
860            permissions: crate::types::Permissions::empty(),
861            roles: crate::types::Roles::empty(),
862            metadata: TokenMetadata::default(),
863        }
864    }
865
866    /// Get the access token string.
867    ///
868    /// # Example
869    ///
870    /// ```rust
871    /// use auth_framework::tokens::AuthToken;
872    ///
873    /// let token = AuthToken::builder("t1", "u1", "my_token").build();
874    /// assert_eq!(token.access_token(), "my_token");
875    /// ```
876    pub fn access_token(&self) -> &str {
877        &self.access_token
878    }
879
880    /// Get the user ID.
881    ///
882    /// # Example
883    ///
884    /// ```rust
885    /// use auth_framework::tokens::AuthToken;
886    ///
887    /// let token = AuthToken::builder("t1", "user42", "access").build();
888    /// assert_eq!(token.user_id(), "user42");
889    /// ```
890    pub fn user_id(&self) -> &str {
891        &self.user_id
892    }
893
894    /// Get the expiration time.
895    ///
896    /// # Example
897    ///
898    /// ```rust
899    /// use auth_framework::tokens::AuthToken;
900    /// use chrono::Utc;
901    ///
902    /// let token = AuthToken::builder("t1", "u1", "access").build();
903    /// assert!(token.expires_at() > Utc::now());
904    /// ```
905    pub fn expires_at(&self) -> DateTime<Utc> {
906        self.expires_at
907    }
908
909    /// Get the token value.
910    ///
911    /// Alias for [`access_token()`](Self::access_token).
912    ///
913    /// # Example
914    ///
915    /// ```rust
916    /// use auth_framework::tokens::AuthToken;
917    ///
918    /// let token = AuthToken::builder("t1", "u1", "tok_value").build();
919    /// assert_eq!(token.token_value(), "tok_value");
920    /// ```
921    pub fn token_value(&self) -> &str {
922        &self.access_token
923    }
924
925    /// Get the token type.
926    ///
927    /// # Example
928    ///
929    /// ```rust
930    /// use auth_framework::tokens::AuthToken;
931    ///
932    /// let token = AuthToken::builder("t1", "u1", "access")
933    ///     .token_type("Bearer")
934    ///     .build();
935    /// assert_eq!(token.token_type(), Some("Bearer"));
936    /// ```
937    pub fn token_type(&self) -> Option<&str> {
938        self.token_type.as_deref()
939    }
940
941    /// Get the subject claim.
942    ///
943    /// # Example
944    ///
945    /// ```rust
946    /// use auth_framework::tokens::AuthToken;
947    ///
948    /// let token = AuthToken::builder("t1", "u1", "access")
949    ///     .subject("sub-123")
950    ///     .build();
951    /// assert_eq!(token.subject(), Some("sub-123"));
952    /// ```
953    pub fn subject(&self) -> Option<&str> {
954        self.subject.as_deref()
955    }
956
957    /// Get the issuer.
958    ///
959    /// # Example
960    ///
961    /// ```rust
962    /// use auth_framework::tokens::AuthToken;
963    ///
964    /// let token = AuthToken::builder("t1", "u1", "access")
965    ///     .issuer("my-service")
966    ///     .build();
967    /// assert_eq!(token.issuer(), Some("my-service"));
968    /// ```
969    pub fn issuer(&self) -> Option<&str> {
970        self.issuer.as_deref()
971    }
972
973    /// Check if the token has expired.
974    ///
975    /// # Example
976    ///
977    /// ```rust
978    /// use auth_framework::tokens::AuthToken;
979    ///
980    /// let token = AuthToken::builder("t1", "u1", "access").build();
981    /// assert!(!token.is_expired()); // 1-hour default
982    /// ```
983    pub fn is_expired(&self) -> bool {
984        Utc::now() > self.expires_at
985    }
986
987    /// Check if the token is expiring within the given duration.
988    ///
989    /// # Example
990    ///
991    /// ```rust
992    /// use auth_framework::tokens::AuthToken;
993    /// use std::time::Duration;
994    ///
995    /// let token = AuthToken::builder("t1", "u1", "access").build();
996    /// assert!(token.is_expiring(Duration::from_secs(7200))); // within 2 hours
997    /// ```
998    pub fn is_expiring(&self, within: Duration) -> bool {
999        Utc::now() + within > self.expires_at
1000    }
1001
1002    /// Check if the token has been revoked.
1003    ///
1004    /// # Example
1005    ///
1006    /// ```rust
1007    /// use auth_framework::tokens::AuthToken;
1008    ///
1009    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1010    /// assert!(!token.is_revoked());
1011    /// token.revoke(Some("user request".to_string()));
1012    /// assert!(token.is_revoked());
1013    /// ```
1014    pub fn is_revoked(&self) -> bool {
1015        self.metadata.revoked
1016    }
1017
1018    /// Check if the token is valid (not expired and not revoked).
1019    ///
1020    /// # Example
1021    ///
1022    /// ```rust
1023    /// use auth_framework::tokens::AuthToken;
1024    ///
1025    /// let token = AuthToken::builder("t1", "u1", "access").build();
1026    /// assert!(token.is_valid());
1027    /// ```
1028    pub fn is_valid(&self) -> bool {
1029        !self.is_expired() && !self.is_revoked()
1030    }
1031
1032    /// Check whether this token carries a refresh token.
1033    ///
1034    /// # Example
1035    ///
1036    /// ```rust
1037    /// use auth_framework::tokens::AuthToken;
1038    ///
1039    /// let token = AuthToken::builder("t1", "u1", "access")
1040    ///     .refresh_token("rt-abc")
1041    ///     .build();
1042    /// assert!(token.has_refresh_token());
1043    /// ```
1044    pub fn has_refresh_token(&self) -> bool {
1045        self.refresh_token.is_some()
1046    }
1047
1048    /// Return the refresh token string, if present.
1049    ///
1050    /// # Example
1051    ///
1052    /// ```rust
1053    /// use auth_framework::tokens::AuthToken;
1054    ///
1055    /// let token = AuthToken::builder("t1", "u1", "access")
1056    ///     .refresh_token("rt-xyz")
1057    ///     .build();
1058    /// assert_eq!(token.get_refresh_token(), Some("rt-xyz"));
1059    /// ```
1060    pub fn get_refresh_token(&self) -> Option<&str> {
1061        self.refresh_token.as_deref()
1062    }
1063
1064    /// Revoke the token.
1065    ///
1066    /// # Example
1067    ///
1068    /// ```rust
1069    /// use auth_framework::tokens::AuthToken;
1070    ///
1071    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1072    /// token.revoke(Some("compromised".to_string()));
1073    /// assert!(token.is_revoked());
1074    /// ```
1075    pub fn revoke(&mut self, reason: Option<String>) {
1076        self.metadata.revoked = true;
1077        self.metadata.revoked_at = Some(Utc::now());
1078        self.metadata.revoked_reason = reason;
1079    }
1080
1081    /// Update the last used time and increment use count.
1082    ///
1083    /// # Example
1084    ///
1085    /// ```rust
1086    /// use auth_framework::tokens::AuthToken;
1087    ///
1088    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1089    /// assert_eq!(token.metadata.use_count, 0);
1090    /// token.mark_used();
1091    /// assert_eq!(token.metadata.use_count, 1);
1092    /// ```
1093    pub fn mark_used(&mut self) {
1094        self.metadata.last_used = Some(Utc::now());
1095        self.metadata.use_count += 1;
1096    }
1097
1098    /// Add a scope to the token.
1099    ///
1100    /// Duplicates are ignored.
1101    ///
1102    /// # Example
1103    ///
1104    /// ```rust
1105    /// use auth_framework::tokens::AuthToken;
1106    ///
1107    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1108    /// token.add_scope("read");
1109    /// assert!(token.has_scope("read"));
1110    /// ```
1111    pub fn add_scope(&mut self, scope: impl Into<String>) {
1112        let scope = scope.into();
1113        if !self.scopes.contains(&scope) {
1114            self.scopes.push(scope);
1115        }
1116    }
1117
1118    /// Check if the token has a specific scope.
1119    ///
1120    /// # Example
1121    ///
1122    /// ```rust
1123    /// use auth_framework::tokens::AuthToken;
1124    ///
1125    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1126    /// token.add_scope("write");
1127    /// assert!(token.has_scope("write"));
1128    /// assert!(!token.has_scope("admin"));
1129    /// ```
1130    pub fn has_scope(&self, scope: &str) -> bool {
1131        self.scopes.contains(scope)
1132    }
1133
1134    /// Set the refresh token.
1135    ///
1136    /// # Example
1137    ///
1138    /// ```rust
1139    /// use auth_framework::tokens::AuthToken;
1140    ///
1141    /// let token = AuthToken::builder("t1", "u1", "access").build()
1142    ///     .with_refresh_token("refresh_xyz");
1143    /// assert!(token.refresh_token.is_some());
1144    /// ```
1145    pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
1146        self.refresh_token = Some(refresh_token.into());
1147        self
1148    }
1149
1150    /// Set the client ID.
1151    ///
1152    /// # Example
1153    ///
1154    /// ```rust
1155    /// use auth_framework::tokens::AuthToken;
1156    ///
1157    /// let token = AuthToken::builder("t1", "u1", "access").build()
1158    ///     .with_client_id("app-client");
1159    /// assert_eq!(token.client_id.as_deref(), Some("app-client"));
1160    /// ```
1161    pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
1162        self.client_id = Some(client_id.into());
1163        self
1164    }
1165
1166    /// Set the token scopes.
1167    ///
1168    /// # Example
1169    ///
1170    /// ```rust
1171    /// use auth_framework::tokens::AuthToken;
1172    /// use auth_framework::types::Scopes;
1173    ///
1174    /// let token = AuthToken::builder("t1", "u1", "access").build()
1175    ///     .with_scopes(Scopes::new(vec!["read".into()]));
1176    /// assert!(token.has_scope("read"));
1177    /// ```
1178    pub fn with_scopes(mut self, scopes: impl Into<crate::types::Scopes>) -> Self {
1179        self.scopes = scopes.into();
1180        self
1181    }
1182
1183    /// Add metadata to the token.
1184    ///
1185    /// # Example
1186    ///
1187    /// ```rust
1188    /// use auth_framework::tokens::{AuthToken, TokenMetadata};
1189    ///
1190    /// let meta = TokenMetadata::builder().issued_ip("192.168.1.1").build();
1191    /// let token = AuthToken::builder("t1", "u1", "access").build()
1192    ///     .with_metadata(meta);
1193    /// assert_eq!(token.metadata.issued_ip.as_deref(), Some("192.168.1.1"));
1194    /// ```
1195    pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
1196        self.metadata = metadata;
1197        self
1198    }
1199
1200    /// Get time until expiration.
1201    ///
1202    /// Returns `Duration::ZERO` if the token has already expired.
1203    ///
1204    /// # Example
1205    ///
1206    /// ```rust
1207    /// use auth_framework::tokens::AuthToken;
1208    /// use std::time::Duration;
1209    ///
1210    /// let token = AuthToken::builder("t1", "u1", "access").build();
1211    /// assert!(token.time_until_expiry() > Duration::ZERO);
1212    /// ```
1213    pub fn time_until_expiry(&self) -> Duration {
1214        let now = Utc::now();
1215        if self.expires_at > now {
1216            (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
1217        } else {
1218            Duration::ZERO
1219        }
1220    }
1221
1222    /// Add a custom claim to the token metadata.
1223    ///
1224    /// # Example
1225    ///
1226    /// ```rust
1227    /// use auth_framework::tokens::AuthToken;
1228    ///
1229    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1230    /// token.add_custom_claim("tenant", serde_json::json!("acme"));
1231    /// assert_eq!(token.get_custom_claim("tenant").unwrap(), &serde_json::json!("acme"));
1232    /// ```
1233    pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
1234        self.metadata.custom.insert(key.into(), value);
1235    }
1236
1237    /// Get a custom claim from the token metadata.
1238    ///
1239    /// # Example
1240    ///
1241    /// ```rust
1242    /// use auth_framework::tokens::AuthToken;
1243    ///
1244    /// let token = AuthToken::builder("t1", "u1", "access").build();
1245    /// assert!(token.get_custom_claim("missing").is_none());
1246    /// ```
1247    pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
1248        self.metadata.custom.get(key)
1249    }
1250
1251    /// Check if the token has a specific permission.
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_permission("admin");
1260    /// assert!(token.has_permission("admin"));
1261    /// ```
1262    pub fn has_permission(&self, permission: &str) -> bool {
1263        self.permissions.contains(permission)
1264    }
1265
1266    /// Add a permission to the token.
1267    ///
1268    /// Duplicates are ignored.
1269    ///
1270    /// # Example
1271    ///
1272    /// ```rust
1273    /// use auth_framework::tokens::AuthToken;
1274    ///
1275    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1276    /// token.add_permission("write");
1277    /// assert!(token.has_permission("write"));
1278    /// ```
1279    pub fn add_permission(&mut self, permission: impl Into<String>) {
1280        let permission = permission.into();
1281        if !self.permissions.contains(&permission) {
1282            self.permissions.push(permission);
1283        }
1284    }
1285
1286    /// Add a role to the token.
1287    ///
1288    /// Duplicates are ignored.
1289    ///
1290    /// # Example
1291    ///
1292    /// ```rust
1293    /// use auth_framework::tokens::AuthToken;
1294    ///
1295    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1296    /// token.add_role("editor");
1297    /// assert!(token.has_role("editor"));
1298    /// ```
1299    pub fn add_role(&mut self, role: impl Into<String>) {
1300        let role = role.into();
1301        if !self.roles.contains(&role) {
1302            self.roles.push(role);
1303        }
1304    }
1305
1306    /// Check if the token has a specific role.
1307    ///
1308    /// # Example
1309    ///
1310    /// ```rust
1311    /// use auth_framework::tokens::AuthToken;
1312    ///
1313    /// let mut token = AuthToken::builder("t1", "u1", "access").build();
1314    /// token.add_role("admin");
1315    /// assert!(token.has_role("admin"));
1316    /// assert!(!token.has_role("guest"));
1317    /// ```
1318    pub fn has_role(&self, role: &str) -> bool {
1319        self.roles.contains(role)
1320    }
1321
1322    /// Set the permissions.
1323    ///
1324    /// # Example
1325    ///
1326    /// ```rust
1327    /// use auth_framework::tokens::AuthToken;
1328    /// use auth_framework::types::Permissions;
1329    ///
1330    /// let token = AuthToken::builder("t1", "u1", "access").build()
1331    ///     .with_permissions(Permissions::new(vec!["read".into()]));
1332    /// assert!(token.has_permission("read"));
1333    /// ```
1334    pub fn with_permissions(mut self, permissions: impl Into<crate::types::Permissions>) -> Self {
1335        self.permissions = permissions.into();
1336        self
1337    }
1338
1339    /// Set the roles.
1340    ///
1341    /// # Example
1342    ///
1343    /// ```rust
1344    /// use auth_framework::tokens::AuthToken;
1345    /// use auth_framework::types::Roles;
1346    ///
1347    /// let token = AuthToken::builder("t1", "u1", "access").build()
1348    ///     .with_roles(Roles::new(vec!["viewer".into()]));
1349    /// assert!(token.has_role("viewer"));
1350    /// ```
1351    pub fn with_roles(mut self, roles: impl Into<crate::types::Roles>) -> Self {
1352        self.roles = roles.into();
1353        self
1354    }
1355}
1356
1357impl Clone for TokenManager {
1358    fn clone(&self) -> Self {
1359        let (previous_decoding_key, previous_key_material) = match &self.previous_key_material {
1360            Some(KeyMaterial::Hmac(secret)) => (
1361                Some(DecodingKey::from_secret(secret)),
1362                Some(KeyMaterial::Hmac(secret.clone())),
1363            ),
1364            Some(KeyMaterial::Rsa { public, .. }) => (
1365                DecodingKey::from_rsa_pem(public).ok(),
1366                self.previous_key_material.clone(),
1367            ),
1368            None => (None, None),
1369        };
1370        match &self.key_material {
1371            KeyMaterial::Hmac(secret) => Self {
1372                encoding_key: EncodingKey::from_secret(secret),
1373                decoding_key: DecodingKey::from_secret(secret),
1374                previous_decoding_key,
1375                previous_rotated_at: self.previous_rotated_at,
1376                previous_key_grace: self.previous_key_grace,
1377                previous_key_max_token_lifetime: self.previous_key_max_token_lifetime,
1378                key_material: self.key_material.clone(),
1379                previous_key_material,
1380                algorithm: self.algorithm,
1381                issuer: self.issuer.clone(),
1382                audience: self.audience.clone(),
1383                default_lifetime: self.default_lifetime,
1384            },
1385            KeyMaterial::Rsa { private, public } => Self {
1386                // SAFETY: The PEM was already validated when the TokenManager was first
1387                // constructed; re-parsing it here during Clone cannot fail unless the
1388                // bytes were corrupted in memory, which would be a catastrophic bug.
1389                encoding_key: EncodingKey::from_rsa_pem(private).expect("RSA private key PEM re-parse failed during Clone — this indicates memory corruption"),
1390                decoding_key: DecodingKey::from_rsa_pem(public).expect("RSA public key PEM re-parse failed during Clone — this indicates memory corruption"),
1391                previous_decoding_key,
1392                previous_rotated_at: self.previous_rotated_at,
1393                previous_key_grace: self.previous_key_grace,
1394                previous_key_max_token_lifetime: self.previous_key_max_token_lifetime,
1395                key_material: self.key_material.clone(),
1396                previous_key_material,
1397                algorithm: self.algorithm,
1398                issuer: self.issuer.clone(),
1399                audience: self.audience.clone(),
1400                default_lifetime: self.default_lifetime,
1401            },
1402        }
1403    }
1404}
1405
1406/// Strip PEM headers/footers and whitespace, then base64-decode to DER.
1407fn pem_to_der(pem: &str) -> Result<Vec<u8>> {
1408    let b64: String = pem
1409        .lines()
1410        .filter(|line| {
1411            !line.starts_with("-----BEGIN") && !line.starts_with("-----END") && !line.is_empty()
1412        })
1413        .collect();
1414
1415    base64::engine::general_purpose::STANDARD
1416        .decode(&b64)
1417        .map_err(|e| AuthError::crypto(format!("Failed to base64-decode PEM: {e}")))
1418}
1419
1420impl TokenManager {
1421    fn jwks_from_public_pem(public_key: &[u8], algorithm: Algorithm) -> Result<JwksPublicKey> {
1422        let pem = std::str::from_utf8(public_key)
1423            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key PEM encoding: {e}")))?;
1424        let der = pem_to_der(pem)?;
1425
1426        // `PublicKey::from_der` parses either RFC8017 (PKCS#1) or RFC5280
1427        // (X.509 SubjectPublicKeyInfo / PKCS#8) DER automatically -- no need
1428        // to try two separate parse paths as the `rsa` crate required.
1429        let public_key = aws_lc_rs::rsa::PublicKey::from_der(&der).map_err(|e| {
1430            AuthError::crypto(format!(
1431                "Failed to parse RSA public key for JWKS export: {e}"
1432            ))
1433        })?;
1434
1435        let modulus = public_key.modulus().big_endian_without_leading_zero();
1436        let exponent = public_key.exponent().big_endian_without_leading_zero();
1437        let kid_digest = Sha256::digest(modulus);
1438
1439        let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus);
1440        let e = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(exponent);
1441        let kid = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(kid_digest);
1442
1443        Ok(JwksPublicKey {
1444            algorithm,
1445            kid,
1446            n,
1447            e,
1448        })
1449    }
1450
1451    /// Export the current and previous RSA verification keys as JWKS-compatible material.
1452    pub fn export_public_jwks(&self) -> Result<Vec<JwksPublicKey>> {
1453        let mut keys = Vec::new();
1454
1455        if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1456            keys.push(Self::jwks_from_public_pem(public, self.algorithm)?);
1457        }
1458
1459        if self.previous_key_live(Utc::now().timestamp())
1460            && let Some(KeyMaterial::Rsa { public, .. }) = &self.previous_key_material
1461        {
1462            let previous = Self::jwks_from_public_pem(public, self.algorithm)?;
1463            if !keys.iter().any(|key| key.kid == previous.kid) {
1464                keys.push(previous);
1465            }
1466        }
1467
1468        Ok(keys)
1469    }
1470
1471    /// Create a new token manager with HMAC key.
1472    pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
1473        Self {
1474            encoding_key: EncodingKey::from_secret(secret),
1475            decoding_key: DecodingKey::from_secret(secret),
1476            previous_decoding_key: None,
1477            previous_rotated_at: None,
1478            previous_key_grace: DEFAULT_PREVIOUS_KEY_WINDOW,
1479            previous_key_max_token_lifetime: DEFAULT_PREVIOUS_KEY_WINDOW,
1480            key_material: KeyMaterial::Hmac(secret.to_vec()),
1481            previous_key_material: None,
1482            algorithm: Algorithm::HS256,
1483            issuer: issuer.into(),
1484            audience: audience.into(),
1485            default_lifetime: Duration::from_secs(3600), // 1 hour
1486        }
1487    }
1488
1489    /// Create a new token manager with RSA keys.
1490    ///
1491    /// ## RSA Key Format Support
1492    ///
1493    /// This method supports RSA keys in both standard PEM formats:
1494    /// - **PKCS#1**: `-----BEGIN RSA PRIVATE KEY-----` (traditional RSA format)
1495    /// - **PKCS#8**: `-----BEGIN PRIVATE KEY-----` (modern standard format, recommended)
1496    ///
1497    /// Both formats are automatically detected and parsed. No format conversion is required.
1498    ///
1499    /// ## Example
1500    ///
1501    /// ```rust,no_run
1502    /// use auth_framework::tokens::TokenManager;
1503    ///
1504    /// // Both PKCS#1 and PKCS#8 formats work; provide PEM bytes from your key store.
1505    /// # let private_key: &[u8] = b"";
1506    /// # let public_key: &[u8] = b"";
1507    ///
1508    /// let manager = TokenManager::new_rsa(
1509    ///     private_key,
1510    ///     public_key,
1511    ///     "my-service",
1512    ///     "my-audience"
1513    /// )?;
1514    /// # Ok::<(), auth_framework::errors::AuthError>(())
1515    /// ```
1516    pub fn new_rsa(
1517        private_key: &[u8],
1518        public_key: &[u8],
1519        issuer: impl Into<String>,
1520        audience: impl Into<String>,
1521    ) -> Result<Self> {
1522        let encoding_key = EncodingKey::from_rsa_pem(private_key)
1523            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1524
1525        let decoding_key = DecodingKey::from_rsa_pem(public_key)
1526            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1527
1528        Ok(Self {
1529            encoding_key,
1530            decoding_key,
1531            previous_decoding_key: None,
1532            previous_rotated_at: None,
1533            previous_key_grace: DEFAULT_PREVIOUS_KEY_WINDOW,
1534            previous_key_max_token_lifetime: DEFAULT_PREVIOUS_KEY_WINDOW,
1535            key_material: KeyMaterial::Rsa {
1536                private: private_key.to_vec(),
1537                public: public_key.to_vec(),
1538            },
1539            previous_key_material: None,
1540            algorithm: Algorithm::RS256,
1541            issuer: issuer.into(),
1542            audience: audience.into(),
1543            default_lifetime: Duration::from_secs(3600), // 1 hour
1544        })
1545    }
1546
1547    /// Rotate HMAC key, keeping the current key as the previous decoding key
1548    /// to seamlessly allow verification of tokens signed with the old key.
1549    pub fn rotate_hmac_key(&mut self, new_secret: &[u8]) {
1550        self.rotate_hmac_key_at(new_secret, Utc::now().timestamp());
1551    }
1552
1553    fn rotate_hmac_key_at(&mut self, new_secret: &[u8], now: i64) {
1554        // Move current key to previous
1555        if let KeyMaterial::Hmac(secret) = &self.key_material {
1556            self.previous_decoding_key = Some(DecodingKey::from_secret(secret));
1557            self.previous_key_material = Some(KeyMaterial::Hmac(secret.clone()));
1558            self.previous_rotated_at = Some(now);
1559        }
1560
1561        // Set new key
1562        self.encoding_key = EncodingKey::from_secret(new_secret);
1563        self.decoding_key = DecodingKey::from_secret(new_secret);
1564        self.key_material = KeyMaterial::Hmac(new_secret.to_vec());
1565        self.algorithm = Algorithm::HS256;
1566    }
1567
1568    /// Rotate RSA key, keeping the current key as the previous decoding key
1569    /// to seamlessly allow verification of tokens signed with the old key.
1570    pub fn rotate_rsa_key(&mut self, private_key: &[u8], public_key: &[u8]) -> Result<()> {
1571        let new_encoding_key = EncodingKey::from_rsa_pem(private_key)
1572            .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1573        let new_decoding_key = DecodingKey::from_rsa_pem(public_key)
1574            .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1575
1576        // Move current key to previous
1577        if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1578            self.previous_decoding_key = DecodingKey::from_rsa_pem(public).ok();
1579            self.previous_key_material = Some(self.key_material.clone());
1580            self.previous_rotated_at = Some(Utc::now().timestamp());
1581        }
1582
1583        // Set new key
1584        self.encoding_key = new_encoding_key;
1585        self.decoding_key = new_decoding_key;
1586        self.key_material = KeyMaterial::Rsa {
1587            private: private_key.to_vec(),
1588            public: public_key.to_vec(),
1589        };
1590        self.algorithm = Algorithm::RS256;
1591
1592        Ok(())
1593    }
1594
1595    /// Retire the previous key (if any), so tokens signed with it are no longer valid.
1596    pub fn retire_previous_key(&mut self) {
1597        self.previous_decoding_key = None;
1598        self.previous_key_material = None;
1599        self.previous_rotated_at = None;
1600    }
1601
1602    /// Set how long the previous key keeps verifying tokens after a rotation (default 24 hours).
1603    pub fn with_previous_key_grace(mut self, grace: Duration) -> Self {
1604        self.previous_key_grace = grace;
1605        self
1606    }
1607
1608    /// Set the longest token lifetime (`exp - iat`) accepted under the previous key
1609    /// (default 24 hours).
1610    pub fn with_previous_key_max_token_lifetime(mut self, max: Duration) -> Self {
1611        self.previous_key_max_token_lifetime = max;
1612        self
1613    }
1614
1615    /// Whether the previous key may still verify tokens at unix time `now`.
1616    fn previous_key_live(&self, now: i64) -> bool {
1617        match self.previous_rotated_at {
1618            Some(at) => now.saturating_sub(at) <= self.previous_key_grace.as_secs() as i64,
1619            None => false,
1620        }
1621    }
1622
1623    /// Whether `claims` may be accepted under the previous key: it was issued before the
1624    /// rotation and its lifetime is within the configured maximum.
1625    fn previous_key_accepts(&self, claims: &JwtClaims, now: i64) -> bool {
1626        let Some(at) = self.previous_rotated_at else {
1627            return false;
1628        };
1629        self.previous_key_live(now)
1630            && claims.iat <= at
1631            && claims.exp.saturating_sub(claims.iat)
1632                <= self.previous_key_max_token_lifetime.as_secs() as i64
1633    }
1634
1635    /// Set the default token lifetime.
1636    pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
1637        self.default_lifetime = lifetime;
1638        self
1639    }
1640
1641    /// Create a new JWT token.
1642    pub fn create_jwt_token(
1643        &self,
1644        user_id: impl Into<String>,
1645        scopes: Vec<String>,
1646        lifetime: Option<Duration>,
1647    ) -> Result<String> {
1648        self.encode_jwt_token(user_id.into(), scopes, lifetime, None)
1649    }
1650
1651    /// Create a JWT for a token issued to an OAuth client on a user's behalf: it carries the
1652    /// `client_id` claim, which marks it as delegated access and not as the user's own session.
1653    pub fn create_client_jwt_token(
1654        &self,
1655        user_id: impl Into<String>,
1656        client_id: impl Into<String>,
1657        scopes: Vec<String>,
1658        lifetime: Option<Duration>,
1659    ) -> Result<String> {
1660        self.encode_jwt_token(user_id.into(), scopes, lifetime, Some(client_id.into()))
1661    }
1662
1663    fn encode_jwt_token(
1664        &self,
1665        user_id: String,
1666        scopes: Vec<String>,
1667        lifetime: Option<Duration>,
1668        client_id: Option<String>,
1669    ) -> Result<String> {
1670        let lifetime = lifetime.unwrap_or(self.default_lifetime);
1671        let now = Utc::now();
1672        let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
1673
1674        let claims = JwtClaims {
1675            sub: user_id,
1676            iss: self.issuer.clone(),
1677            aud: self.audience.clone(),
1678            exp: exp.timestamp(),
1679            iat: now.timestamp(),
1680            nbf: now.timestamp(),
1681            jti: Uuid::new_v4().to_string(),
1682            scope: scopes.join(" "),
1683            permissions: None,
1684            roles: None,
1685            client_id,
1686            custom: HashMap::new(),
1687        };
1688
1689        let header = Header::new(self.algorithm);
1690
1691        encode(&header, &claims, &self.encoding_key)
1692            .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
1693    }
1694
1695    /// Validate a JWT that stands for a user's own session: like
1696    /// [`validate_jwt_token`](Self::validate_jwt_token), but a token issued to an OAuth client
1697    /// (one that carries a `client_id` claim) is refused.
1698    pub fn validate_session_jwt_token(&self, token: &str) -> Result<JwtClaims> {
1699        let claims = self.validate_jwt_token(token)?;
1700        if claims.client_id.is_some() {
1701            return Err(AuthError::Token(TokenError::Invalid {
1702                message: "Token was issued to an OAuth client and is not a user session"
1703                    .to_string(),
1704            }));
1705        }
1706        Ok(claims)
1707    }
1708
1709    /// Validate and decode a JWT token.
1710    pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
1711        self.validate_jwt_token_at(token, Utc::now().timestamp())
1712    }
1713
1714    fn validate_jwt_token_at(&self, token: &str, now: i64) -> Result<JwtClaims> {
1715        let mut validation = Validation::new(self.algorithm);
1716        validation.set_issuer(&[&self.issuer]);
1717        validation.set_audience(&[&self.audience]);
1718
1719        match decode::<JwtClaims>(token, &self.decoding_key, &validation) {
1720            Ok(token_data) => Ok(token_data.claims),
1721            Err(e) => {
1722                match e.kind() {
1723                    jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
1724                        Err(AuthError::Token(TokenError::Expired))
1725                    }
1726                    jsonwebtoken::errors::ErrorKind::InvalidSignature => {
1727                        // If signature is invalid, try the previous key if configured
1728                        if self.previous_key_live(now)
1729                            && let Some(prev_key) = &self.previous_decoding_key
1730                            && let Ok(prev_token_data) =
1731                                decode::<JwtClaims>(token, prev_key, &validation)
1732                            && self.previous_key_accepts(&prev_token_data.claims, now)
1733                        {
1734                            return Ok(prev_token_data.claims);
1735                        }
1736
1737                        Err(AuthError::Token(TokenError::Invalid {
1738                            message: "Invalid token signature".to_string(),
1739                        }))
1740                    }
1741                    _ => Err(AuthError::Token(TokenError::Invalid {
1742                        message: "Invalid token format".to_string(),
1743                    })),
1744                }
1745            }
1746        }
1747    }
1748
1749    /// Create a complete authentication token with JWT.
1750    pub fn create_auth_token(
1751        &self,
1752        user_id: impl Into<String>,
1753        scopes: impl Into<crate::types::Scopes>,
1754        auth_method: impl Into<String>,
1755        lifetime: Option<std::time::Duration>,
1756    ) -> Result<AuthToken> {
1757        let user_id_str = user_id.into();
1758        let scopes: crate::types::Scopes = scopes.into();
1759        let lifetime = lifetime.unwrap_or(self.default_lifetime);
1760
1761        let jwt_token = self.create_jwt_token(&user_id_str, scopes.to_vec(), Some(lifetime))?;
1762
1763        let token =
1764            AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
1765
1766        Ok(token)
1767    }
1768
1769    /// Create a complete authentication token for a token issued to an OAuth client
1770    /// (see [`create_client_jwt_token`](Self::create_client_jwt_token)).
1771    pub fn create_client_auth_token(
1772        &self,
1773        user_id: impl Into<String>,
1774        client_id: impl Into<String>,
1775        scopes: impl Into<crate::types::Scopes>,
1776        auth_method: impl Into<String>,
1777        lifetime: Option<std::time::Duration>,
1778    ) -> Result<AuthToken> {
1779        let user_id_str = user_id.into();
1780        let client_id = client_id.into();
1781        let scopes: crate::types::Scopes = scopes.into();
1782        let lifetime = lifetime.unwrap_or(self.default_lifetime);
1783
1784        let jwt_token = self.create_client_jwt_token(
1785            &user_id_str,
1786            &client_id,
1787            scopes.to_vec(),
1788            Some(lifetime),
1789        )?;
1790
1791        Ok(
1792            AuthToken::new(user_id_str, jwt_token, lifetime, auth_method)
1793                .with_scopes(scopes)
1794                .with_client_id(client_id),
1795        )
1796    }
1797
1798    /// Validate an authentication token.
1799    pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
1800        // Check if token is expired
1801        if token.is_expired() {
1802            return Err(TokenError::Expired.into());
1803        }
1804
1805        // Check if token is revoked
1806        if token.is_revoked() {
1807            return Err(TokenError::Invalid {
1808                message: "Token has been revoked".to_string(),
1809            }
1810            .into());
1811        }
1812
1813        // Validate JWT if it's a JWT token
1814        if token.auth_method == "jwt" || token.access_token.contains('.') {
1815            self.validate_jwt_token(&token.access_token)?;
1816        }
1817
1818        Ok(())
1819    }
1820
1821    /// Refresh a token (create a new one with extended lifetime).
1822    pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1823        if token.is_expired() {
1824            return Err(TokenError::Expired.into());
1825        }
1826
1827        if token.is_revoked() {
1828            return Err(TokenError::Invalid {
1829                message: "Cannot refresh revoked token".to_string(),
1830            }
1831            .into());
1832        }
1833
1834        // Create a new token with the same properties but new expiry
1835        if let Some(client_id) = &token.client_id {
1836            return self.create_client_auth_token(
1837                &token.user_id,
1838                client_id,
1839                token.scopes.clone(),
1840                &token.auth_method,
1841                Some(self.default_lifetime),
1842            );
1843        }
1844        self.create_auth_token(
1845            &token.user_id,
1846            token.scopes.clone(),
1847            &token.auth_method,
1848            Some(self.default_lifetime),
1849        )
1850    }
1851
1852    /// Extract token information from a JWT.
1853    pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
1854        let claims = self.validate_jwt_token(token)?;
1855
1856        Ok(TokenInfo {
1857            user_id: claims.sub,
1858            username: claims
1859                .custom
1860                .get("username")
1861                .and_then(|v| v.as_str())
1862                .map(|s| s.to_string()),
1863            email: claims
1864                .custom
1865                .get("email")
1866                .and_then(|v| v.as_str())
1867                .map(|s| s.to_string()),
1868            name: claims
1869                .custom
1870                .get("name")
1871                .and_then(|v| v.as_str())
1872                .map(|s| s.to_string()),
1873            roles: claims
1874                .custom
1875                .get("roles")
1876                .and_then(|v| v.as_array())
1877                .map(|arr| {
1878                    arr.iter()
1879                        .filter_map(|v| v.as_str())
1880                        .map(|s| s.to_string())
1881                        .collect()
1882                })
1883                .unwrap_or_default(),
1884            permissions: claims
1885                .scope
1886                .split_whitespace()
1887                .map(|s| s.to_string())
1888                .collect(),
1889            attributes: claims.custom,
1890        })
1891    }
1892}
1893
1894/// Trait for converting tokens to user profiles
1895#[async_trait::async_trait]
1896pub trait TokenToProfile {
1897    /// Convert this token to a user profile using the specified provider
1898    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile>;
1899
1900    /// Convert this token to a user profile with a custom extractor
1901    async fn to_profile_with_extractor(
1902        &self,
1903        provider: &OAuthProvider,
1904        extractor: &ProfileExtractor,
1905    ) -> Result<ProviderProfile>;
1906}
1907
1908#[async_trait::async_trait]
1909impl TokenToProfile for AuthToken {
1910    async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile> {
1911        let extractor = ProfileExtractor::new();
1912        extractor.extract_profile(self, provider).await
1913    }
1914
1915    async fn to_profile_with_extractor(
1916        &self,
1917        provider: &OAuthProvider,
1918        extractor: &ProfileExtractor,
1919    ) -> Result<ProviderProfile> {
1920        extractor.extract_profile(self, provider).await
1921    }
1922}
1923
1924#[cfg(test)]
1925mod tests {
1926    use super::*;
1927
1928    #[test]
1929    fn test_auth_token_creation() {
1930        let token = AuthToken::new(
1931            "user123",
1932            "token123",
1933            Duration::from_secs(3600), // 1 hour
1934            "password",
1935        );
1936
1937        assert_eq!(token.user_id(), "user123");
1938        assert_eq!(token.access_token(), "token123");
1939        assert!(!token.is_expired());
1940        assert!(!token.is_revoked());
1941        assert!(token.is_valid());
1942    }
1943
1944    #[test]
1945    fn test_token_expiry() {
1946        let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
1947
1948        // Wait a bit to ensure expiry
1949        std::thread::sleep(std::time::Duration::from_millis(10));
1950
1951        assert!(token.is_expired());
1952        assert!(!token.is_valid());
1953    }
1954
1955    #[test]
1956    fn test_token_revocation() {
1957        let mut token = AuthToken::new(
1958            "user123",
1959            "token123",
1960            Duration::from_secs(3600), // 1 hour
1961            "password",
1962        );
1963
1964        assert!(!token.is_revoked());
1965
1966        token.revoke(Some("User logout".to_string()));
1967
1968        assert!(token.is_revoked());
1969        assert!(!token.is_valid());
1970        assert!(token.metadata.revoked);
1971    }
1972
1973    fn generate_test_rsa_pems() -> (Vec<u8>, Vec<u8>) {
1974        use aws_lc_rs::signature::KeyPair as _;
1975
1976        fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
1977            let b64 = base64::engine::general_purpose::STANDARD.encode(der);
1978            let mut pem = format!("-----BEGIN {label}-----\n");
1979            for chunk in b64.as_bytes().chunks(64) {
1980                pem.push_str(std::str::from_utf8(chunk).unwrap());
1981                pem.push('\n');
1982            }
1983            pem.push_str(&format!("-----END {label}-----\n"));
1984            pem.into_bytes()
1985        }
1986
1987        let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
1988            .expect("RSA key generation failed");
1989        let priv_der =
1990            aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
1991                .expect("private key DER export failed");
1992        let pub_der = key_pair.public_key().as_ref();
1993
1994        (
1995            der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
1996            // PublicKey::as_ref() returns RFC8017 (PKCS#1 RSAPublicKey) DER,
1997            // not SPKI -- label accordingly, matching jsonwebtoken's own
1998            // PEM classifier (Standard::Pkcs1 for the "RSA PUBLIC KEY" tag).
1999            der_to_pem(pub_der, "RSA PUBLIC KEY"),
2000        )
2001    }
2002
2003    /// Same key pair as `generate_test_rsa_pems`, but the public half in
2004    /// SPKI/PKCS#8 ("PUBLIC KEY") form -- the format the old `rsa` crate's
2005    /// `from_public_key_pem` treated as primary, and a different parse path
2006    /// through `jwks_from_public_pem`/`pem_to_der` than the PKCS#1 form
2007    /// above.
2008    fn generate_test_rsa_pems_spki_public() -> (Vec<u8>, Vec<u8>) {
2009        use aws_lc_rs::signature::KeyPair as _;
2010
2011        fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
2012            let b64 = base64::engine::general_purpose::STANDARD.encode(der);
2013            let mut pem = format!("-----BEGIN {label}-----\n");
2014            for chunk in b64.as_bytes().chunks(64) {
2015                pem.push_str(std::str::from_utf8(chunk).unwrap());
2016                pem.push('\n');
2017            }
2018            pem.push_str(&format!("-----END {label}-----\n"));
2019            pem.into_bytes()
2020        }
2021
2022        let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
2023            .expect("RSA key generation failed");
2024        let priv_der =
2025            aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
2026                .expect("private key DER export failed");
2027        let public_key = aws_lc_rs::rsa::PublicKey::from_der(key_pair.public_key().as_ref())
2028            .expect("re-parsing the freshly generated public key must succeed");
2029        let spki_der = aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::PublicKeyX509Der>::as_der(
2030            &public_key,
2031        )
2032        .expect("SPKI DER export failed");
2033
2034        (
2035            der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
2036            der_to_pem(spki_der.as_ref(), "PUBLIC KEY"),
2037        )
2038    }
2039
2040    /// Regression/coverage test for the RSA-removal rewrite of
2041    /// `jwks_from_public_pem`: a real RSA key's exported JWKS `n`/`e` must
2042    /// match the key's own modulus/exponent, and the exported key must
2043    /// actually be usable to verify a token signed by the paired private key.
2044    #[test]
2045    fn test_export_public_jwks_round_trips_rsa_key() {
2046        let (priv_pem, pub_pem) = generate_test_rsa_pems();
2047        let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
2048            .expect("TokenManager::new_rsa should accept a freshly generated RSA key pair");
2049
2050        let jwks = manager
2051            .export_public_jwks()
2052            .expect("JWKS export should succeed for a valid RSA key");
2053        assert_eq!(jwks.len(), 1, "exactly one key, no previous key configured");
2054
2055        let exported = &jwks[0];
2056        assert_eq!(exported.algorithm, Algorithm::RS256);
2057        assert!(!exported.n.is_empty());
2058        assert!(!exported.e.is_empty());
2059
2060        // Independently re-derive n/e directly from the DER and confirm they
2061        // match what jwks_from_public_pem produced -- not just "didn't error."
2062        let der = pem_to_der(std::str::from_utf8(&pub_pem).unwrap()).unwrap();
2063        let public_key =
2064            aws_lc_rs::rsa::PublicKey::from_der(&der).expect("public key DER should parse");
2065        let expected_n = base64::engine::general_purpose::URL_SAFE_NO_PAD
2066            .encode(public_key.modulus().big_endian_without_leading_zero());
2067        let expected_e = base64::engine::general_purpose::URL_SAFE_NO_PAD
2068            .encode(public_key.exponent().big_endian_without_leading_zero());
2069        assert_eq!(exported.n, expected_n);
2070        assert_eq!(exported.e, expected_e);
2071
2072        // The exported JWKS must be independently usable: sign a real token
2073        // with the manager's private key, then verify it using ONLY the
2074        // exported n/e (not the manager, not the PEM) -- the actual use case
2075        // a resource server validating against a published JWKS exercises.
2076        let token = manager
2077            .create_jwt_token("test-user", vec![], None)
2078            .expect("signing with the freshly generated RSA key should succeed");
2079        let decoding_key = DecodingKey::from_rsa_components(&exported.n, &exported.e)
2080            .expect("DecodingKey should accept the exported n/e");
2081        let mut validation = Validation::new(Algorithm::RS256);
2082        validation.set_issuer(&["test-issuer"]);
2083        validation.set_audience(&["test-audience"]);
2084        decode::<JwtClaims>(&token, &decoding_key, &validation)
2085            .expect("a token signed by this key must verify against its own exported JWKS");
2086    }
2087
2088    /// Same as the PKCS#1 test above, but for the SPKI ("PUBLIC KEY") PEM
2089    /// form -- the format the old `rsa` crate's `from_public_key_pem`
2090    /// treated as primary, and a different parse path through
2091    /// `pem_to_der`/`PublicKey::from_der` than the PKCS#1 form.
2092    #[test]
2093    fn test_export_public_jwks_accepts_spki_public_key_pem() {
2094        let (priv_pem, pub_pem) = generate_test_rsa_pems_spki_public();
2095        let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
2096            .expect("TokenManager::new_rsa should accept an SPKI-form public key");
2097
2098        let jwks = manager
2099            .export_public_jwks()
2100            .expect("JWKS export should succeed for an SPKI-form RSA public key");
2101        assert_eq!(jwks.len(), 1);
2102        assert!(!jwks[0].n.is_empty());
2103        assert!(!jwks[0].e.is_empty());
2104    }
2105
2106    const OLD_SECRET: &[u8] = b"old-secret-old-secret-old-secret-0";
2107    const NEW_SECRET: &[u8] = b"new-secret-new-secret-new-secret-1";
2108
2109    /// A manager that has rotated from `OLD_SECRET` to `NEW_SECRET`, plus a token the old key
2110    /// signed with the given lifetime. Returns (manager, token, rotation unix time).
2111    fn rotated_with_old_token(old_lifetime: Duration) -> (TokenManager, String, i64) {
2112        let old = TokenManager::new_hmac(OLD_SECRET, "iss", "aud");
2113        let token = old
2114            .create_jwt_token("user-1", vec!["read".into()], Some(old_lifetime))
2115            .unwrap();
2116        let at = Utc::now().timestamp();
2117        let mut manager = old;
2118        manager.rotate_hmac_key_at(NEW_SECRET, at);
2119        (manager, token, at)
2120    }
2121
2122    #[test]
2123    fn the_previous_key_verifies_old_tokens_inside_the_grace_window() {
2124        let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2125        assert!(m.validate_jwt_token_at(&token, at + 60).is_ok());
2126    }
2127
2128    #[test]
2129    fn the_previous_key_stops_verifying_after_the_grace_window_without_a_retire_call() {
2130        let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2131        let grace = m.previous_key_grace.as_secs() as i64;
2132        assert!(m.validate_jwt_token_at(&token, at + grace).is_ok());
2133        assert!(m.validate_jwt_token_at(&token, at + grace + 1).is_err());
2134    }
2135
2136    #[test]
2137    fn the_grace_window_is_configurable() {
2138        let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2139        let m = m.with_previous_key_grace(Duration::from_secs(10));
2140        assert!(m.validate_jwt_token_at(&token, at + 10).is_ok());
2141        assert!(m.validate_jwt_token_at(&token, at + 11).is_err());
2142    }
2143
2144    #[test]
2145    fn a_token_issued_after_the_rotation_is_not_accepted_under_the_previous_key() {
2146        // The rotation is recorded as having happened in the past, so a token the old key signs
2147        // now was "issued" after it.
2148        let old = TokenManager::new_hmac(OLD_SECRET, "iss", "aud");
2149        let mut m = old.clone();
2150        m.rotate_hmac_key_at(NEW_SECRET, Utc::now().timestamp() - 100);
2151        let late = old
2152            .create_jwt_token("user-1", vec![], Some(Duration::from_secs(3600)))
2153            .unwrap();
2154        assert!(m.validate_jwt_token(&late).is_err());
2155    }
2156
2157    #[test]
2158    fn a_long_lived_token_is_not_accepted_under_the_previous_key() {
2159        let (m, long, at) = rotated_with_old_token(Duration::from_secs(48 * 3600));
2160        assert!(m.validate_jwt_token_at(&long, at + 1).is_err());
2161        let m = m.with_previous_key_max_token_lifetime(Duration::from_secs(72 * 3600));
2162        assert!(m.validate_jwt_token_at(&long, at + 1).is_ok());
2163    }
2164
2165    #[test]
2166    fn retire_previous_key_still_retires_at_once() {
2167        let (mut m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2168        m.retire_previous_key();
2169        assert!(m.validate_jwt_token_at(&token, at + 1).is_err());
2170    }
2171
2172    #[test]
2173    fn tokens_from_the_current_key_are_unaffected_by_the_grace_window() {
2174        let (m, _, at) = rotated_with_old_token(Duration::from_secs(3600));
2175        let fresh = m
2176            .create_jwt_token("user-2", vec![], Some(Duration::from_secs(3600)))
2177            .unwrap();
2178        let grace = m.previous_key_grace.as_secs() as i64;
2179        assert!(m.validate_jwt_token_at(&fresh, at + grace + 1000).is_ok());
2180    }
2181
2182    #[test]
2183    fn a_clone_keeps_the_rotation_time_and_the_bounds() {
2184        let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2185        let m = m.with_previous_key_grace(Duration::from_secs(10));
2186        let c = m.clone();
2187        assert!(c.validate_jwt_token_at(&token, at + 10).is_ok());
2188        assert!(c.validate_jwt_token_at(&token, at + 11).is_err());
2189    }
2190}