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