Skip to main content

luxid_core/
auth.rs

1//! Authentication: password hashing, tokens, and the request's identity.
2//!
3//! `Auth` carries *who the request is*, not the user record. Loading a model
4//! from that identity belongs to the data layer, so `ctx.auth.user()` arrives
5//! with the ORM; everything a token-based API needs is here today.
6
7use 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/// Who the current request is, plus whatever claims came with them.
25#[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    /// Attach a claim. Reserved names (`sub`, `exp`, `iat`) are set by the
40    /// signer and cannot be overridden here.
41    #[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    /// The subject parsed into the app's id type.
56    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/// The authentication state of the current request.
80///
81/// Present on every context, authenticated or not.
82#[derive(Debug, Default, Clone)]
83pub struct Auth {
84    identity: Option<Identity>,
85}
86
87impl Auth {
88    /// Middleware that requires a valid bearer token.
89    ///
90    /// Resolves [`Jwt`] from the container, so the signing key is configured
91    /// once in `providers()`.
92    pub fn jwt() -> JwtGuard {
93        JwtGuard { required: true }
94    }
95
96    /// As [`Auth::jwt`], but allows anonymous requests through. Useful for
97    /// endpoints that render differently when signed in.
98    pub fn optional_jwt() -> JwtGuard {
99        JwtGuard { required: false }
100    }
101
102    /// Cookie-backed sessions.
103    ///
104    /// Loads the session, exposes it as `ctx.session`, sets `ctx.auth` from the
105    /// session's subject, and persists any changes afterwards. Anonymous
106    /// requests pass through — a session is how a user *becomes*
107    /// authenticated, so refusing them would leave nowhere to log in.
108    ///
109    /// Requires a `SessionStore` bound in `providers()`.
110    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    /// The identity, or a 401.
123    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    /// The authenticated subject parsed into the app's id type, or a 401.
132    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
145/// Argon2id password hashing.
146pub struct Hash;
147
148impl Hash {
149    /// Hash a password with a fresh random salt.
150    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    /// Verify a password against a stored hash.
160    ///
161    /// A malformed stored hash is a failed verification, not an error, so a
162    /// corrupt row cannot be distinguished from a wrong password by timing or
163    /// by response.
164    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
184/// HS256 token signing and verification.
185///
186/// Register once in `providers()`; [`Auth::jwt`] resolves it from the
187/// container.
188pub 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        // Never print key material.
197        f.debug_struct("Jwt")
198            .field("ttl", &self.ttl)
199            .finish_non_exhaustive()
200    }
201}
202
203impl Jwt {
204    /// Default lifetime for issued tokens.
205    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    /// Issue a token that expires after the configured TTL.
226    pub fn sign(&self, identity: &Identity) -> Result<String> {
227        self.sign_expiring_at(identity, now() + self.ttl.as_secs())
228    }
229
230    /// Issue a token with an explicit expiry, for short-lived links and the
231    /// like.
232    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    /// Verify a token. Any failure — bad signature, expiry, malformed — is a
245    /// 401 and never explains which, so tokens cannot be probed.
246    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
267/// Bearer-token guard produced by [`Auth::jwt`] / [`Auth::optional_jwt`].
268pub 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            // `bearer_token` borrows `ctx.request`; `ctx.auth` is a different
276            // field, so both borrows coexist and the token needs no copy. That
277            // is a per-request allocation avoided on every authenticated route.
278            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
294/// Cookie-backed session middleware, produced by [`Auth::session`].
295pub 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    /// Send the cookie only over HTTPS. Turn this on in production.
318    #[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            // An unknown or expired id starts a fresh session rather than
338            // failing: a stale cookie is ordinary, not an error.
339            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            // Last request's flash becomes readable now; this request starts a
350            // fresh bag. Done before the action runs so both middleware and
351            // actions see the same values.
352            session.age_flash();
353
354            if let Some(subject) = session.subject() {
355                ctx.auth.set(Identity::new(subject));
356            }
357
358            // The middleware keeps a handle so it can read back whatever the
359            // action did, after the context has been consumed.
360            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                // The old entry is dead once the id rotates; leaving it would
379                // keep a logged-in session alive under the previous cookie.
380                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        // Both render identically, so a caller cannot probe which failed.
509        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}