1use std::{
2 collections::HashMap,
3 marker::PhantomData,
4 ops::Deref,
5 sync::Arc,
6 time::{Duration, SystemTime, UNIX_EPOCH},
7};
8
9use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
10use http::{HeaderValue, header};
11use jsonwebtoken::{
12 Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, decode_header, encode,
13};
14use phoenix_http::{
15 BoxFuture, FromRequest, IntoResponse, Middleware, Next, Request, Response, StatusCode,
16};
17use serde::{Deserialize, Serialize, de::DeserializeOwned};
18use thiserror::Error;
19use zeroize::Zeroizing;
20
21const MIN_SECRET_BYTES: usize = 32;
22
23#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
25pub struct JwtClaims<T> {
26 pub sub: String,
27 pub jti: String,
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub sid: Option<String>,
30 pub exp: u64,
31 pub iat: u64,
32 pub nbf: u64,
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub iss: Option<String>,
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub aud: Option<String>,
37 #[serde(flatten)]
38 pub custom: T,
39}
40
41#[derive(Clone)]
43pub struct JwtKey {
44 id: String,
45 secret: Zeroizing<Vec<u8>>,
46}
47
48impl JwtKey {
49 pub fn new(id: impl Into<String>, secret: impl AsRef<[u8]>) -> Result<Self, JwtError> {
55 let id = id.into();
56 if id.trim().is_empty() {
57 return Err(JwtError::InvalidKeyId);
58 }
59 if secret.as_ref().len() < MIN_SECRET_BYTES {
60 return Err(JwtError::WeakKey);
61 }
62 Ok(Self {
63 id,
64 secret: Zeroizing::new(secret.as_ref().to_vec()),
65 })
66 }
67
68 #[must_use]
69 pub fn id(&self) -> &str {
70 &self.id
71 }
72}
73
74impl std::fmt::Debug for JwtKey {
75 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 formatter
77 .debug_struct("JwtKey")
78 .field("id", &self.id)
79 .field("secret", &"[REDACTED]")
80 .finish()
81 }
82}
83
84#[derive(Clone, Debug)]
85pub struct JwtConfig {
86 pub ttl: Duration,
87 pub leeway: Duration,
88 pub issuer: Option<String>,
89 pub audience: Option<String>,
90}
91
92impl Default for JwtConfig {
93 fn default() -> Self {
94 Self {
95 ttl: Duration::from_mins(15),
96 leeway: Duration::from_secs(30),
97 issuer: None,
98 audience: None,
99 }
100 }
101}
102
103impl JwtConfig {
104 #[must_use]
105 pub const fn new(ttl: Duration) -> Self {
106 Self {
107 ttl,
108 leeway: Duration::from_secs(30),
109 issuer: None,
110 audience: None,
111 }
112 }
113
114 #[must_use]
115 pub const fn leeway(mut self, leeway: Duration) -> Self {
116 self.leeway = leeway;
117 self
118 }
119
120 #[must_use]
121 pub fn issuer(mut self, issuer: impl Into<String>) -> Self {
122 self.issuer = Some(issuer.into());
123 self
124 }
125
126 #[must_use]
127 pub fn audience(mut self, audience: impl Into<String>) -> Self {
128 self.audience = Some(audience.into());
129 self
130 }
131}
132
133#[derive(Clone, Debug)]
135pub struct JwtManager {
136 active_key_id: String,
137 keys: HashMap<String, JwtKey>,
138 config: JwtConfig,
139}
140
141impl JwtManager {
142 pub fn new(active: JwtKey, config: JwtConfig) -> Result<Self, JwtError> {
148 validate_config(&config)?;
149 let active_key_id = active.id.clone();
150 Ok(Self {
151 active_key_id,
152 keys: HashMap::from([(active.id.clone(), active)]),
153 config,
154 })
155 }
156
157 #[must_use]
159 pub fn with_verification_key(mut self, key: JwtKey) -> Self {
160 self.keys.insert(key.id.clone(), key);
161 self
162 }
163
164 #[must_use]
166 pub const fn access_token_ttl(&self) -> Duration {
167 self.config.ttl
168 }
169
170 pub fn issue<T: Serialize>(
176 &self,
177 subject: impl Into<String>,
178 custom: T,
179 ) -> Result<String, JwtError> {
180 self.issue_at(subject.into(), custom, unix_timestamp()?)
181 }
182
183 fn issue_at<T: Serialize>(
184 &self,
185 subject: String,
186 custom: T,
187 now: u64,
188 ) -> Result<String, JwtError> {
189 self.issue_at_in_family(subject, custom, now, None)
190 .map(|(token, _)| token)
191 }
192
193 pub(crate) fn issue_at_in_family<T: Serialize>(
194 &self,
195 subject: String,
196 custom: T,
197 now: u64,
198 session_id: Option<String>,
199 ) -> Result<(String, JwtClaims<T>), JwtError> {
200 if subject.trim().is_empty() {
201 return Err(JwtError::InvalidSubject);
202 }
203 if session_id
204 .as_ref()
205 .is_some_and(|session_id| session_id.trim().is_empty())
206 {
207 return Err(JwtError::InvalidSessionId);
208 }
209 validate_custom_claims(&custom)?;
210 let key = self
211 .keys
212 .get(&self.active_key_id)
213 .ok_or(JwtError::UnknownKey)?;
214 let claims = JwtClaims {
215 sub: subject,
216 jti: random_identifier(),
217 sid: session_id,
218 exp: now.saturating_add(self.config.ttl.as_secs()),
219 iat: now,
220 nbf: now,
221 iss: self.config.issuer.clone(),
222 aud: self.config.audience.clone(),
223 custom,
224 };
225 let mut header = Header::new(Algorithm::HS256);
226 header.kid = Some(key.id.clone());
227 let token = encode(
228 &header,
229 &claims,
230 &EncodingKey::from_secret(key.secret.as_ref()),
231 )
232 .map_err(JwtError::Token)?;
233 Ok((token, claims))
234 }
235
236 pub fn verify<T: DeserializeOwned>(&self, token: &str) -> Result<JwtClaims<T>, JwtError> {
242 let header = decode_header(token).map_err(JwtError::Token)?;
243 if header.alg != Algorithm::HS256 {
244 return Err(JwtError::InvalidAlgorithm);
245 }
246 let key_id = header.kid.ok_or(JwtError::MissingKeyId)?;
247 let key = self.keys.get(&key_id).ok_or(JwtError::UnknownKey)?;
248 let mut validation = Validation::new(Algorithm::HS256);
249 validation.leeway = self.config.leeway.as_secs();
250 validation.validate_nbf = true;
251 let mut required = vec!["exp", "iat", "nbf", "sub", "jti"];
252 if let Some(issuer) = &self.config.issuer {
253 validation.set_issuer(&[issuer]);
254 required.push("iss");
255 }
256 if let Some(audience) = &self.config.audience {
257 validation.set_audience(&[audience]);
258 required.push("aud");
259 }
260 validation.set_required_spec_claims(&required);
261 let claims = decode::<JwtClaims<T>>(
262 token,
263 &DecodingKey::from_secret(key.secret.as_ref()),
264 &validation,
265 )
266 .map(|data| data.claims)
267 .map_err(JwtError::Token)?;
268 if claims.sub.trim().is_empty() {
269 return Err(JwtError::InvalidSubject);
270 }
271 if claims.jti.trim().is_empty() {
272 return Err(JwtError::InvalidTokenId);
273 }
274 if claims
275 .sid
276 .as_ref()
277 .is_some_and(|session_id| session_id.trim().is_empty())
278 {
279 return Err(JwtError::InvalidSessionId);
280 }
281 Ok(claims)
282 }
283}
284
285fn validate_custom_claims(custom: &impl Serialize) -> Result<(), JwtError> {
286 const RESERVED: &[&str] = &["sub", "jti", "sid", "exp", "iat", "nbf", "iss", "aud"];
287 let value = serde_json::to_value(custom).map_err(JwtError::CustomClaims)?;
288 let object = value
289 .as_object()
290 .ok_or(JwtError::CustomClaimsMustBeObject)?;
291 if object.keys().any(|key| RESERVED.contains(&key.as_str())) {
292 return Err(JwtError::ReservedClaim);
293 }
294 Ok(())
295}
296
297fn validate_config(config: &JwtConfig) -> Result<(), JwtError> {
298 if config.ttl.is_zero() {
299 return Err(JwtError::InvalidTtl);
300 }
301 if config
302 .issuer
303 .as_ref()
304 .is_some_and(|value| value.trim().is_empty())
305 || config
306 .audience
307 .as_ref()
308 .is_some_and(|value| value.trim().is_empty())
309 {
310 return Err(JwtError::InvalidClaimPolicy);
311 }
312 Ok(())
313}
314
315pub struct Jwt<T>(Arc<JwtClaims<T>>);
317
318impl<T> Jwt<T> {
319 pub(crate) fn from_verified(claims: JwtClaims<T>) -> Self {
320 Self(Arc::new(claims))
321 }
322}
323
324impl<T> Clone for Jwt<T> {
325 fn clone(&self) -> Self {
326 Self(Arc::clone(&self.0))
327 }
328}
329
330impl<T> std::fmt::Debug for Jwt<T> {
331 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
332 formatter.debug_tuple("Jwt").field(&"[VERIFIED]").finish()
333 }
334}
335
336impl<T> Deref for Jwt<T> {
337 type Target = JwtClaims<T>;
338
339 fn deref(&self) -> &Self::Target {
340 &self.0
341 }
342}
343
344impl<T> FromRequest for Jwt<T>
345where
346 T: Send + Sync + 'static,
347{
348 type Rejection = JwtRejection;
349
350 fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
351 request
352 .extensions()
353 .get::<Self>()
354 .cloned()
355 .ok_or(JwtRejection)
356 }
357}
358
359#[derive(Clone, Debug)]
361pub struct JwtAuth<T> {
362 manager: Arc<JwtManager>,
363 marker: PhantomData<fn() -> T>,
364}
365
366impl<T> JwtAuth<T> {
367 #[must_use]
368 pub fn new(manager: impl Into<Arc<JwtManager>>) -> Self {
369 Self {
370 manager: manager.into(),
371 marker: PhantomData,
372 }
373 }
374}
375
376impl<T> Middleware for JwtAuth<T>
377where
378 T: DeserializeOwned + Send + Sync + 'static,
379{
380 fn handle(&self, mut request: Request, next: Next) -> BoxFuture<Response> {
381 let manager = Arc::clone(&self.manager);
382 Box::pin(async move {
383 let token = request
384 .headers()
385 .get(header::AUTHORIZATION)
386 .and_then(|value| value.to_str().ok())
387 .and_then(bearer_token);
388 let Some(token) = token else {
389 return JwtRejection.into_response();
390 };
391 let Ok(claims) = manager.verify::<T>(token) else {
392 return JwtRejection.into_response();
393 };
394 request.extensions_mut().insert(Jwt::from_verified(claims));
395 next.run(request).await
396 })
397 }
398}
399
400pub(crate) fn bearer_token(value: &str) -> Option<&str> {
401 let (scheme, token) = value.split_once(' ')?;
402 (scheme.eq_ignore_ascii_case("bearer")
403 && !token.is_empty()
404 && !token.chars().any(char::is_whitespace))
405 .then_some(token)
406}
407
408#[derive(Clone, Copy, Debug, Error)]
409#[error("A valid bearer token is required.")]
410pub struct JwtRejection;
411
412impl IntoResponse for JwtRejection {
413 fn into_response(self) -> Response {
414 let mut response = Response::text("Unauthorized").with_status(StatusCode::UNAUTHORIZED);
415 response
416 .headers_mut()
417 .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
418 response
419 }
420}
421
422#[derive(Debug, Error)]
423pub enum JwtError {
424 #[error("JWT key IDs cannot be empty")]
425 InvalidKeyId,
426 #[error("JWT HS256 keys must contain at least 32 bytes")]
427 WeakKey,
428 #[error("JWT time-to-live must be greater than zero")]
429 InvalidTtl,
430 #[error("JWT issuer and audience policies cannot be empty")]
431 InvalidClaimPolicy,
432 #[error("JWT subject cannot be empty")]
433 InvalidSubject,
434 #[error("JWT token ID cannot be empty")]
435 InvalidTokenId,
436 #[error("JWT session ID cannot be empty")]
437 InvalidSessionId,
438 #[error("JWT header is missing a key ID")]
439 MissingKeyId,
440 #[error("JWT key ID is not recognized")]
441 UnknownKey,
442 #[error("JWT algorithm is not allowed")]
443 InvalidAlgorithm,
444 #[error("JWT custom claims must serialize as an object")]
445 CustomClaimsMustBeObject,
446 #[error("JWT custom claims cannot redefine reserved claims")]
447 ReservedClaim,
448 #[error("JWT custom claim serialization failed")]
449 CustomClaims(#[source] serde_json::Error),
450 #[error("JWT processing failed")]
451 Token(#[source] jsonwebtoken::errors::Error),
452 #[error("the system clock is before the Unix epoch")]
453 InvalidClock,
454}
455
456fn unix_timestamp() -> Result<u64, JwtError> {
457 SystemTime::now()
458 .duration_since(UNIX_EPOCH)
459 .map(|duration| duration.as_secs())
460 .map_err(|_| JwtError::InvalidClock)
461}
462
463pub(crate) fn current_timestamp() -> Result<u64, JwtError> {
464 unix_timestamp()
465}
466
467fn random_identifier() -> String {
468 URL_SAFE_NO_PAD.encode(rand::random::<[u8; 16]>())
469}
470
471#[cfg(test)]
472mod tests {
473 use super::*;
474 use phoenix_http::{Method, typed};
475 use phoenix_routing::Routes;
476
477 #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
478 struct UserClaims {
479 role: String,
480 }
481
482 #[derive(Serialize)]
483 struct ConflictingClaims {
484 sub: String,
485 }
486
487 fn manager(key_id: &str, byte: u8) -> JwtManager {
488 JwtManager::new(
489 JwtKey::new(key_id, [byte; 32]).unwrap(),
490 JwtConfig::new(Duration::from_mins(5))
491 .leeway(Duration::ZERO)
492 .issuer("phoenix.test")
493 .audience("api.test"),
494 )
495 .unwrap()
496 }
497
498 #[test]
499 fn round_trips_and_rotates_keys_without_exposing_secrets() {
500 let old = JwtKey::new("old", [7_u8; 32]).unwrap();
501 assert!(format!("{old:?}").contains("[REDACTED]"));
502 let old_manager = JwtManager::new(old.clone(), JwtConfig::default()).unwrap();
503 let token = old_manager
504 .issue(
505 "user-1",
506 UserClaims {
507 role: "admin".to_owned(),
508 },
509 )
510 .unwrap();
511 let rotated = JwtManager::new(
512 JwtKey::new("current", [9_u8; 32]).unwrap(),
513 JwtConfig::default(),
514 )
515 .unwrap()
516 .with_verification_key(old);
517
518 let claims = rotated.verify::<UserClaims>(&token).unwrap();
519 assert_eq!(claims.sub, "user-1");
520 assert_eq!(claims.custom.role, "admin");
521 }
522
523 #[test]
524 fn rejects_weak_unknown_and_expired_tokens() {
525 assert!(matches!(
526 JwtKey::new("weak", b"short"),
527 Err(JwtError::WeakKey)
528 ));
529 let active_manager = manager("active", 3);
530 let expired = active_manager
531 .issue_at(
532 "user-1".to_owned(),
533 UserClaims {
534 role: "member".to_owned(),
535 },
536 1,
537 )
538 .unwrap();
539 assert!(matches!(
540 active_manager.verify::<UserClaims>(&expired),
541 Err(JwtError::Token(_))
542 ));
543
544 let foreign = manager("foreign", 4)
545 .issue(
546 "user-1",
547 UserClaims {
548 role: "member".to_owned(),
549 },
550 )
551 .unwrap();
552 assert!(matches!(
553 active_manager.verify::<UserClaims>(&foreign),
554 Err(JwtError::UnknownKey)
555 ));
556 assert!(matches!(
557 active_manager.issue(
558 "user-1",
559 ConflictingClaims {
560 sub: "shadow".to_owned()
561 }
562 ),
563 Err(JwtError::ReservedClaim)
564 ));
565 assert!(matches!(
566 active_manager.issue(
567 " ",
568 UserClaims {
569 role: "member".to_owned(),
570 }
571 ),
572 Err(JwtError::InvalidSubject)
573 ));
574 assert!(matches!(
575 active_manager.issue_at_in_family(
576 "user-1".to_owned(),
577 UserClaims {
578 role: "member".to_owned(),
579 },
580 1,
581 Some(String::new()),
582 ),
583 Err(JwtError::InvalidSessionId)
584 ));
585 }
586
587 #[tokio::test]
588 async fn bearer_middleware_inserts_typed_verified_claims() {
589 let manager = manager("active", 5);
590 let token = manager
591 .issue(
592 "user-7",
593 UserClaims {
594 role: "editor".to_owned(),
595 },
596 )
597 .unwrap();
598 let handler = typed(|claims: Jwt<UserClaims>| async move {
599 format!("{}:{}", claims.sub, claims.custom.role)
600 });
601 let router = Routes::new()
602 .get("/private", handler)
603 .with_middleware(JwtAuth::<UserClaims>::new(Arc::new(manager)))
604 .build()
605 .unwrap();
606
607 let missing = router
608 .handle(Request::new(Method::GET, "/private".parse().unwrap()))
609 .await;
610 assert_eq!(missing.status(), StatusCode::UNAUTHORIZED);
611 assert_eq!(missing.headers()[header::WWW_AUTHENTICATE], "Bearer");
612
613 let mut request = Request::new(Method::GET, "/private".parse().unwrap());
614 request.headers_mut().insert(
615 header::AUTHORIZATION,
616 HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
617 );
618 let response = router.handle(request).await;
619 assert_eq!(response.status(), StatusCode::OK);
620 assert_eq!(response.body(), "user-7:editor");
621 }
622}