1use std::str::FromStr;
8use std::sync::Arc;
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
11use argon2::Argon2;
12use argon2::password_hash::rand_core::OsRng;
13use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
14use serde::de::DeserializeOwned;
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17
18use crate::context::HttpContext;
19use crate::error::{Error, Result};
20use crate::http::{Cookie, Response};
21use crate::middleware::{BoxFuture, Middleware, Next};
22use crate::session::{Session, SessionData, SessionStore, new_id};
23
24#[derive(Debug, Clone, PartialEq)]
26pub struct Identity {
27 subject: String,
28 claims: Map<String, Value>,
29}
30
31impl Identity {
32 pub fn new(subject: impl Into<String>) -> Self {
33 Self {
34 subject: subject.into(),
35 claims: Map::new(),
36 }
37 }
38
39 #[must_use]
42 pub fn with_claim(mut self, name: impl Into<String>, value: impl Into<Value>) -> Self {
43 let name = name.into();
44
45 if !matches!(name.as_str(), "sub" | "exp" | "iat") {
46 self.claims.insert(name, value.into());
47 }
48 self
49 }
50
51 pub fn subject(&self) -> &str {
52 &self.subject
53 }
54
55 pub fn id<T: FromStr>(&self) -> Result<T> {
57 self.subject.parse().map_err(|_| {
58 Error::internal(format!(
59 "identity subject `{}` is not the expected id type",
60 self.subject
61 ))
62 })
63 }
64
65 pub fn claim<T: DeserializeOwned>(&self, name: &str) -> Result<Option<T>> {
66 match self.claims.get(name) {
67 Some(value) => serde_json::from_value(value.clone())
68 .map(Some)
69 .map_err(|err| Error::internal(format!("claim `{name}`: {err}"))),
70 None => Ok(None),
71 }
72 }
73
74 pub fn claims(&self) -> &Map<String, Value> {
75 &self.claims
76 }
77}
78
79#[derive(Debug, Default, Clone)]
83pub struct Auth {
84 identity: Option<Identity>,
85}
86
87impl Auth {
88 pub fn jwt() -> JwtGuard {
93 JwtGuard { required: true }
94 }
95
96 pub fn optional_jwt() -> JwtGuard {
99 JwtGuard { required: false }
100 }
101
102 pub fn session() -> SessionGuard {
111 SessionGuard {
112 ttl: SessionGuard::DEFAULT_TTL,
113 cookie: SessionGuard::DEFAULT_COOKIE,
114 secure: false,
115 }
116 }
117
118 pub fn check(&self) -> bool {
119 self.identity.is_some()
120 }
121
122 pub fn identity(&self) -> Result<&Identity> {
124 self.identity.as_ref().ok_or(Error::Unauthorized)
125 }
126
127 pub fn try_identity(&self) -> Option<&Identity> {
128 self.identity.as_ref()
129 }
130
131 pub fn id<T: FromStr>(&self) -> Result<T> {
133 self.identity()?.id()
134 }
135
136 pub fn set(&mut self, identity: Identity) {
137 self.identity = Some(identity);
138 }
139
140 pub fn forget(&mut self) {
141 self.identity = None;
142 }
143}
144
145pub struct Hash;
147
148impl Hash {
149 pub fn make(password: &str) -> Result<String> {
151 let salt = SaltString::generate(&mut OsRng);
152
153 Argon2::default()
154 .hash_password(password.as_bytes(), &salt)
155 .map(|hash| hash.to_string())
156 .map_err(|err| Error::internal(format!("could not hash password: {err}")))
157 }
158
159 pub fn verify(password: &str, hash: &str) -> bool {
165 let Ok(parsed) = PasswordHash::new(hash) else {
166 return false;
167 };
168
169 Argon2::default()
170 .verify_password(password.as_bytes(), &parsed)
171 .is_ok()
172 }
173}
174
175#[derive(Debug, Serialize, Deserialize)]
176struct Claims {
177 sub: String,
178 exp: u64,
179 iat: u64,
180 #[serde(flatten)]
181 extra: Map<String, Value>,
182}
183
184pub struct Jwt {
189 encoding: jsonwebtoken::EncodingKey,
190 decoding: jsonwebtoken::DecodingKey,
191 ttl: Duration,
192}
193
194impl std::fmt::Debug for Jwt {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 f.debug_struct("Jwt")
198 .field("ttl", &self.ttl)
199 .finish_non_exhaustive()
200 }
201}
202
203impl Jwt {
204 pub const DEFAULT_TTL: Duration = Duration::from_secs(60 * 60);
206
207 pub fn new(secret: impl AsRef<[u8]>) -> Self {
208 Self {
209 encoding: jsonwebtoken::EncodingKey::from_secret(secret.as_ref()),
210 decoding: jsonwebtoken::DecodingKey::from_secret(secret.as_ref()),
211 ttl: Self::DEFAULT_TTL,
212 }
213 }
214
215 #[must_use]
216 pub fn with_ttl(mut self, ttl: Duration) -> Self {
217 self.ttl = ttl;
218 self
219 }
220
221 pub fn ttl(&self) -> Duration {
222 self.ttl
223 }
224
225 pub fn sign(&self, identity: &Identity) -> Result<String> {
227 self.sign_expiring_at(identity, now() + self.ttl.as_secs())
228 }
229
230 pub fn sign_expiring_at(&self, identity: &Identity, expires_at: u64) -> Result<String> {
233 let claims = Claims {
234 sub: identity.subject.clone(),
235 exp: expires_at,
236 iat: now(),
237 extra: identity.claims.clone(),
238 };
239
240 jsonwebtoken::encode(&jsonwebtoken::Header::default(), &claims, &self.encoding)
241 .map_err(|err| Error::internal(format!("could not sign token: {err}")))
242 }
243
244 pub fn verify(&self, token: &str) -> Result<Identity> {
247 let mut validation = jsonwebtoken::Validation::new(jsonwebtoken::Algorithm::HS256);
248 validation.leeway = 0;
249
250 let data = jsonwebtoken::decode::<Claims>(token, &self.decoding, &validation)
251 .map_err(|_| Error::Unauthorized)?;
252
253 Ok(Identity {
254 subject: data.claims.sub,
255 claims: data.claims.extra,
256 })
257 }
258}
259
260fn now() -> u64 {
261 SystemTime::now()
262 .duration_since(UNIX_EPOCH)
263 .map(|elapsed| elapsed.as_secs())
264 .unwrap_or_default()
265}
266
267pub struct JwtGuard {
269 required: bool,
270}
271
272impl Middleware for JwtGuard {
273 fn handle<'a>(&'a self, mut ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>> {
274 Box::pin(async move {
275 match ctx.request.bearer_token() {
279 Some(token) => {
280 let jwt: Arc<Jwt> = ctx.services.get::<Jwt>()?;
281 let identity = jwt.verify(token)?;
282
283 ctx.auth.set(identity);
284 }
285 None if self.required => return Err(Error::Unauthorized),
286 None => {}
287 }
288
289 next.run(ctx).await
290 })
291 }
292}
293
294pub struct SessionGuard {
296 ttl: Duration,
297 cookie: &'static str,
298 secure: bool,
299}
300
301impl SessionGuard {
302 pub const DEFAULT_TTL: Duration = Duration::from_secs(60 * 60 * 24 * 14);
303 pub const DEFAULT_COOKIE: &'static str = "luxid_session";
304
305 #[must_use]
306 pub fn ttl(mut self, ttl: Duration) -> Self {
307 self.ttl = ttl;
308 self
309 }
310
311 #[must_use]
312 pub fn cookie(mut self, name: &'static str) -> Self {
313 self.cookie = name;
314 self
315 }
316
317 #[must_use]
319 pub fn secure(mut self, secure: bool) -> Self {
320 self.secure = secure;
321 self
322 }
323}
324
325impl Middleware for SessionGuard {
326 fn handle<'a>(&'a self, mut ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>> {
327 Box::pin(async move {
328 let store = ctx.services.get_dyn::<dyn SessionStore>().map_err(|_| {
329 Error::internal(
330 "sessions need a store. Bind one in `providers()`, e.g. \
331 `.bind::<dyn SessionStore, _>(|_| Arc::new(MemoryStore::new()))`.",
332 )
333 })?;
334
335 let presented = ctx.request.cookie(self.cookie).map(str::to_owned);
336
337 let (id, data) = match presented.as_deref() {
340 Some(id) => match store.load(id).await? {
341 Some(data) => (id.to_owned(), data),
342 None => (new_id(), SessionData::new()),
343 },
344 None => (new_id(), SessionData::new()),
345 };
346
347 let session = Session::attached(id, data);
348
349 session.age_flash();
353
354 if let Some(subject) = session.subject() {
355 ctx.auth.set(Identity::new(subject));
356 }
357
358 let handle = session.clone();
361 ctx.session = session;
362
363 let response = next.run(ctx).await?;
364
365 let (id, data, dirty, destroyed) = handle.snapshot();
366
367 if destroyed {
368 store.destroy(&id).await?;
369
370 return Ok(response.cookie(Cookie::removal(self.cookie)));
371 }
372
373 let rotated = presented.as_deref() != Some(id.as_str());
374
375 if dirty {
376 store.save(&id, data, self.ttl).await?;
377
378 if let Some(previous) = presented.as_deref()
381 && previous != id
382 {
383 store.destroy(previous).await?;
384 }
385 }
386
387 if rotated {
388 return Ok(response.cookie(
389 Cookie::new(self.cookie, id)
390 .max_age(self.ttl.as_secs() as i64)
391 .secure(self.secure),
392 ));
393 }
394
395 Ok(response)
396 })
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn hashes_verify_against_the_original_password() {
406 let hash = Hash::make("correct horse battery staple").expect("hashes");
407
408 assert!(Hash::verify("correct horse battery staple", &hash));
409 assert!(!Hash::verify("wrong password", &hash));
410 }
411
412 #[test]
413 fn the_same_password_hashes_differently_each_time() {
414 let first = Hash::make("secret").expect("hashes");
415 let second = Hash::make("secret").expect("hashes");
416
417 assert_ne!(first, second, "a fresh salt is used per hash");
418 assert!(Hash::verify("secret", &first));
419 assert!(Hash::verify("secret", &second));
420 }
421
422 #[test]
423 fn a_corrupt_stored_hash_fails_verification_rather_than_erroring() {
424 assert!(!Hash::verify("secret", "not-a-phc-string"));
425 assert!(!Hash::verify("secret", ""));
426 }
427
428 #[test]
429 fn tokens_round_trip_subject_and_claims() {
430 let jwt = Jwt::new("test-secret");
431 let identity = Identity::new("42")
432 .with_claim("role", "admin")
433 .with_claim("team", 7);
434
435 let token = jwt.sign(&identity).expect("signs");
436 let decoded = jwt.verify(&token).expect("verifies");
437
438 assert_eq!(decoded.subject(), "42");
439 assert_eq!(decoded.id::<i64>().expect("parses"), 42);
440 assert_eq!(
441 decoded.claim::<String>("role").expect("claim"),
442 Some("admin".into())
443 );
444 assert_eq!(decoded.claim::<i64>("team").expect("claim"), Some(7));
445 assert_eq!(decoded.claim::<String>("absent").expect("claim"), None);
446 }
447
448 #[test]
449 fn reserved_claims_cannot_be_overridden() {
450 let jwt = Jwt::new("test-secret");
451 let identity = Identity::new("1")
452 .with_claim("sub", "999")
453 .with_claim("exp", 0);
454
455 let decoded = jwt
456 .verify(&jwt.sign(&identity).expect("signs"))
457 .expect("verifies");
458
459 assert_eq!(
460 decoded.subject(),
461 "1",
462 "sub comes from the identity, not a claim"
463 );
464 }
465
466 #[test]
467 fn an_expired_token_is_rejected() {
468 let jwt = Jwt::new("test-secret");
469 let identity = Identity::new("1");
470
471 let token = jwt.sign_expiring_at(&identity, now() - 60).expect("signs");
472
473 assert_eq!(jwt.verify(&token).unwrap_err().status_code().as_u16(), 401);
474 }
475
476 #[test]
477 fn a_token_signed_with_another_secret_is_rejected() {
478 let issuer = Jwt::new("secret-a");
479 let verifier = Jwt::new("secret-b");
480
481 let token = issuer.sign(&Identity::new("1")).expect("signs");
482
483 assert_eq!(
484 verifier.verify(&token).unwrap_err().status_code().as_u16(),
485 401
486 );
487 }
488
489 #[test]
490 fn a_tampered_token_is_rejected() {
491 let jwt = Jwt::new("test-secret");
492 let token = jwt.sign(&Identity::new("1")).expect("signs");
493
494 let mut tampered = token.clone();
495 tampered.push('x');
496
497 assert!(jwt.verify(&tampered).is_err());
498 }
499
500 #[test]
501 fn verification_failures_do_not_explain_themselves() {
502 let jwt = Jwt::new("test-secret");
503 let expired = jwt
504 .sign_expiring_at(&Identity::new("1"), now() - 60)
505 .expect("signs");
506 let forged = Jwt::new("other").sign(&Identity::new("1")).expect("signs");
507
508 assert_eq!(
510 jwt.verify(&expired).unwrap_err().problem(),
511 jwt.verify(&forged).unwrap_err().problem()
512 );
513 }
514
515 #[test]
516 fn an_anonymous_auth_reports_unauthorized() {
517 let auth = Auth::default();
518
519 assert!(!auth.check());
520 assert!(auth.try_identity().is_none());
521 assert_eq!(auth.identity().unwrap_err().status_code().as_u16(), 401);
522 assert_eq!(auth.id::<i64>().unwrap_err().status_code().as_u16(), 401);
523 }
524
525 #[test]
526 fn setting_and_forgetting_an_identity() {
527 let mut auth = Auth::default();
528 auth.set(Identity::new("7"));
529
530 assert!(auth.check());
531 assert_eq!(auth.id::<i64>().expect("id"), 7);
532
533 auth.forget();
534 assert!(!auth.check());
535 }
536
537 #[test]
538 fn the_debug_output_never_leaks_key_material() {
539 let rendered = format!("{:?}", Jwt::new("super-secret-value"));
540 assert!(!rendered.contains("super-secret"), "{rendered}");
541 }
542}