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