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