1use 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#[cfg_attr(feature = "postgres-storage", derive(FromRow))]
22#[derive(Clone, Serialize, Deserialize)]
23pub struct AuthToken {
24 pub token_id: String,
26
27 pub user_id: String,
29
30 pub access_token: String,
32
33 pub token_type: Option<String>,
35
36 pub subject: Option<String>,
38
39 pub issuer: Option<String>,
41
42 pub refresh_token: Option<String>,
44
45 pub issued_at: DateTime<Utc>,
47
48 pub expires_at: DateTime<Utc>,
50
51 pub scopes: crate::types::Scopes,
53
54 pub auth_method: String,
56
57 pub client_id: Option<String>,
59
60 pub user_profile: Option<ProviderProfile>,
62
63 pub permissions: crate::types::Permissions,
65
66 pub roles: crate::types::Roles,
68
69 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#[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 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 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 pub fn subject(mut self, subject: impl Into<String>) -> Self {
236 self.subject = Some(subject.into());
237 self
238 }
239
240 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
253 self.issuer = Some(issuer.into());
254 self
255 }
256
257 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 pub fn issued_at(mut self, issued_at: DateTime<Utc>) -> Self {
289 self.issued_at = issued_at;
290 self
291 }
292
293 pub fn expires_at(mut self, expires_at: DateTime<Utc>) -> Self {
307 self.expires_at = expires_at;
308 self
309 }
310
311 pub fn scopes(mut self, scopes: crate::types::Scopes) -> Self {
324 self.scopes = scopes;
325 self
326 }
327
328 pub fn auth_method(mut self, auth_method: impl Into<String>) -> Self {
341 self.auth_method = auth_method.into();
342 self
343 }
344
345 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 pub fn user_profile(mut self, user_profile: ProviderProfile) -> Self {
376 self.user_profile = Some(user_profile);
377 self
378 }
379
380 pub fn permissions(mut self, permissions: crate::types::Permissions) -> Self {
393 self.permissions = permissions;
394 self
395 }
396
397 pub fn roles(mut self, roles: crate::types::Roles) -> Self {
410 self.roles = roles;
411 self
412 }
413
414 pub fn metadata(mut self, metadata: TokenMetadata) -> Self {
427 self.metadata = metadata;
428 self
429 }
430
431 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 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#[derive(Clone, Serialize, Deserialize, Default)]
489pub struct TokenMetadata {
490 pub issued_ip: Option<String>,
492
493 pub user_agent: Option<String>,
495
496 pub device_id: Option<String>,
498
499 pub session_id: Option<String>,
501
502 pub revoked: bool,
504
505 pub revoked_at: Option<DateTime<Utc>>,
507
508 pub revoked_reason: Option<String>,
510
511 pub last_used: Option<DateTime<Utc>>,
513
514 pub use_count: u64,
516
517 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 pub fn builder() -> TokenMetadataBuilder {
556 TokenMetadataBuilder::default()
557 }
558}
559
560#[derive(Debug, Clone, Default)]
562pub struct TokenMetadataBuilder {
563 inner: TokenMetadata,
564}
565
566impl TokenMetadataBuilder {
567 pub fn issued_ip(mut self, ip: impl Into<String>) -> Self {
578 self.inner.issued_ip = Some(ip.into());
579 self
580 }
581
582 pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
593 self.inner.user_agent = Some(ua.into());
594 self
595 }
596
597 pub fn device_id(mut self, id: impl Into<String>) -> Self {
608 self.inner.device_id = Some(id.into());
609 self
610 }
611
612 pub fn session_id(mut self, id: impl Into<String>) -> Self {
623 self.inner.session_id = Some(id.into());
624 self
625 }
626
627 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
688pub struct TokenInfo {
689 pub user_id: String,
691
692 pub username: Option<String>,
694
695 pub email: Option<String>,
697
698 pub name: Option<String>,
700
701 pub roles: Vec<String>,
703
704 pub permissions: Vec<String>,
706
707 pub attributes: HashMap<String, serde_json::Value>,
709}
710
711#[derive(Debug, Clone, Serialize, Deserialize)]
716pub struct JwtClaims {
717 pub sub: String,
719
720 pub iss: String,
722
723 pub aud: String,
725
726 pub exp: i64,
728
729 pub iat: i64,
731
732 pub nbf: i64,
734
735 pub jti: String,
737
738 pub scope: String,
740
741 pub permissions: Option<Vec<String>>,
743
744 pub roles: Option<Vec<String>>,
746
747 pub client_id: Option<String>,
749
750 #[serde(flatten)]
752 pub custom: HashMap<String, serde_json::Value>,
753}
754
755pub struct TokenManager {
762 encoding_key: EncodingKey,
764
765 decoding_key: DecodingKey,
767
768 previous_decoding_key: Option<DecodingKey>,
776
777 previous_rotated_at: Option<i64>,
779
780 previous_key_grace: Duration,
782
783 previous_key_max_token_lifetime: Duration,
785
786 key_material: KeyMaterial,
788
789 previous_key_material: Option<KeyMaterial>,
791
792 algorithm: Algorithm,
794
795 issuer: String,
797
798 audience: String,
800
801 default_lifetime: Duration,
803}
804
805const DEFAULT_PREVIOUS_KEY_WINDOW: Duration = Duration::from_secs(24 * 3600);
808
809#[derive(Clone)]
811enum KeyMaterial {
812 Hmac(Vec<u8>),
814 Rsa { private: Vec<u8>, public: Vec<u8> },
816}
817
818#[derive(Debug, Clone, Serialize, Deserialize)]
823pub struct JwksPublicKey {
824 pub algorithm: Algorithm,
826 pub kid: String,
828 pub n: String,
830 pub e: String,
832}
833
834impl AuthToken {
835 pub fn new(
837 user_id: impl Into<String>,
838 access_token: impl Into<String>,
839 expires_in: std::time::Duration,
840 auth_method: impl Into<String>,
841 ) -> Self {
842 let now = Utc::now();
843 let expires_in_chrono =
844 chrono::Duration::from_std(expires_in).unwrap_or(chrono::Duration::hours(1));
845
846 Self {
847 token_id: Uuid::new_v4().to_string(),
848 user_id: user_id.into(),
849 access_token: access_token.into(),
850 refresh_token: None,
851 token_type: Some("Bearer".to_string()),
852 subject: None,
853 issuer: None,
854 issued_at: now,
855 expires_at: now + expires_in_chrono,
856 scopes: crate::types::Scopes::empty(),
857 auth_method: auth_method.into(),
858 client_id: None,
859 user_profile: None,
860 permissions: crate::types::Permissions::empty(),
861 roles: crate::types::Roles::empty(),
862 metadata: TokenMetadata::default(),
863 }
864 }
865
866 pub fn access_token(&self) -> &str {
877 &self.access_token
878 }
879
880 pub fn user_id(&self) -> &str {
891 &self.user_id
892 }
893
894 pub fn expires_at(&self) -> DateTime<Utc> {
906 self.expires_at
907 }
908
909 pub fn token_value(&self) -> &str {
922 &self.access_token
923 }
924
925 pub fn token_type(&self) -> Option<&str> {
938 self.token_type.as_deref()
939 }
940
941 pub fn subject(&self) -> Option<&str> {
954 self.subject.as_deref()
955 }
956
957 pub fn issuer(&self) -> Option<&str> {
970 self.issuer.as_deref()
971 }
972
973 pub fn is_expired(&self) -> bool {
984 Utc::now() > self.expires_at
985 }
986
987 pub fn is_expiring(&self, within: Duration) -> bool {
999 Utc::now() + within > self.expires_at
1000 }
1001
1002 pub fn is_revoked(&self) -> bool {
1015 self.metadata.revoked
1016 }
1017
1018 pub fn is_valid(&self) -> bool {
1029 !self.is_expired() && !self.is_revoked()
1030 }
1031
1032 pub fn has_refresh_token(&self) -> bool {
1045 self.refresh_token.is_some()
1046 }
1047
1048 pub fn get_refresh_token(&self) -> Option<&str> {
1061 self.refresh_token.as_deref()
1062 }
1063
1064 pub fn revoke(&mut self, reason: Option<String>) {
1076 self.metadata.revoked = true;
1077 self.metadata.revoked_at = Some(Utc::now());
1078 self.metadata.revoked_reason = reason;
1079 }
1080
1081 pub fn mark_used(&mut self) {
1094 self.metadata.last_used = Some(Utc::now());
1095 self.metadata.use_count += 1;
1096 }
1097
1098 pub fn add_scope(&mut self, scope: impl Into<String>) {
1112 let scope = scope.into();
1113 if !self.scopes.contains(&scope) {
1114 self.scopes.push(scope);
1115 }
1116 }
1117
1118 pub fn has_scope(&self, scope: &str) -> bool {
1131 self.scopes.contains(scope)
1132 }
1133
1134 pub fn with_refresh_token(mut self, refresh_token: impl Into<String>) -> Self {
1146 self.refresh_token = Some(refresh_token.into());
1147 self
1148 }
1149
1150 pub fn with_client_id(mut self, client_id: impl Into<String>) -> Self {
1162 self.client_id = Some(client_id.into());
1163 self
1164 }
1165
1166 pub fn with_scopes(mut self, scopes: impl Into<crate::types::Scopes>) -> Self {
1179 self.scopes = scopes.into();
1180 self
1181 }
1182
1183 pub fn with_metadata(mut self, metadata: TokenMetadata) -> Self {
1196 self.metadata = metadata;
1197 self
1198 }
1199
1200 pub fn time_until_expiry(&self) -> Duration {
1214 let now = Utc::now();
1215 if self.expires_at > now {
1216 (self.expires_at - now).to_std().unwrap_or(Duration::ZERO)
1217 } else {
1218 Duration::ZERO
1219 }
1220 }
1221
1222 pub fn add_custom_claim(&mut self, key: impl Into<String>, value: serde_json::Value) {
1234 self.metadata.custom.insert(key.into(), value);
1235 }
1236
1237 pub fn get_custom_claim(&self, key: &str) -> Option<&serde_json::Value> {
1248 self.metadata.custom.get(key)
1249 }
1250
1251 pub fn has_permission(&self, permission: &str) -> bool {
1263 self.permissions.contains(permission)
1264 }
1265
1266 pub fn add_permission(&mut self, permission: impl Into<String>) {
1280 let permission = permission.into();
1281 if !self.permissions.contains(&permission) {
1282 self.permissions.push(permission);
1283 }
1284 }
1285
1286 pub fn add_role(&mut self, role: impl Into<String>) {
1300 let role = role.into();
1301 if !self.roles.contains(&role) {
1302 self.roles.push(role);
1303 }
1304 }
1305
1306 pub fn has_role(&self, role: &str) -> bool {
1319 self.roles.contains(role)
1320 }
1321
1322 pub fn with_permissions(mut self, permissions: impl Into<crate::types::Permissions>) -> Self {
1335 self.permissions = permissions.into();
1336 self
1337 }
1338
1339 pub fn with_roles(mut self, roles: impl Into<crate::types::Roles>) -> Self {
1352 self.roles = roles.into();
1353 self
1354 }
1355}
1356
1357impl Clone for TokenManager {
1358 fn clone(&self) -> Self {
1359 let (previous_decoding_key, previous_key_material) = match &self.previous_key_material {
1360 Some(KeyMaterial::Hmac(secret)) => (
1361 Some(DecodingKey::from_secret(secret)),
1362 Some(KeyMaterial::Hmac(secret.clone())),
1363 ),
1364 Some(KeyMaterial::Rsa { public, .. }) => (
1365 DecodingKey::from_rsa_pem(public).ok(),
1366 self.previous_key_material.clone(),
1367 ),
1368 None => (None, None),
1369 };
1370 match &self.key_material {
1371 KeyMaterial::Hmac(secret) => Self {
1372 encoding_key: EncodingKey::from_secret(secret),
1373 decoding_key: DecodingKey::from_secret(secret),
1374 previous_decoding_key,
1375 previous_rotated_at: self.previous_rotated_at,
1376 previous_key_grace: self.previous_key_grace,
1377 previous_key_max_token_lifetime: self.previous_key_max_token_lifetime,
1378 key_material: self.key_material.clone(),
1379 previous_key_material,
1380 algorithm: self.algorithm,
1381 issuer: self.issuer.clone(),
1382 audience: self.audience.clone(),
1383 default_lifetime: self.default_lifetime,
1384 },
1385 KeyMaterial::Rsa { private, public } => Self {
1386 encoding_key: EncodingKey::from_rsa_pem(private).expect("RSA private key PEM re-parse failed during Clone — this indicates memory corruption"),
1390 decoding_key: DecodingKey::from_rsa_pem(public).expect("RSA public key PEM re-parse failed during Clone — this indicates memory corruption"),
1391 previous_decoding_key,
1392 previous_rotated_at: self.previous_rotated_at,
1393 previous_key_grace: self.previous_key_grace,
1394 previous_key_max_token_lifetime: self.previous_key_max_token_lifetime,
1395 key_material: self.key_material.clone(),
1396 previous_key_material,
1397 algorithm: self.algorithm,
1398 issuer: self.issuer.clone(),
1399 audience: self.audience.clone(),
1400 default_lifetime: self.default_lifetime,
1401 },
1402 }
1403 }
1404}
1405
1406fn pem_to_der(pem: &str) -> Result<Vec<u8>> {
1408 let b64: String = pem
1409 .lines()
1410 .filter(|line| {
1411 !line.starts_with("-----BEGIN") && !line.starts_with("-----END") && !line.is_empty()
1412 })
1413 .collect();
1414
1415 base64::engine::general_purpose::STANDARD
1416 .decode(&b64)
1417 .map_err(|e| AuthError::crypto(format!("Failed to base64-decode PEM: {e}")))
1418}
1419
1420impl TokenManager {
1421 fn jwks_from_public_pem(public_key: &[u8], algorithm: Algorithm) -> Result<JwksPublicKey> {
1422 let pem = std::str::from_utf8(public_key)
1423 .map_err(|e| AuthError::crypto(format!("Invalid RSA public key PEM encoding: {e}")))?;
1424 let der = pem_to_der(pem)?;
1425
1426 let public_key = aws_lc_rs::rsa::PublicKey::from_der(&der).map_err(|e| {
1430 AuthError::crypto(format!(
1431 "Failed to parse RSA public key for JWKS export: {e}"
1432 ))
1433 })?;
1434
1435 let modulus = public_key.modulus().big_endian_without_leading_zero();
1436 let exponent = public_key.exponent().big_endian_without_leading_zero();
1437 let kid_digest = Sha256::digest(modulus);
1438
1439 let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus);
1440 let e = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(exponent);
1441 let kid = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(kid_digest);
1442
1443 Ok(JwksPublicKey {
1444 algorithm,
1445 kid,
1446 n,
1447 e,
1448 })
1449 }
1450
1451 pub fn export_public_jwks(&self) -> Result<Vec<JwksPublicKey>> {
1453 let mut keys = Vec::new();
1454
1455 if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1456 keys.push(Self::jwks_from_public_pem(public, self.algorithm)?);
1457 }
1458
1459 if self.previous_key_live(Utc::now().timestamp())
1460 && let Some(KeyMaterial::Rsa { public, .. }) = &self.previous_key_material
1461 {
1462 let previous = Self::jwks_from_public_pem(public, self.algorithm)?;
1463 if !keys.iter().any(|key| key.kid == previous.kid) {
1464 keys.push(previous);
1465 }
1466 }
1467
1468 Ok(keys)
1469 }
1470
1471 pub fn new_hmac(secret: &[u8], issuer: impl Into<String>, audience: impl Into<String>) -> Self {
1473 Self {
1474 encoding_key: EncodingKey::from_secret(secret),
1475 decoding_key: DecodingKey::from_secret(secret),
1476 previous_decoding_key: None,
1477 previous_rotated_at: None,
1478 previous_key_grace: DEFAULT_PREVIOUS_KEY_WINDOW,
1479 previous_key_max_token_lifetime: DEFAULT_PREVIOUS_KEY_WINDOW,
1480 key_material: KeyMaterial::Hmac(secret.to_vec()),
1481 previous_key_material: None,
1482 algorithm: Algorithm::HS256,
1483 issuer: issuer.into(),
1484 audience: audience.into(),
1485 default_lifetime: Duration::from_secs(3600), }
1487 }
1488
1489 pub fn new_rsa(
1517 private_key: &[u8],
1518 public_key: &[u8],
1519 issuer: impl Into<String>,
1520 audience: impl Into<String>,
1521 ) -> Result<Self> {
1522 let encoding_key = EncodingKey::from_rsa_pem(private_key)
1523 .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1524
1525 let decoding_key = DecodingKey::from_rsa_pem(public_key)
1526 .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1527
1528 Ok(Self {
1529 encoding_key,
1530 decoding_key,
1531 previous_decoding_key: None,
1532 previous_rotated_at: None,
1533 previous_key_grace: DEFAULT_PREVIOUS_KEY_WINDOW,
1534 previous_key_max_token_lifetime: DEFAULT_PREVIOUS_KEY_WINDOW,
1535 key_material: KeyMaterial::Rsa {
1536 private: private_key.to_vec(),
1537 public: public_key.to_vec(),
1538 },
1539 previous_key_material: None,
1540 algorithm: Algorithm::RS256,
1541 issuer: issuer.into(),
1542 audience: audience.into(),
1543 default_lifetime: Duration::from_secs(3600), })
1545 }
1546
1547 pub fn rotate_hmac_key(&mut self, new_secret: &[u8]) {
1550 self.rotate_hmac_key_at(new_secret, Utc::now().timestamp());
1551 }
1552
1553 fn rotate_hmac_key_at(&mut self, new_secret: &[u8], now: i64) {
1554 if let KeyMaterial::Hmac(secret) = &self.key_material {
1556 self.previous_decoding_key = Some(DecodingKey::from_secret(secret));
1557 self.previous_key_material = Some(KeyMaterial::Hmac(secret.clone()));
1558 self.previous_rotated_at = Some(now);
1559 }
1560
1561 self.encoding_key = EncodingKey::from_secret(new_secret);
1563 self.decoding_key = DecodingKey::from_secret(new_secret);
1564 self.key_material = KeyMaterial::Hmac(new_secret.to_vec());
1565 self.algorithm = Algorithm::HS256;
1566 }
1567
1568 pub fn rotate_rsa_key(&mut self, private_key: &[u8], public_key: &[u8]) -> Result<()> {
1571 let new_encoding_key = EncodingKey::from_rsa_pem(private_key)
1572 .map_err(|e| AuthError::crypto(format!("Invalid RSA private key: {e}")))?;
1573 let new_decoding_key = DecodingKey::from_rsa_pem(public_key)
1574 .map_err(|e| AuthError::crypto(format!("Invalid RSA public key: {e}")))?;
1575
1576 if let KeyMaterial::Rsa { public, .. } = &self.key_material {
1578 self.previous_decoding_key = DecodingKey::from_rsa_pem(public).ok();
1579 self.previous_key_material = Some(self.key_material.clone());
1580 self.previous_rotated_at = Some(Utc::now().timestamp());
1581 }
1582
1583 self.encoding_key = new_encoding_key;
1585 self.decoding_key = new_decoding_key;
1586 self.key_material = KeyMaterial::Rsa {
1587 private: private_key.to_vec(),
1588 public: public_key.to_vec(),
1589 };
1590 self.algorithm = Algorithm::RS256;
1591
1592 Ok(())
1593 }
1594
1595 pub fn retire_previous_key(&mut self) {
1597 self.previous_decoding_key = None;
1598 self.previous_key_material = None;
1599 self.previous_rotated_at = None;
1600 }
1601
1602 pub fn with_previous_key_grace(mut self, grace: Duration) -> Self {
1604 self.previous_key_grace = grace;
1605 self
1606 }
1607
1608 pub fn with_previous_key_max_token_lifetime(mut self, max: Duration) -> Self {
1611 self.previous_key_max_token_lifetime = max;
1612 self
1613 }
1614
1615 fn previous_key_live(&self, now: i64) -> bool {
1617 match self.previous_rotated_at {
1618 Some(at) => now.saturating_sub(at) <= self.previous_key_grace.as_secs() as i64,
1619 None => false,
1620 }
1621 }
1622
1623 fn previous_key_accepts(&self, claims: &JwtClaims, now: i64) -> bool {
1626 let Some(at) = self.previous_rotated_at else {
1627 return false;
1628 };
1629 self.previous_key_live(now)
1630 && claims.iat <= at
1631 && claims.exp.saturating_sub(claims.iat)
1632 <= self.previous_key_max_token_lifetime.as_secs() as i64
1633 }
1634
1635 pub fn with_default_lifetime(mut self, lifetime: Duration) -> Self {
1637 self.default_lifetime = lifetime;
1638 self
1639 }
1640
1641 pub fn create_jwt_token(
1643 &self,
1644 user_id: impl Into<String>,
1645 scopes: Vec<String>,
1646 lifetime: Option<Duration>,
1647 ) -> Result<String> {
1648 self.encode_jwt_token(user_id.into(), scopes, lifetime, None)
1649 }
1650
1651 pub fn create_client_jwt_token(
1654 &self,
1655 user_id: impl Into<String>,
1656 client_id: impl Into<String>,
1657 scopes: Vec<String>,
1658 lifetime: Option<Duration>,
1659 ) -> Result<String> {
1660 self.encode_jwt_token(user_id.into(), scopes, lifetime, Some(client_id.into()))
1661 }
1662
1663 fn encode_jwt_token(
1664 &self,
1665 user_id: String,
1666 scopes: Vec<String>,
1667 lifetime: Option<Duration>,
1668 client_id: Option<String>,
1669 ) -> Result<String> {
1670 let lifetime = lifetime.unwrap_or(self.default_lifetime);
1671 let now = Utc::now();
1672 let exp = now + chrono::Duration::from_std(lifetime).unwrap_or(chrono::Duration::hours(1));
1673
1674 let claims = JwtClaims {
1675 sub: user_id,
1676 iss: self.issuer.clone(),
1677 aud: self.audience.clone(),
1678 exp: exp.timestamp(),
1679 iat: now.timestamp(),
1680 nbf: now.timestamp(),
1681 jti: Uuid::new_v4().to_string(),
1682 scope: scopes.join(" "),
1683 permissions: None,
1684 roles: None,
1685 client_id,
1686 custom: HashMap::new(),
1687 };
1688
1689 let header = Header::new(self.algorithm);
1690
1691 encode(&header, &claims, &self.encoding_key)
1692 .map_err(|e| TokenError::creation_failed(format!("JWT encoding failed: {e}")).into())
1693 }
1694
1695 pub fn validate_session_jwt_token(&self, token: &str) -> Result<JwtClaims> {
1699 let claims = self.validate_jwt_token(token)?;
1700 if claims.client_id.is_some() {
1701 return Err(AuthError::Token(TokenError::Invalid {
1702 message: "Token was issued to an OAuth client and is not a user session"
1703 .to_string(),
1704 }));
1705 }
1706 Ok(claims)
1707 }
1708
1709 pub fn validate_jwt_token(&self, token: &str) -> Result<JwtClaims> {
1711 self.validate_jwt_token_at(token, Utc::now().timestamp())
1712 }
1713
1714 fn validate_jwt_token_at(&self, token: &str, now: i64) -> Result<JwtClaims> {
1715 let mut validation = Validation::new(self.algorithm);
1716 validation.set_issuer(&[&self.issuer]);
1717 validation.set_audience(&[&self.audience]);
1718
1719 match decode::<JwtClaims>(token, &self.decoding_key, &validation) {
1720 Ok(token_data) => Ok(token_data.claims),
1721 Err(e) => {
1722 match e.kind() {
1723 jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
1724 Err(AuthError::Token(TokenError::Expired))
1725 }
1726 jsonwebtoken::errors::ErrorKind::InvalidSignature => {
1727 if self.previous_key_live(now)
1729 && let Some(prev_key) = &self.previous_decoding_key
1730 && let Ok(prev_token_data) =
1731 decode::<JwtClaims>(token, prev_key, &validation)
1732 && self.previous_key_accepts(&prev_token_data.claims, now)
1733 {
1734 return Ok(prev_token_data.claims);
1735 }
1736
1737 Err(AuthError::Token(TokenError::Invalid {
1738 message: "Invalid token signature".to_string(),
1739 }))
1740 }
1741 _ => Err(AuthError::Token(TokenError::Invalid {
1742 message: "Invalid token format".to_string(),
1743 })),
1744 }
1745 }
1746 }
1747 }
1748
1749 pub fn create_auth_token(
1751 &self,
1752 user_id: impl Into<String>,
1753 scopes: impl Into<crate::types::Scopes>,
1754 auth_method: impl Into<String>,
1755 lifetime: Option<std::time::Duration>,
1756 ) -> Result<AuthToken> {
1757 let user_id_str = user_id.into();
1758 let scopes: crate::types::Scopes = scopes.into();
1759 let lifetime = lifetime.unwrap_or(self.default_lifetime);
1760
1761 let jwt_token = self.create_jwt_token(&user_id_str, scopes.to_vec(), Some(lifetime))?;
1762
1763 let token =
1764 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method).with_scopes(scopes);
1765
1766 Ok(token)
1767 }
1768
1769 pub fn create_client_auth_token(
1772 &self,
1773 user_id: impl Into<String>,
1774 client_id: impl Into<String>,
1775 scopes: impl Into<crate::types::Scopes>,
1776 auth_method: impl Into<String>,
1777 lifetime: Option<std::time::Duration>,
1778 ) -> Result<AuthToken> {
1779 let user_id_str = user_id.into();
1780 let client_id = client_id.into();
1781 let scopes: crate::types::Scopes = scopes.into();
1782 let lifetime = lifetime.unwrap_or(self.default_lifetime);
1783
1784 let jwt_token = self.create_client_jwt_token(
1785 &user_id_str,
1786 &client_id,
1787 scopes.to_vec(),
1788 Some(lifetime),
1789 )?;
1790
1791 Ok(
1792 AuthToken::new(user_id_str, jwt_token, lifetime, auth_method)
1793 .with_scopes(scopes)
1794 .with_client_id(client_id),
1795 )
1796 }
1797
1798 pub fn validate_auth_token(&self, token: &AuthToken) -> Result<()> {
1800 if token.is_expired() {
1802 return Err(TokenError::Expired.into());
1803 }
1804
1805 if token.is_revoked() {
1807 return Err(TokenError::Invalid {
1808 message: "Token has been revoked".to_string(),
1809 }
1810 .into());
1811 }
1812
1813 if token.auth_method == "jwt" || token.access_token.contains('.') {
1815 self.validate_jwt_token(&token.access_token)?;
1816 }
1817
1818 Ok(())
1819 }
1820
1821 pub fn refresh_token(&self, token: &AuthToken) -> Result<AuthToken> {
1823 if token.is_expired() {
1824 return Err(TokenError::Expired.into());
1825 }
1826
1827 if token.is_revoked() {
1828 return Err(TokenError::Invalid {
1829 message: "Cannot refresh revoked token".to_string(),
1830 }
1831 .into());
1832 }
1833
1834 if let Some(client_id) = &token.client_id {
1836 return self.create_client_auth_token(
1837 &token.user_id,
1838 client_id,
1839 token.scopes.clone(),
1840 &token.auth_method,
1841 Some(self.default_lifetime),
1842 );
1843 }
1844 self.create_auth_token(
1845 &token.user_id,
1846 token.scopes.clone(),
1847 &token.auth_method,
1848 Some(self.default_lifetime),
1849 )
1850 }
1851
1852 pub fn extract_token_info(&self, token: &str) -> Result<TokenInfo> {
1854 let claims = self.validate_jwt_token(token)?;
1855
1856 Ok(TokenInfo {
1857 user_id: claims.sub,
1858 username: claims
1859 .custom
1860 .get("username")
1861 .and_then(|v| v.as_str())
1862 .map(|s| s.to_string()),
1863 email: claims
1864 .custom
1865 .get("email")
1866 .and_then(|v| v.as_str())
1867 .map(|s| s.to_string()),
1868 name: claims
1869 .custom
1870 .get("name")
1871 .and_then(|v| v.as_str())
1872 .map(|s| s.to_string()),
1873 roles: claims
1874 .custom
1875 .get("roles")
1876 .and_then(|v| v.as_array())
1877 .map(|arr| {
1878 arr.iter()
1879 .filter_map(|v| v.as_str())
1880 .map(|s| s.to_string())
1881 .collect()
1882 })
1883 .unwrap_or_default(),
1884 permissions: claims
1885 .scope
1886 .split_whitespace()
1887 .map(|s| s.to_string())
1888 .collect(),
1889 attributes: claims.custom,
1890 })
1891 }
1892}
1893
1894#[async_trait::async_trait]
1896pub trait TokenToProfile {
1897 async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile>;
1899
1900 async fn to_profile_with_extractor(
1902 &self,
1903 provider: &OAuthProvider,
1904 extractor: &ProfileExtractor,
1905 ) -> Result<ProviderProfile>;
1906}
1907
1908#[async_trait::async_trait]
1909impl TokenToProfile for AuthToken {
1910 async fn to_profile(&self, provider: &OAuthProvider) -> Result<ProviderProfile> {
1911 let extractor = ProfileExtractor::new();
1912 extractor.extract_profile(self, provider).await
1913 }
1914
1915 async fn to_profile_with_extractor(
1916 &self,
1917 provider: &OAuthProvider,
1918 extractor: &ProfileExtractor,
1919 ) -> Result<ProviderProfile> {
1920 extractor.extract_profile(self, provider).await
1921 }
1922}
1923
1924#[cfg(test)]
1925mod tests {
1926 use super::*;
1927
1928 #[test]
1929 fn test_auth_token_creation() {
1930 let token = AuthToken::new(
1931 "user123",
1932 "token123",
1933 Duration::from_secs(3600), "password",
1935 );
1936
1937 assert_eq!(token.user_id(), "user123");
1938 assert_eq!(token.access_token(), "token123");
1939 assert!(!token.is_expired());
1940 assert!(!token.is_revoked());
1941 assert!(token.is_valid());
1942 }
1943
1944 #[test]
1945 fn test_token_expiry() {
1946 let token = AuthToken::new("user123", "token123", Duration::from_millis(1), "password");
1947
1948 std::thread::sleep(std::time::Duration::from_millis(10));
1950
1951 assert!(token.is_expired());
1952 assert!(!token.is_valid());
1953 }
1954
1955 #[test]
1956 fn test_token_revocation() {
1957 let mut token = AuthToken::new(
1958 "user123",
1959 "token123",
1960 Duration::from_secs(3600), "password",
1962 );
1963
1964 assert!(!token.is_revoked());
1965
1966 token.revoke(Some("User logout".to_string()));
1967
1968 assert!(token.is_revoked());
1969 assert!(!token.is_valid());
1970 assert!(token.metadata.revoked);
1971 }
1972
1973 fn generate_test_rsa_pems() -> (Vec<u8>, Vec<u8>) {
1974 use aws_lc_rs::signature::KeyPair as _;
1975
1976 fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
1977 let b64 = base64::engine::general_purpose::STANDARD.encode(der);
1978 let mut pem = format!("-----BEGIN {label}-----\n");
1979 for chunk in b64.as_bytes().chunks(64) {
1980 pem.push_str(std::str::from_utf8(chunk).unwrap());
1981 pem.push('\n');
1982 }
1983 pem.push_str(&format!("-----END {label}-----\n"));
1984 pem.into_bytes()
1985 }
1986
1987 let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
1988 .expect("RSA key generation failed");
1989 let priv_der =
1990 aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
1991 .expect("private key DER export failed");
1992 let pub_der = key_pair.public_key().as_ref();
1993
1994 (
1995 der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
1996 der_to_pem(pub_der, "RSA PUBLIC KEY"),
2000 )
2001 }
2002
2003 fn generate_test_rsa_pems_spki_public() -> (Vec<u8>, Vec<u8>) {
2009 use aws_lc_rs::signature::KeyPair as _;
2010
2011 fn der_to_pem(der: &[u8], label: &str) -> Vec<u8> {
2012 let b64 = base64::engine::general_purpose::STANDARD.encode(der);
2013 let mut pem = format!("-----BEGIN {label}-----\n");
2014 for chunk in b64.as_bytes().chunks(64) {
2015 pem.push_str(std::str::from_utf8(chunk).unwrap());
2016 pem.push('\n');
2017 }
2018 pem.push_str(&format!("-----END {label}-----\n"));
2019 pem.into_bytes()
2020 }
2021
2022 let key_pair = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
2023 .expect("RSA key generation failed");
2024 let priv_der =
2025 aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::Pkcs8V1Der>::as_der(&key_pair)
2026 .expect("private key DER export failed");
2027 let public_key = aws_lc_rs::rsa::PublicKey::from_der(key_pair.public_key().as_ref())
2028 .expect("re-parsing the freshly generated public key must succeed");
2029 let spki_der = aws_lc_rs::encoding::AsDer::<aws_lc_rs::encoding::PublicKeyX509Der>::as_der(
2030 &public_key,
2031 )
2032 .expect("SPKI DER export failed");
2033
2034 (
2035 der_to_pem(priv_der.as_ref(), "PRIVATE KEY"),
2036 der_to_pem(spki_der.as_ref(), "PUBLIC KEY"),
2037 )
2038 }
2039
2040 #[test]
2045 fn test_export_public_jwks_round_trips_rsa_key() {
2046 let (priv_pem, pub_pem) = generate_test_rsa_pems();
2047 let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
2048 .expect("TokenManager::new_rsa should accept a freshly generated RSA key pair");
2049
2050 let jwks = manager
2051 .export_public_jwks()
2052 .expect("JWKS export should succeed for a valid RSA key");
2053 assert_eq!(jwks.len(), 1, "exactly one key, no previous key configured");
2054
2055 let exported = &jwks[0];
2056 assert_eq!(exported.algorithm, Algorithm::RS256);
2057 assert!(!exported.n.is_empty());
2058 assert!(!exported.e.is_empty());
2059
2060 let der = pem_to_der(std::str::from_utf8(&pub_pem).unwrap()).unwrap();
2063 let public_key =
2064 aws_lc_rs::rsa::PublicKey::from_der(&der).expect("public key DER should parse");
2065 let expected_n = base64::engine::general_purpose::URL_SAFE_NO_PAD
2066 .encode(public_key.modulus().big_endian_without_leading_zero());
2067 let expected_e = base64::engine::general_purpose::URL_SAFE_NO_PAD
2068 .encode(public_key.exponent().big_endian_without_leading_zero());
2069 assert_eq!(exported.n, expected_n);
2070 assert_eq!(exported.e, expected_e);
2071
2072 let token = manager
2077 .create_jwt_token("test-user", vec![], None)
2078 .expect("signing with the freshly generated RSA key should succeed");
2079 let decoding_key = DecodingKey::from_rsa_components(&exported.n, &exported.e)
2080 .expect("DecodingKey should accept the exported n/e");
2081 let mut validation = Validation::new(Algorithm::RS256);
2082 validation.set_issuer(&["test-issuer"]);
2083 validation.set_audience(&["test-audience"]);
2084 decode::<JwtClaims>(&token, &decoding_key, &validation)
2085 .expect("a token signed by this key must verify against its own exported JWKS");
2086 }
2087
2088 #[test]
2093 fn test_export_public_jwks_accepts_spki_public_key_pem() {
2094 let (priv_pem, pub_pem) = generate_test_rsa_pems_spki_public();
2095 let manager = TokenManager::new_rsa(&priv_pem, &pub_pem, "test-issuer", "test-audience")
2096 .expect("TokenManager::new_rsa should accept an SPKI-form public key");
2097
2098 let jwks = manager
2099 .export_public_jwks()
2100 .expect("JWKS export should succeed for an SPKI-form RSA public key");
2101 assert_eq!(jwks.len(), 1);
2102 assert!(!jwks[0].n.is_empty());
2103 assert!(!jwks[0].e.is_empty());
2104 }
2105
2106 const OLD_SECRET: &[u8] = b"old-secret-old-secret-old-secret-0";
2107 const NEW_SECRET: &[u8] = b"new-secret-new-secret-new-secret-1";
2108
2109 fn rotated_with_old_token(old_lifetime: Duration) -> (TokenManager, String, i64) {
2112 let old = TokenManager::new_hmac(OLD_SECRET, "iss", "aud");
2113 let token = old
2114 .create_jwt_token("user-1", vec!["read".into()], Some(old_lifetime))
2115 .unwrap();
2116 let at = Utc::now().timestamp();
2117 let mut manager = old;
2118 manager.rotate_hmac_key_at(NEW_SECRET, at);
2119 (manager, token, at)
2120 }
2121
2122 #[test]
2123 fn the_previous_key_verifies_old_tokens_inside_the_grace_window() {
2124 let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2125 assert!(m.validate_jwt_token_at(&token, at + 60).is_ok());
2126 }
2127
2128 #[test]
2129 fn the_previous_key_stops_verifying_after_the_grace_window_without_a_retire_call() {
2130 let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2131 let grace = m.previous_key_grace.as_secs() as i64;
2132 assert!(m.validate_jwt_token_at(&token, at + grace).is_ok());
2133 assert!(m.validate_jwt_token_at(&token, at + grace + 1).is_err());
2134 }
2135
2136 #[test]
2137 fn the_grace_window_is_configurable() {
2138 let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2139 let m = m.with_previous_key_grace(Duration::from_secs(10));
2140 assert!(m.validate_jwt_token_at(&token, at + 10).is_ok());
2141 assert!(m.validate_jwt_token_at(&token, at + 11).is_err());
2142 }
2143
2144 #[test]
2145 fn a_token_issued_after_the_rotation_is_not_accepted_under_the_previous_key() {
2146 let old = TokenManager::new_hmac(OLD_SECRET, "iss", "aud");
2149 let mut m = old.clone();
2150 m.rotate_hmac_key_at(NEW_SECRET, Utc::now().timestamp() - 100);
2151 let late = old
2152 .create_jwt_token("user-1", vec![], Some(Duration::from_secs(3600)))
2153 .unwrap();
2154 assert!(m.validate_jwt_token(&late).is_err());
2155 }
2156
2157 #[test]
2158 fn a_long_lived_token_is_not_accepted_under_the_previous_key() {
2159 let (m, long, at) = rotated_with_old_token(Duration::from_secs(48 * 3600));
2160 assert!(m.validate_jwt_token_at(&long, at + 1).is_err());
2161 let m = m.with_previous_key_max_token_lifetime(Duration::from_secs(72 * 3600));
2162 assert!(m.validate_jwt_token_at(&long, at + 1).is_ok());
2163 }
2164
2165 #[test]
2166 fn retire_previous_key_still_retires_at_once() {
2167 let (mut m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2168 m.retire_previous_key();
2169 assert!(m.validate_jwt_token_at(&token, at + 1).is_err());
2170 }
2171
2172 #[test]
2173 fn tokens_from_the_current_key_are_unaffected_by_the_grace_window() {
2174 let (m, _, at) = rotated_with_old_token(Duration::from_secs(3600));
2175 let fresh = m
2176 .create_jwt_token("user-2", vec![], Some(Duration::from_secs(3600)))
2177 .unwrap();
2178 let grace = m.previous_key_grace.as_secs() as i64;
2179 assert!(m.validate_jwt_token_at(&fresh, at + grace + 1000).is_ok());
2180 }
2181
2182 #[test]
2183 fn a_clone_keeps_the_rotation_time_and_the_bounds() {
2184 let (m, token, at) = rotated_with_old_token(Duration::from_secs(3600));
2185 let m = m.with_previous_key_grace(Duration::from_secs(10));
2186 let c = m.clone();
2187 assert!(c.validate_jwt_token_at(&token, at + 10).is_ok());
2188 assert!(c.validate_jwt_token_at(&token, at + 11).is_err());
2189 }
2190}