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