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 signed_in_layout(state: &AppState) -> &'static str {
255 if state.views.exists("layouts/app.html") {
256 "layouts/app.html"
257 } else {
258 "renox/auth/layout.html"
259 }
260}
261
262pub(crate) fn current_user_id() -> Option<i64> {
263 crate::context::get::<CurrentGrants>().map(|current| current.user_id)
264}
265
266fn current_grants(user_id: i64) -> Option<Arc<Grants>> {
267 crate::context::get::<CurrentGrants>()
268 .filter(|current| current.user_id == user_id)
269 .map(|current| current.grants)
270}
271
272pub(crate) type AsyncGate = Arc<
273 dyn Fn(
274 User,
275 AppState,
276 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<bool>> + Send>>
277 + Send
278 + Sync,
279>;
280
281#[derive(Clone)]
284pub(crate) struct CurrentUser {
285 pub user: Option<Arc<User>>,
286 pub gates: Gates,
287 pub token_id: Option<i64>,
290 pub abilities: Option<Arc<Vec<String>>>,
293 pub device: Option<Arc<Device>>,
295 pub grants: Arc<Grants>,
296}
297
298#[derive(Clone)]
302pub struct AuthUser {
303 user: Arc<User>,
304 gates: Gates,
305 state: Option<AppState>,
306 token_id: Option<i64>,
307 abilities: Option<Arc<Vec<String>>>,
308 grants: Arc<Grants>,
309 role_names: std::sync::OnceLock<Vec<String>>,
311}
312
313impl Deref for AuthUser {
314 type Target = User;
315
316 fn deref(&self) -> &User {
317 &self.user
318 }
319}
320
321impl AuthUser {
322 pub fn token_id(&self) -> Option<i64> {
326 self.token_id
327 }
328
329 pub fn token_can(&self, ability: &str) -> bool {
333 self.abilities
334 .as_ref()
335 .is_none_or(|list| list.iter().any(|a| a == ability || a == "*"))
336 }
337
338 pub fn has_role(&self, role: &str) -> bool {
342 self.grants.has_role(role)
343 }
344
345 pub fn has_permission(&self, permission: &str) -> bool {
349 self.grants.has_permission(permission)
350 }
351
352 pub fn has_permission_anywhere(&self, permission: &str) -> bool {
359 self.grants.has_permission_anywhere(permission)
360 }
361
362 pub fn has_role_in(&self, role: &str, scope: &permissions::Scope) -> bool {
365 self.grants.has_role_in(role, Some(scope))
366 }
367
368 pub fn has_permission_in(&self, permission: &str, scope: &permissions::Scope) -> bool {
372 self.grants.has_permission_in(permission, Some(scope))
373 }
374
375 pub fn scopes_with<M: crate::db::Model>(
379 &self,
380 permission: &str,
381 ) -> permissions::Scopes<M::Key> {
382 self.grants.scopes_with::<M>(permission)
383 }
384
385 pub fn role_names(&self) -> &[String] {
389 self.role_names.get_or_init(|| self.grants.roles())
390 }
391
392 pub fn can(&self, ability: &str, target: &impl Policy) -> bool {
395 self.before(ability)
396 .unwrap_or_else(|| target.allows(&self.user, ability))
397 }
398
399 fn before(&self, ability: &str) -> Option<bool> {
400 self.gates
401 .before
402 .as_ref()
403 .and_then(|before| before(&self.user, ability))
404 }
405
406 pub fn authorize(&self, ability: &str, target: &impl Policy) -> Result {
408 if self.can(ability, target) {
409 Ok(())
410 } else {
411 Err(Error::Forbidden)
412 }
413 }
414
415 pub fn allows(&self, gate: &str) -> bool {
419 self.gates.check(&self.user, &self.grants, gate)
420 }
421
422 pub fn gate(&self, gate: &str) -> Result {
424 if self.allows(gate) {
425 Ok(())
426 } else {
427 Err(Error::Forbidden)
428 }
429 }
430
431 pub async fn allows_async(&self, gate: &str) -> Result<bool> {
435 if let Some(allowed) = self.before(gate) {
436 return Ok(allowed);
437 }
438 if self.gates.gates.contains_key(gate) || self.grants.has_permission(gate) {
439 return Ok(self.allows(gate));
440 }
441 let Some(state) = &self.state else {
442 return Ok(false);
443 };
444 match state.async_gates.get(gate) {
445 Some(check) => check(self.user.as_ref().clone(), state.clone()).await,
446 None => Ok(false),
447 }
448 }
449
450 pub async fn gate_async(&self, gate: &str) -> Result {
452 if self.allows_async(gate).await? {
453 Ok(())
454 } else {
455 Err(Error::Forbidden)
456 }
457 }
458
459 pub fn user(&self) -> &User {
461 &self.user
462 }
463}
464
465impl<S: Send + Sync> FromRequestParts<S> for AuthUser {
466 type Rejection = Response;
467
468 async fn from_request_parts(parts: &mut Parts, _: &S) -> std::result::Result<Self, Response> {
469 match current(&parts.extensions) {
470 Some(user) => Ok(user),
471 None => Err(unauthenticated(parts)),
472 }
473 }
474}
475
476impl<S: Send + Sync> OptionalFromRequestParts<S> for AuthUser {
477 type Rejection = Infallible;
478
479 async fn from_request_parts(
480 parts: &mut Parts,
481 _: &S,
482 ) -> std::result::Result<Option<Self>, Infallible> {
483 Ok(current(&parts.extensions))
484 }
485}
486
487pub(crate) fn auth_user_of(current: &CurrentUser, state: &AppState) -> Option<AuthUser> {
490 Some(AuthUser {
491 user: current.user.clone()?,
492 gates: current.gates.clone(),
493 state: Some(state.clone()),
494 token_id: current.token_id,
495 abilities: current.abilities.clone(),
496 grants: current.grants.clone(),
497 role_names: std::sync::OnceLock::new(),
498 })
499}
500
501fn current(extensions: &axum::http::Extensions) -> Option<AuthUser> {
502 let current = extensions.get::<CurrentUser>()?;
503 Some(AuthUser {
504 user: current.user.clone()?,
505 gates: current.gates.clone(),
506 state: extensions.get::<AppState>().cloned(),
507 token_id: current.token_id,
508 abilities: current.abilities.clone(),
509 grants: current.grants.clone(),
510 role_names: std::sync::OnceLock::new(),
511 })
512}
513
514pub fn login(session: &Session, user: &User, remember: Option<std::time::Duration>) -> Result {
518 session.regenerate_token();
519 session.put(AUTH_ID, user.id)?;
520 session.put(AUTH_HASH, fingerprint(&user.password))?;
521 session.put(AUTH_AT, unix_millis())?;
522 session.put(AUTH_SID, crate::crypto::random_token())?;
523 if let Some(lifetime) = remember {
524 session.set_lifetime(lifetime);
525 }
526 Ok(())
527}
528
529pub async fn logout(db: &Db, session: &Session) -> Result {
534 match (session.get::<i64>(AUTH_ID), session.get::<String>(AUTH_SID)) {
535 (Some(_), Some(sid)) => revoke_session(db, session, &sid).await?,
536 (Some(id), None) => {
538 user::revoke_sessions(db, id).await?;
539 }
540 _ => {}
541 }
542 session.flush();
543 Ok(())
544}
545
546pub async fn logout_other_devices(db: &Db, session: &Session, user: &User) -> Result {
549 let cut_off = user::revoke_sessions(db, user.id).await?;
550 let lifetime = session
553 .lifetime()
554 .map(|minutes| std::time::Duration::from_secs(minutes * 60));
555 login(session, user, lifetime)?;
556 session.put(AUTH_AT, cut_off + 1)?;
557 Ok(())
558}
559
560pub async fn change_password(
563 db: &Db,
564 session: &Session,
565 user: &mut User,
566 password: &str,
567) -> Result {
568 user.set_password(db, password).await?;
569 logout_other_devices(db, session, user).await
570}
571
572async fn revoke_session(db: &Db, session: &Session, sid: &str) -> Result {
574 let minutes = session.lifetime().unwrap_or(60 * 24 * 30);
575 let expires = crate::db::now() + chrono::Duration::minutes(minutes as i64);
576 crate::db::sql("DELETE FROM revoked_sessions WHERE expires_at < ?")
577 .bind(crate::db::now())
578 .execute(db)
579 .await?;
580 crate::db::sql(
581 "INSERT INTO revoked_sessions (id, expires_at) SELECT ?, ? \
582 WHERE NOT EXISTS (SELECT 1 FROM revoked_sessions WHERE id = ?)",
583 )
584 .bind(sid)
585 .bind(expires)
586 .bind(sid)
587 .execute(db)
588 .await?;
589 Ok(())
590}
591
592pub(crate) fn unix_millis() -> i64 {
593 crate::clock::unix_millis()
594}
595
596fn fingerprint(password_hash: &str) -> String {
599 use sha2::{Digest, Sha256};
600 let digest = Sha256::digest(password_hash.as_bytes());
601 digest.iter().take(16).map(|b| format!("{b:02x}")).collect()
602}
603
604pub(crate) async fn middleware(
606 axum::extract::State(state): axum::extract::State<AppState>,
607 mut req: Request,
608 next: Next,
609) -> Response {
610 let bearer = req
611 .headers()
612 .get(AUTHORIZATION)
613 .and_then(|v| v.to_str().ok())
614 .and_then(|v| v.strip_prefix("Bearer "))
615 .map(str::to_owned);
616 let session = req.extensions().get::<Session>().cloned();
617 let mut device = None;
618 let (user, token) = match (&bearer, &session) {
619 (Some(bearer), _) if bearer.trim().starts_with('d') => {
620 match device::authenticate(&state.db, bearer.trim()).await {
621 Ok(found) => device = found.map(Arc::new),
622 Err(err) => tracing::error!(error = ?err, "could not check the device token"),
623 }
624 (None, None)
625 }
626 (Some(bearer), _) => match tokens::authenticate(&state.db, bearer.trim()).await {
629 Ok(Some((user, token))) => (Some(user), Some(token)),
630 Ok(None) => (None, None),
631 Err(err) => {
632 tracing::error!(error = ?err, "could not check the API token");
633 (None, None)
634 }
635 },
636 (None, Some(session)) => (resolve(&state, session).await, None),
637 (None, None) => (None, None),
638 };
639 let grants = match &user {
640 Some(user) if state.gates.permissions => {
641 match permissions::grants(&state.db, user.id).await {
642 Ok(grants) => grants,
643 Err(err) => {
644 tracing::error!(error = ?err, "could not load the user's roles");
645 Grants::default()
646 }
647 }
648 }
649 _ => Grants::default(),
650 };
651 let grants = Arc::new(grants);
652 if let Some(user) = &user {
653 crate::context::set(CurrentGrants {
656 user_id: user.id,
657 grants: grants.clone(),
658 });
659 }
660 req.extensions_mut().insert(CurrentUser {
661 user: user.map(Arc::new),
662 gates: state.gates.clone(),
663 token_id: token.as_ref().map(|t| t.0),
664 abilities: token.and_then(|t| t.1).map(Arc::new),
665 device,
666 grants,
667 });
668 req.extensions_mut().insert(state);
669 next.run(req).await
670}
671
672async fn resolve(state: &AppState, session: &Session) -> Option<User> {
673 let id: i64 = session.get(AUTH_ID)?;
674 let hash: String = session.get(AUTH_HASH).unwrap_or_default();
675 let logged_in_at: i64 = session.get(AUTH_AT).unwrap_or(0);
676 let sid: String = session.get(AUTH_SID).unwrap_or_default();
677 match User::find_with_revocation(&state.db, id, &sid).await {
678 Ok(Some((user, revoked_at, session_revoked)))
679 if constant_time_eq(&fingerprint(&user.password), &hash)
680 && (revoked_at == 0 || logged_in_at > revoked_at)
681 && !session_revoked =>
682 {
683 Some(user)
684 }
685 Ok(_) => {
686 session.remove(AUTH_ID);
689 session.remove(AUTH_HASH);
690 session.remove(AUTH_AT);
691 session.remove(AUTH_SID);
692 None
693 }
694 Err(err) => {
695 tracing::error!(error = ?err, "could not load the logged-in user");
696 None
697 }
698 }
699}
700
701fn wants_json(headers: &axum::http::HeaderMap) -> bool {
702 headers
703 .get(ACCEPT)
704 .and_then(|v| v.to_str().ok())
705 .is_some_and(|v| v.contains("application/json"))
706}
707
708fn path_or(state: Option<&AppState>, route: &str, fallback: &str) -> String {
709 state
710 .and_then(|s| s.url(route, &[]).ok())
711 .unwrap_or_else(|| fallback.to_owned())
712}
713
714fn unauthenticated(parts: &Parts) -> Response {
716 if wants_json(&parts.headers) || parts.headers.contains_key(AUTHORIZATION) {
717 let body = serde_json::json!({ "message": "Unauthenticated." });
718 return (StatusCode::UNAUTHORIZED, axum::Json(body)).into_response();
719 }
720 let login = path_or(parts.extensions.get::<AppState>(), "login", "/login");
721 if let (Some(session), &Method::GET) = (parts.extensions.get::<Session>(), &parts.method) {
722 let intended = parts
723 .uri
724 .path_and_query()
725 .map(|p| p.as_str().to_owned())
726 .unwrap_or_else(|| "/".into());
727 let _ = session.put(INTENDED, intended);
728 }
729 if Htmx::from_headers(&parts.headers).request {
730 return HxRedirect(login).into_response();
731 }
732 Redirect::to(&login).into_response()
733}
734
735pub(crate) async fn require_auth(req: Request, next: Next) -> Response {
737 if current(req.extensions()).is_some() {
738 return next.run(req).await;
739 }
740 let (parts, _) = req.into_parts();
741 unauthenticated(&parts)
742}
743
744#[derive(Clone)]
747pub(crate) enum Requirement {
748 Gate(String),
749 Role(String),
750 Permission(String),
751 Ability(String),
752}
753
754pub(crate) async fn require(requirement: Arc<Requirement>, req: Request, next: Next) -> Response {
757 let Some(user) = current(req.extensions()) else {
758 let (parts, _) = req.into_parts();
759 return unauthenticated(&parts);
760 };
761 let allowed = match requirement.as_ref() {
762 Requirement::Gate(gate) => match user.allows_async(gate).await {
763 Ok(allowed) => allowed,
764 Err(err) => return err.into_response(),
765 },
766 Requirement::Role(role) => user.has_role(role),
767 Requirement::Permission(permission) => user.allows(permission),
768 Requirement::Ability(ability) => user.token_can(ability),
769 };
770 if allowed {
771 next.run(req).await
772 } else {
773 Error::Forbidden.into_response()
774 }
775}
776
777pub(crate) async fn require_verified(req: Request, next: Next) -> Response {
779 let Some(user) = current(req.extensions()) else {
780 let (parts, _) = req.into_parts();
781 return unauthenticated(&parts);
782 };
783 if user.email_verified_at.is_some() {
784 return next.run(req).await;
785 }
786 if wants_json(req.headers()) || user_via_token(req.extensions()) {
787 let body = serde_json::json!({ "message": "Your email address is not verified." });
788 return (StatusCode::FORBIDDEN, axum::Json(body)).into_response();
789 }
790 let notice = path_or(
791 req.extensions().get::<AppState>(),
792 "verification.notice",
793 "/verify-email",
794 );
795 if Htmx::from_headers(req.headers()).request {
796 return HxRedirect(notice).into_response();
797 }
798 Redirect::to(¬ice).into_response()
799}
800
801pub(crate) fn user_via_token(extensions: &axum::http::Extensions) -> bool {
802 extensions
803 .get::<CurrentUser>()
804 .is_some_and(|c| c.token_id.is_some() || c.device.is_some())
805}
806
807pub(crate) async fn guest_only(req: Request, next: Next) -> Response {
809 if current(req.extensions()).is_none() {
810 return next.run(req).await;
811 }
812 Redirect::to(&path_or(req.extensions().get::<AppState>(), "home", "/")).into_response()
813}
814
815pub(crate) fn intended(session: &Session, fallback: String) -> String {
817 session
818 .pull::<String>(INTENDED)
819 .filter(|path| crate::htmx::is_local_path(path))
820 .unwrap_or(fallback)
821}
822
823#[cfg(test)]
824mod tests {
825 use super::*;
826
827 #[test]
828 fn fingerprints_are_short_and_stable() {
829 let a = fingerprint("$argon2id$v=19$abc");
830 assert_eq!(a.len(), 32);
831 assert_eq!(a, fingerprint("$argon2id$v=19$abc"));
832 assert_ne!(a, fingerprint("$argon2id$v=19$abd"));
833 }
834}