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