1pub(crate) mod account;
36mod device;
37pub mod events;
38mod external;
39mod inbox;
40pub(crate) mod module;
41pub mod notifications;
42pub mod one_time;
43pub mod passwordless;
44mod passwords;
45pub mod permissions;
46pub mod second_factor;
47mod throttle;
48mod tokens;
49mod user;
50mod verification;
51
52use std::collections::HashMap;
53use std::convert::Infallible;
54use std::ops::Deref;
55use std::sync::Arc;
56
57use axum::extract::{FromRequestParts, OptionalFromRequestParts, Request};
58use axum::http::header::{ACCEPT, AUTHORIZATION};
59use axum::http::request::Parts;
60use axum::http::{Method, StatusCode};
61use axum::middleware::Next;
62use axum::response::{IntoResponse, Redirect, Response};
63
64pub(crate) use account::require_password_confirmed;
65pub(crate) use device::require as device_guard;
66pub use device::{Device, DeviceToken, NewDeviceToken};
67pub use external::{confirm_identity, register_verified, registration_open, sign_in};
68pub use module::{Auth, Registration};
69pub use notifications::{
70 Channel, DatabaseMessage, DatabaseNotification, Notification, Recipient,
71 prune_read_notifications,
72};
73pub use one_time::{CodeCheck, OneTimeCode, prune_expired_codes};
74pub use passwordless::{LoginCodeDelivery, LoginCodes};
75pub(crate) use permissions::Grants;
76pub use permissions::Permissions;
77pub use second_factor::{PendingLogin, complete_login, pending_login};
78pub(crate) use throttle::LoginThrottle;
79pub use tokens::{AccessToken, NewToken, prune_expired_tokens};
80pub use user::{User, hash_password, needs_rehash, normalize_email, verify_password};
81pub use verification::send_verification;
82
83use crate::crypto::constant_time_eq;
84use crate::db::Db;
85use crate::{AppState, Error, Htmx, HxRedirect, Result, Session};
86
87pub(crate) const AUTH_ID: &str = "_auth_user_id";
88const AUTH_HASH: &str = "_auth_password_hash";
89const AUTH_AT: &str = "_auth_at";
91const AUTH_SID: &str = "_auth_session_id";
93const INTENDED: &str = "_intended";
94
95pub trait Policy {
112 fn allows(&self, user: &User, ability: &str) -> bool;
114}
115
116#[derive(Debug, Clone, serde::Serialize)]
133#[non_exhaustive]
134pub struct Can<T> {
135 #[serde(flatten)]
137 pub item: T,
138 #[serde(rename = "_can")]
140 pub abilities: std::collections::BTreeMap<String, bool>,
141}
142
143pub trait Viewer: viewer::Sealed {
147 fn as_user(&self) -> &User;
149
150 fn before(&self, _ability: &str) -> Option<bool> {
152 None
153 }
154}
155
156mod viewer {
157 pub trait Sealed {}
158 impl Sealed for super::User {}
159 impl Sealed for super::AuthUser {}
160}
161
162impl Viewer for User {
163 fn as_user(&self) -> &User {
164 self
165 }
166}
167
168impl Viewer for AuthUser {
169 fn as_user(&self) -> &User {
170 &self.user
171 }
172
173 fn before(&self, ability: &str) -> Option<bool> {
174 AuthUser::before(self, ability)
175 }
176}
177
178impl<T: Policy> Can<T> {
179 pub fn new<V: Viewer + ?Sized>(item: T, user: Option<&V>, abilities: &[&str]) -> Self {
181 let abilities = abilities
182 .iter()
183 .map(|ability| {
184 let allowed = user.is_some_and(|user| {
185 user.before(ability)
186 .unwrap_or_else(|| item.allows(user.as_user(), ability))
187 });
188 ((*ability).to_owned(), allowed)
189 })
190 .collect();
191 Self { item, abilities }
192 }
193}
194
195pub(crate) type Gate = Arc<dyn Fn(&User) -> bool + Send + Sync>;
196pub(crate) type GateBefore = Arc<dyn Fn(&User, &str) -> Option<bool> + Send + Sync>;
197pub(crate) type Gates = Arc<Access>;
198
199#[derive(Default)]
202pub(crate) struct Access {
203 pub gates: HashMap<String, Gate>,
204 pub before: Option<GateBefore>,
205 pub permissions: bool,
206}
207
208impl Access {
209 pub(crate) fn check(&self, user: &User, grants: &Grants, name: &str) -> bool {
212 if let Some(allowed) = self.before.as_ref().and_then(|before| before(user, name)) {
213 return allowed;
214 }
215 match self.gates.get(name) {
216 Some(check) => check(user),
217 None => grants.has_permission(name),
218 }
219 }
220}
221
222#[derive(Clone)]
224pub(crate) struct CurrentGrants {
225 user_id: i64,
226 grants: Arc<Grants>,
227}
228
229impl User {
230 pub fn has_role(&self, role: &str) -> bool {
239 current_grants(self.id).is_some_and(|g| g.has_role(role))
240 }
241
242 pub fn has_permission(&self, permission: &str) -> bool {
245 current_grants(self.id).is_some_and(|g| g.has_permission(permission))
246 }
247}
248
249pub(crate) fn current_user_id() -> Option<i64> {
251 crate::context::get::<CurrentGrants>().map(|current| current.user_id)
252}
253
254fn current_grants(user_id: i64) -> Option<Arc<Grants>> {
255 crate::context::get::<CurrentGrants>()
256 .filter(|current| current.user_id == user_id)
257 .map(|current| current.grants)
258}
259
260pub(crate) type AsyncGate = Arc<
261 dyn Fn(
262 User,
263 AppState,
264 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send>>
265 + Send
266 + Sync,
267>;
268
269#[derive(Clone)]
272pub(crate) struct CurrentUser {
273 pub user: Option<Arc<User>>,
274 pub gates: Gates,
275 pub token_id: Option<i64>,
278 pub abilities: Option<Arc<Vec<String>>>,
281 pub device: Option<Arc<Device>>,
283 pub grants: Arc<Grants>,
284}
285
286#[derive(Clone)]
290pub struct AuthUser {
291 user: Arc<User>,
292 gates: Gates,
293 state: Option<AppState>,
294 token_id: Option<i64>,
295 abilities: Option<Arc<Vec<String>>>,
296 grants: Arc<Grants>,
297 role_names: std::sync::OnceLock<Vec<String>>,
299}
300
301impl Deref for AuthUser {
302 type Target = User;
303
304 fn deref(&self) -> &User {
305 &self.user
306 }
307}
308
309impl AuthUser {
310 pub fn token_id(&self) -> Option<i64> {
314 self.token_id
315 }
316
317 pub fn token_can(&self, ability: &str) -> bool {
321 self.abilities
322 .as_ref()
323 .is_none_or(|list| list.iter().any(|a| a == ability || a == "*"))
324 }
325
326 pub fn has_role(&self, role: &str) -> bool {
330 self.grants.has_role(role)
331 }
332
333 pub fn has_permission(&self, permission: &str) -> bool {
337 self.grants.has_permission(permission)
338 }
339
340 pub fn has_permission_anywhere(&self, permission: &str) -> bool {
347 self.grants.has_permission_anywhere(permission)
348 }
349
350 pub fn has_role_in(&self, role: &str, scope: &permissions::Scope) -> bool {
353 self.grants.has_role_in(role, Some(scope))
354 }
355
356 pub fn has_permission_in(&self, permission: &str, scope: &permissions::Scope) -> bool {
360 self.grants.has_permission_in(permission, Some(scope))
361 }
362
363 pub fn scopes_with<M: crate::db::Model>(
367 &self,
368 permission: &str,
369 ) -> permissions::Scopes<M::Key> {
370 self.grants.scopes_with::<M>(permission)
371 }
372
373 pub fn role_names(&self) -> &[String] {
377 self.role_names.get_or_init(|| self.grants.roles())
378 }
379
380 pub fn can(&self, ability: &str, target: &impl Policy) -> bool {
383 self.before(ability)
384 .unwrap_or_else(|| target.allows(&self.user, ability))
385 }
386
387 fn before(&self, ability: &str) -> Option<bool> {
388 self.gates
389 .before
390 .as_ref()
391 .and_then(|before| before(&self.user, ability))
392 }
393
394 pub fn authorize(&self, ability: &str, target: &impl Policy) -> Result {
396 if self.can(ability, target) {
397 Ok(())
398 } else {
399 Err(Error::Forbidden)
400 }
401 }
402
403 pub fn allows(&self, gate: &str) -> bool {
407 self.gates.check(&self.user, &self.grants, gate)
408 }
409
410 pub fn gate(&self, gate: &str) -> Result {
412 if self.allows(gate) {
413 Ok(())
414 } else {
415 Err(Error::Forbidden)
416 }
417 }
418
419 pub async fn allows_async(&self, gate: &str) -> Result<bool> {
423 if let Some(allowed) = self.before(gate) {
424 return Ok(allowed);
425 }
426 if self.gates.gates.contains_key(gate) || self.grants.has_permission(gate) {
427 return Ok(self.allows(gate));
428 }
429 let Some(state) = &self.state else {
430 return Ok(false);
431 };
432 match state.async_gates.get(gate) {
433 Some(check) => check(self.user.as_ref().clone(), state.clone()).await,
434 None => Ok(false),
435 }
436 }
437
438 pub async fn gate_async(&self, gate: &str) -> Result {
440 if self.allows_async(gate).await? {
441 Ok(())
442 } else {
443 Err(Error::Forbidden)
444 }
445 }
446
447 pub fn user(&self) -> &User {
449 &self.user
450 }
451}
452
453impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
454 type Rejection = Response;
455
456 async fn from_request_parts(parts: &mut Parts, _: &S) -> std::result::Result<Self, Response> {
457 match current(&parts.extensions) {
458 Some(user) => Ok(user),
459 None => Err(unauthenticated(parts)),
460 }
461 }
462}
463
464impl<S: Send + Sync> OptionalFromRequestParts<S> for AuthUser {
465 type Rejection = Infallible;
466
467 async fn from_request_parts(
468 parts: &mut Parts,
469 _: &S,
470 ) -> std::result::Result<Option<Self>, Infallible> {
471 Ok(current(&parts.extensions))
472 }
473}
474
475pub(crate) fn auth_user_of(current: &CurrentUser, state: &AppState) -> Option<AuthUser> {
478 Some(AuthUser {
479 user: current.user.clone()?,
480 gates: current.gates.clone(),
481 state: Some(state.clone()),
482 token_id: current.token_id,
483 abilities: current.abilities.clone(),
484 grants: current.grants.clone(),
485 role_names: std::sync::OnceLock::new(),
486 })
487}
488
489fn current(extensions: &axum::http::Extensions) -> Option<AuthUser> {
490 let current = extensions.get::<CurrentUser>()?;
491 Some(AuthUser {
492 user: current.user.clone()?,
493 gates: current.gates.clone(),
494 state: extensions.get::<AppState>().cloned(),
495 token_id: current.token_id,
496 abilities: current.abilities.clone(),
497 grants: current.grants.clone(),
498 role_names: std::sync::OnceLock::new(),
499 })
500}
501
502pub fn login(session: &Session, user: &User, remember: Option<std::time::Duration>) -> Result {
506 session.regenerate_token();
507 session.put(AUTH_ID, user.id)?;
508 session.put(AUTH_HASH, fingerprint(&user.password))?;
509 session.put(AUTH_AT, unix_millis())?;
510 session.put(AUTH_SID, crate::crypto::random_token())?;
511 if let Some(lifetime) = remember {
512 session.set_lifetime(lifetime);
513 }
514 Ok(())
515}
516
517pub async fn logout(db: &Db, session: &Session) -> Result {
522 match (session.get::<i64>(AUTH_ID), session.get::<String>(AUTH_SID)) {
523 (Some(_), Some(sid)) => revoke_session(db, session, &sid).await?,
524 (Some(id), None) => {
526 user::revoke_sessions(db, id).await?;
527 }
528 _ => {}
529 }
530 session.flush();
531 Ok(())
532}
533
534pub async fn logout_other_devices(db: &Db, session: &Session, user: &User) -> Result {
537 let cut_off = user::revoke_sessions(db, user.id).await?;
538 let lifetime = session
541 .lifetime()
542 .map(|minutes| std::time::Duration::from_secs(minutes * 60));
543 login(session, user, lifetime)?;
544 session.put(AUTH_AT, cut_off + 1)?;
545 Ok(())
546}
547
548pub async fn change_password(
551 db: &Db,
552 session: &Session,
553 user: &mut User,
554 password: &str,
555) -> Result {
556 user.set_password(db, password).await?;
557 logout_other_devices(db, session, user).await
558}
559
560async fn revoke_session(db: &Db, session: &Session, sid: &str) -> Result {
562 let minutes = session.lifetime().unwrap_or(60 * 24 * 30);
563 let expires = crate::db::now() + chrono::Duration::minutes(minutes as i64);
564 crate::db::sql("DELETE FROM revoked_sessions WHERE expires_at < ?")
565 .bind(crate::db::now())
566 .execute(db)
567 .await?;
568 crate::db::sql(
569 "INSERT INTO revoked_sessions (id, expires_at) SELECT ?, ? \
570 WHERE NOT EXISTS (SELECT 1 FROM revoked_sessions WHERE id = ?)",
571 )
572 .bind(sid)
573 .bind(expires)
574 .bind(sid)
575 .execute(db)
576 .await?;
577 Ok(())
578}
579
580pub(crate) fn unix_millis() -> i64 {
581 crate::clock::unix_millis()
582}
583
584fn fingerprint(password_hash: &str) -> String {
587 use sha2::{Digest, Sha256};
588 let digest = Sha256::digest(password_hash.as_bytes());
589 digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
590}
591
592pub(crate) async fn middleware(
594 axum::extract::State(state): axum::extract::State<AppState>,
595 mut req: Request,
596 next: Next,
597) -> Response {
598 let bearer = req
599 .headers()
600 .get(AUTHORIZATION)
601 .and_then(|v| v.to_str().ok())
602 .and_then(|v| v.strip_prefix("Bearer "))
603 .map(str::to_owned);
604 let session = req.extensions().get::<Session>().cloned();
605 let mut device = None;
606 let (user, token) = match (&bearer, &session) {
607 (Some(bearer), _) if bearer.trim().starts_with('d') => {
608 match device::authenticate(&state.db, bearer.trim()).await {
609 Ok(found) => device = found.map(Arc::new),
610 Err(err) => tracing::error!(error = ?err, "could not check the device token"),
611 }
612 (None, None)
613 }
614 (Some(bearer), _) => match tokens::authenticate(&state.db, bearer.trim()).await {
617 Ok(Some((user, token))) => (Some(user), Some(token)),
618 Ok(None) => (None, None),
619 Err(err) => {
620 tracing::error!(error = ?err, "could not check the API token");
621 (None, None)
622 }
623 },
624 (None, Some(session)) => (resolve(&state, session).await, None),
625 (None, None) => (None, None),
626 };
627 let grants = match &user {
628 Some(user) if state.gates.permissions => {
629 match permissions::grants(&state.db, user.id).await {
630 Ok(grants) => grants,
631 Err(err) => {
632 tracing::error!(error = ?err, "could not load the user's roles");
633 Grants::default()
634 }
635 }
636 }
637 _ => Grants::default(),
638 };
639 let grants = Arc::new(grants);
640 if let Some(user) = &user {
641 crate::context::set(CurrentGrants {
644 user_id: user.id,
645 grants: grants.clone(),
646 });
647 }
648 req.extensions_mut().insert(CurrentUser {
649 user: user.map(Arc::new),
650 gates: state.gates.clone(),
651 token_id: token.as_ref().map(|t| t.0),
652 abilities: token.and_then(|t| t.1).map(Arc::new),
653 device,
654 grants,
655 });
656 req.extensions_mut().insert(state);
657 next.run(req).await
658}
659
660async fn resolve(state: &AppState, session: &Session) -> Option<User> {
661 let id: i64 = session.get(AUTH_ID)?;
662 let hash: String = session.get(AUTH_HASH).unwrap_or_default();
663 let logged_in_at: i64 = session.get(AUTH_AT).unwrap_or(0);
664 let sid: String = session.get(AUTH_SID).unwrap_or_default();
665 match User::find_with_revocation(&state.db, id, &sid).await {
666 Ok(Some((user, revoked_at, session_revoked)))
667 if constant_time_eq(&fingerprint(&user.password), &hash)
668 && (revoked_at == 0 || logged_in_at > revoked_at)
669 && !session_revoked =>
670 {
671 Some(user)
672 }
673 Ok(_) => {
674 session.remove(AUTH_ID);
677 session.remove(AUTH_HASH);
678 session.remove(AUTH_AT);
679 session.remove(AUTH_SID);
680 None
681 }
682 Err(err) => {
683 tracing::error!(error = ?err, "could not load the logged-in user");
684 None
685 }
686 }
687}
688
689fn wants_json(headers: &axum::http::HeaderMap) -> bool {
690 headers
691 .get(ACCEPT)
692 .and_then(|v| v.to_str().ok())
693 .is_some_and(|v| v.contains("application/json"))
694}
695
696fn path_or(state: Option<&AppState>, route: &str, fallback: &str) -> String {
697 state
698 .and_then(|s| s.url(route, &[]).ok())
699 .unwrap_or_else(|| fallback.to_owned())
700}
701
702fn unauthenticated(parts: &Parts) -> Response {
704 if wants_json(&parts.headers) || parts.headers.contains_key(AUTHORIZATION) {
705 let body = serde_json::json!({ "message": "Unauthenticated." });
706 return (StatusCode::UNAUTHORIZED, axum::Json(body)).into_response();
707 }
708 let login = path_or(parts.extensions.get::<AppState>(), "login", "/login");
709 if let (Some(session), &Method::GET) = (parts.extensions.get::<Session>(), &parts.method) {
710 let intended = parts
711 .uri
712 .path_and_query()
713 .map(|p| p.as_str().to_owned())
714 .unwrap_or_else(|| "/".into());
715 let _ = session.put(INTENDED, intended);
716 }
717 if Htmx::from_headers(&parts.headers).request {
718 return HxRedirect(login).into_response();
719 }
720 Redirect::to(&login).into_response()
721}
722
723pub(crate) async fn require_auth(req: Request, next: Next) -> Response {
725 if current(req.extensions()).is_some() {
726 return next.run(req).await;
727 }
728 let (parts, _) = req.into_parts();
729 unauthenticated(&parts)
730}
731
732#[derive(Clone)]
735pub(crate) enum Requirement {
736 Gate(String),
737 Role(String),
738 Permission(String),
739 Ability(String),
740}
741
742pub(crate) async fn require(requirement: Arc<Requirement>, req: Request, next: Next) -> Response {
745 let Some(user) = current(req.extensions()) else {
746 let (parts, _) = req.into_parts();
747 return unauthenticated(&parts);
748 };
749 let allowed = match requirement.as_ref() {
750 Requirement::Gate(gate) => match user.allows_async(gate).await {
751 Ok(allowed) => allowed,
752 Err(err) => return err.into_response(),
753 },
754 Requirement::Role(role) => user.has_role(role),
755 Requirement::Permission(permission) => user.allows(permission),
756 Requirement::Ability(ability) => user.token_can(ability),
757 };
758 if allowed {
759 next.run(req).await
760 } else {
761 Error::Forbidden.into_response()
762 }
763}
764
765pub(crate) async fn require_verified(req: Request, next: Next) -> Response {
767 let Some(user) = current(req.extensions()) else {
768 let (parts, _) = req.into_parts();
769 return unauthenticated(&parts);
770 };
771 if user.email_verified_at.is_some() {
772 return next.run(req).await;
773 }
774 if wants_json(req.headers()) || user_via_token(req.extensions()) {
775 let body = serde_json::json!({ "message": "Your email address is not verified." });
776 return (StatusCode::FORBIDDEN, axum::Json(body)).into_response();
777 }
778 let notice = path_or(
779 req.extensions().get::<AppState>(),
780 "verification.notice",
781 "/verify-email",
782 );
783 if Htmx::from_headers(req.headers()).request {
784 return HxRedirect(notice).into_response();
785 }
786 Redirect::to(¬ice).into_response()
787}
788
789pub(crate) fn user_via_token(extensions: &axum::http::Extensions) -> bool {
790 extensions
791 .get::<CurrentUser>()
792 .is_some_and(|c| c.token_id.is_some() || c.device.is_some())
793}
794
795pub(crate) async fn guest_only(req: Request, next: Next) -> Response {
797 if current(req.extensions()).is_none() {
798 return next.run(req).await;
799 }
800 Redirect::to(&path_or(req.extensions().get::<AppState>(), "home", "/")).into_response()
801}
802
803pub(crate) fn intended(session: &Session, fallback: String) -> String {
805 session
806 .pull::<String>(INTENDED)
807 .filter(|path| crate::htmx::is_local_path(path))
808 .unwrap_or(fallback)
809}
810
811#[cfg(test)]
812mod tests {
813 use super::*;
814
815 #[test]
816 fn fingerprints_are_short_and_stable() {
817 let a = fingerprint("$argon2id$v=19$abc");
818 assert_eq!(a.len(), 32);
819 assert_eq!(a, fingerprint("$argon2id$v=19$abc"));
820 assert_ne!(a, fingerprint("$argon2id$v=19$abd"));
821 }
822}